Massive whitespace replacement (kill trailing spaces & spaces instead of tabs)
diff --git a/org.eclipse.babel.build.ant/src/org/eclipse/babel/build/ant/BuildTask.java b/org.eclipse.babel.build.ant/src/org/eclipse/babel/build/ant/BuildTask.java
index 00c8876..a3dc010 100644
--- a/org.eclipse.babel.build.ant/src/org/eclipse/babel/build/ant/BuildTask.java
+++ b/org.eclipse.babel.build.ant/src/org/eclipse/babel/build/ant/BuildTask.java
@@ -21,153 +21,159 @@
import org.eclipse.babel.build.core.coverage.LanguagePackCoverageReport;
import org.eclipse.babel.build.core.languagepack.LanguagePack;
-
/**
- * Task used to execute the tool from an ant build script.
- * Builds a {@link org.eclipse.babel.build.core.LazyConfiguration} then
- * passes it to {@link org.eclipse.babel.build.core.languagepack.LanguagePack}.
+ * Task used to execute the tool from an ant build script. Builds a
+ * {@link org.eclipse.babel.build.core.LazyConfiguration} then passes it to
+ * {@link org.eclipse.babel.build.core.languagepack.LanguagePack}.
*
- * <p>All methods are called reflectively by ant depending on attributes
- * supplied by the user in the build file. For example:
+ * <p>
+ * All methods are called reflectively by ant depending on attributes supplied
+ * by the user in the build file. For example:
+ *
* <pre>
* <nlsbuild
- * eclipse="/tmp/eclipse.zip"
- * translations="/tmp/translations"
- * locales="en,zh-TW"
+ * eclipse="/tmp/eclipse.zip"
+ * translations="/tmp/translations"
+ * locales="en,zh-TW"
* />
* </pre>
*
* Would result in the following calls:
+ *
* <pre>
* BuildTask nlsbuild = new BuildTask();
- * nlsbuild.setEclipse("/tmp/eclipse.zip");
- * nlsbuild.setTranslations("/tmp/translations");
- * nlsbuild.setLocales("en,zh_TW");
+ * nlsbuild.setEclipse("/tmp/eclipse.zip");
+ * nlsbuild.setTranslations("/tmp/translations");
+ * nlsbuild.setLocales("en,zh_TW");
* nlsbuild.execute();
* </pre>
*/
public class BuildTask extends Task {
- public static class Exclude{
- String fileType = "";
-
- public void setFileType(String fileType){
- this.fileType = fileType;
- }
- }
-
- public static class Excludes{
- List<Exclude> fileTypes = new LinkedList<Exclude>();
-
- public Exclude createExclude(){
- Exclude exclude = new Exclude();
- fileTypes.add(exclude);
- return exclude;
- }
- }
-
- private final LazyConfiguration config = new LazyConfiguration();
- private CoverageReport coverageReport = new CoverageReport();
- private Excludes excludes = new Excludes();
-
-
- /**
- * Constructs a new BuildTask. Required by ant.
- */
- public BuildTask(){
- super();
- }
-
- /**
- * Sets the working directory for the build. Called by ant.
- *
- * @param file Path to the working directory.
- */
- public void setWorkingDirectory(String file){
- config.setWorkingDirectory(new File(file));
- }
-
- /**
- * Sets the eclipse archive to be used. Called by ant.
- *
- * @param file Path to the Eclipse Archive.
- */
- public void setEclipse(String file){
- config.setArchiveRoot(new File(file));
- }
-
- public void setLongReport(boolean longReport){
- config.setLongReport(longReport);
- }
-
- public void setIncludeXmlReport(boolean xml){
- config.setIncludeXmlReport(xml);
- }
-
- /**
- * Sets the locales to be used. Called by ant.
- *
- * @param specifier List of locales to be used (of the format "en,zh_TW").
- */
- public void setLocales(String specifier){
- config.addLocales(Configuration.helper.getLocales(specifier));
- config.addLocaleGroups(Configuration.helper.getLocaleGroups(specifier));
- }
-
- /**
- * Sets the translations to be used. Called by ant.
- *
- * @param file Path to the translations.
- */
- public void setTranslations(String file){
- config.setTranslationsRoot(new File(file));
- }
-
- /**
- * Sets whether to include pseudo-translations in the generated
- * translation catalog. Called by ant.
- *
- * @param include Whether to include pseudo-translations.
- */
- public void setIncludePseudoTranslations(boolean include){
- config.setIncludePseudoTranslations(include);
- }
-
- public CoverageReport createCoverageReport(){
- coverageReport = new CoverageReport();
- return coverageReport;
- }
-
- public Excludes createExcludes(){
- excludes = new Excludes();
- return excludes;
- }
-
- /**
- * Build the translation catalog. Called by ant.
- */
- @Override
- public void execute() throws BuildException {
- try {
- for(Ignore ignore : coverageReport.ignores()){
- config.addFilter(ignore.toFilter());
- }
-
- for(Exclude exclude : excludes.fileTypes){
- config.addExclude(exclude.fileType);
-
- }
-
- config.validate();
- System.out.println("Parsing language pack...");
- LanguagePack languagePack = new LanguagePack(config);
- LanguagePackCoverageReport coverage = languagePack.generate();
- System.out.println("Printing coverage report...");
- Configuration.helper.printLanguagePackResult(config, coverage);
- System.out.println("DONE");
- } catch (Exception e) {
- System.err.println(e.getMessage());
- throw new BuildException(e);
- }
- }
+ public static class Exclude {
+ String fileType = "";
+
+ public void setFileType(String fileType) {
+ this.fileType = fileType;
+ }
+ }
+
+ public static class Excludes {
+ List<Exclude> fileTypes = new LinkedList<Exclude>();
+
+ public Exclude createExclude() {
+ Exclude exclude = new Exclude();
+ fileTypes.add(exclude);
+ return exclude;
+ }
+ }
+
+ private final LazyConfiguration config = new LazyConfiguration();
+ private CoverageReport coverageReport = new CoverageReport();
+ private Excludes excludes = new Excludes();
+
+ /**
+ * Constructs a new BuildTask. Required by ant.
+ */
+ public BuildTask() {
+ super();
+ }
+
+ /**
+ * Sets the working directory for the build. Called by ant.
+ *
+ * @param file
+ * Path to the working directory.
+ */
+ public void setWorkingDirectory(String file) {
+ config.setWorkingDirectory(new File(file));
+ }
+
+ /**
+ * Sets the eclipse archive to be used. Called by ant.
+ *
+ * @param file
+ * Path to the Eclipse Archive.
+ */
+ public void setEclipse(String file) {
+ config.setArchiveRoot(new File(file));
+ }
+
+ public void setLongReport(boolean longReport) {
+ config.setLongReport(longReport);
+ }
+
+ public void setIncludeXmlReport(boolean xml) {
+ config.setIncludeXmlReport(xml);
+ }
+
+ /**
+ * Sets the locales to be used. Called by ant.
+ *
+ * @param specifier
+ * List of locales to be used (of the format "en,zh_TW").
+ */
+ public void setLocales(String specifier) {
+ config.addLocales(Configuration.helper.getLocales(specifier));
+ config.addLocaleGroups(Configuration.helper.getLocaleGroups(specifier));
+ }
+
+ /**
+ * Sets the translations to be used. Called by ant.
+ *
+ * @param file
+ * Path to the translations.
+ */
+ public void setTranslations(String file) {
+ config.setTranslationsRoot(new File(file));
+ }
+
+ /**
+ * Sets whether to include pseudo-translations in the generated translation
+ * catalog. Called by ant.
+ *
+ * @param include
+ * Whether to include pseudo-translations.
+ */
+ public void setIncludePseudoTranslations(boolean include) {
+ config.setIncludePseudoTranslations(include);
+ }
+
+ public CoverageReport createCoverageReport() {
+ coverageReport = new CoverageReport();
+ return coverageReport;
+ }
+
+ public Excludes createExcludes() {
+ excludes = new Excludes();
+ return excludes;
+ }
+
+ /**
+ * Build the translation catalog. Called by ant.
+ */
+ @Override
+ public void execute() throws BuildException {
+ try {
+ for (Ignore ignore : coverageReport.ignores()) {
+ config.addFilter(ignore.toFilter());
+ }
+
+ for (Exclude exclude : excludes.fileTypes) {
+ config.addExclude(exclude.fileType);
+
+ }
+
+ config.validate();
+ System.out.println("Parsing language pack...");
+ LanguagePack languagePack = new LanguagePack(config);
+ LanguagePackCoverageReport coverage = languagePack.generate();
+ System.out.println("Printing coverage report...");
+ Configuration.helper.printLanguagePackResult(config, coverage);
+ System.out.println("DONE");
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ throw new BuildException(e);
+ }
+ }
}
diff --git a/org.eclipse.babel.build.ant/src/org/eclipse/babel/build/ant/CoverageReport.java b/org.eclipse.babel.build.ant/src/org/eclipse/babel/build/ant/CoverageReport.java
index c2b4474..684231b 100644
--- a/org.eclipse.babel.build.ant/src/org/eclipse/babel/build/ant/CoverageReport.java
+++ b/org.eclipse.babel.build.ant/src/org/eclipse/babel/build/ant/CoverageReport.java
@@ -14,16 +14,16 @@
import java.util.List;
public class CoverageReport {
- private final List<Ignore> ignores = new LinkedList<Ignore>();
-
- public Ignore createIgnore(){
- Ignore ignore = new Ignore();
- ignores.add(ignore);
- return ignore;
- }
-
- public List<Ignore> ignores(){
- return ignores;
- }
+ private final List<Ignore> ignores = new LinkedList<Ignore>();
+
+ public Ignore createIgnore() {
+ Ignore ignore = new Ignore();
+ ignores.add(ignore);
+ return ignore;
+ }
+
+ public List<Ignore> ignores() {
+ return ignores;
+ }
}
diff --git a/org.eclipse.babel.build.ant/src/org/eclipse/babel/build/ant/Ignore.java b/org.eclipse.babel.build.ant/src/org/eclipse/babel/build/ant/Ignore.java
index 7f38337..42d0e58 100644
--- a/org.eclipse.babel.build.ant/src/org/eclipse/babel/build/ant/Ignore.java
+++ b/org.eclipse.babel.build.ant/src/org/eclipse/babel/build/ant/Ignore.java
@@ -13,13 +13,13 @@
import org.eclipse.babel.build.core.Filter;
public class Ignore {
- private String pattern;
-
- public void setPattern(String pattern){
- this.pattern = pattern;
- }
-
- public Filter toFilter(){
- return new Filter(pattern);
- }
+ private String pattern;
+
+ public void setPattern(String pattern) {
+ this.pattern = pattern;
+ }
+
+ public Filter toFilter() {
+ return new Filter(pattern);
+ }
}
diff --git a/org.eclipse.babel.build.ant/src/org/eclipse/babel/build/ant/test/TestBuildTask.java b/org.eclipse.babel.build.ant/src/org/eclipse/babel/build/ant/test/TestBuildTask.java
index a765c68..a966ee1 100644
--- a/org.eclipse.babel.build.ant/src/org/eclipse/babel/build/ant/test/TestBuildTask.java
+++ b/org.eclipse.babel.build.ant/src/org/eclipse/babel/build/ant/test/TestBuildTask.java
@@ -14,28 +14,28 @@
import org.eclipse.babel.build.ant.BuildTask;
-public class TestBuildTask extends TestCase{
- public void testBuildTask() throws Exception {
- BuildTask buildTask = new BuildTask();
- buildTask.setWorkingDirectory("/work/nls/w");
- buildTask.setEclipse("/work/nls/testing/eclipse-SDK-3.4M5-win32.zip");
- buildTask
- .setTranslations("/Users/aaron/Desktop/nls/IES_3.3/piiDocTransDir");
- buildTask.setLocales("gr1");
- buildTask.createCoverageReport().createIgnore().setPattern(
- "^META-INF/.*");
- buildTask.execute();
- }
+public class TestBuildTask extends TestCase {
+ public void testBuildTask() throws Exception {
+ BuildTask buildTask = new BuildTask();
+ buildTask.setWorkingDirectory("/work/nls/w");
+ buildTask.setEclipse("/work/nls/testing/eclipse-SDK-3.4M5-win32.zip");
+ buildTask
+ .setTranslations("/Users/aaron/Desktop/nls/IES_3.3/piiDocTransDir");
+ buildTask.setLocales("gr1");
+ buildTask.createCoverageReport().createIgnore()
+ .setPattern("^META-INF/.*");
+ buildTask.execute();
+ }
- public void testBuildTask_missingEclipse() throws Exception {
- BuildTask buildTask = new BuildTask();
- buildTask.setWorkingDirectory("/work/nls/w");
- buildTask.setEclipse("/this/path/doesnt/exist");
- buildTask
- .setTranslations("/Users/aaron/Desktop/nls/IES_3.3/piiDocTransDir");
- buildTask.setLocales("gr1");
- buildTask.createCoverageReport().createIgnore().setPattern(
- "^META-INF/.*");
- buildTask.execute();
- }
+ public void testBuildTask_missingEclipse() throws Exception {
+ BuildTask buildTask = new BuildTask();
+ buildTask.setWorkingDirectory("/work/nls/w");
+ buildTask.setEclipse("/this/path/doesnt/exist");
+ buildTask
+ .setTranslations("/Users/aaron/Desktop/nls/IES_3.3/piiDocTransDir");
+ buildTask.setLocales("gr1");
+ buildTask.createCoverageReport().createIgnore()
+ .setPattern("^META-INF/.*");
+ buildTask.execute();
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/annotations/Requirement.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/annotations/Requirement.java
index 92b9e61..2736612 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/annotations/Requirement.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/annotations/Requirement.java
@@ -11,5 +11,5 @@
package org.eclipse.babel.build.annotations;
public @interface Requirement {
- int[] id();
+ int[] id();
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/CommandLineConfiguration.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/CommandLineConfiguration.java
index 91a1ffa..e055546 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/CommandLineConfiguration.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/CommandLineConfiguration.java
@@ -23,209 +23,217 @@
import org.eclipse.babel.build.core.exceptions.MissingLocationException;
import org.eclipse.babel.build.core.translationcatalogue.TranslationCatalogue;
-
-
/**
* Configuration which derives it's parameters from parsing a command line.
*/
public class CommandLineConfiguration implements Configuration {
- public class Times{
- public long eclipseInstallPopulation;
- public long translationCataloguePopulation;
- public long languagePackGeneration;
- }
-
- private EclipseTarget eclipseInstall = null;
- private TranslationCatalogue translationCatalogue = null;
- private final Set<LocaleProxy> locales;
- private final Set<LocaleGroup> localeGroups;
- private final File workingDirectory;
- private final File eclipseRoot;
- private final File translationsRoot;
- final Times times = new Times();
- private File report;
- private final Set<String> excludeList;
- private List<Filter> reportFilters;
-
- private final boolean includeXmlReport;
- private final boolean longReport;
- private String localeExtension;
-
- final static String TOKEN = Messages.getString("Characters_locale_token"); //$NON-NLS-1$
-
- public CommandLineConfiguration(String... args) {
- Options opts = new Options(
- "--working-directory=", "--locales=",
- "--translation-archive=!", "--eclipse-archive=!",
- "--coverage-report=", "--exclude-list=",
- "--report-ignore-list=", "--xml", "--long-report"
- ).parse(args);
-
- Set<LocaleProxy> locales = helper.getLocales(opts.get("--locales"));
- Set<LocaleGroup> localeGroups = helper.getLocaleGroups(opts.get("--locales"));
- Set<String> excludeList = getExcludeList(opts.get("--exclude-list"));
-
- this.eclipseRoot = new File(opts.get("--eclipse-archive"));
- this.locales = locales;
- this.localeGroups = localeGroups;
- this.translationsRoot = new File(opts.get("--translation-archive"));
- this.workingDirectory = new File(opts.get("--working-directory", "."));
-
- this.excludeList = excludeList;
- report = new File(opts.get("--coverage-report", new File(workingDirectory, "coverage.xml").getAbsolutePath()));
-
- if(!report.isAbsolute()){
- report = new File(workingDirectory, report.getPath());
- }
-
- reportFilters = buildFilterList(opts.get("--report-ignore-list", ""));
-
- includeXmlReport = opts.isSet("--xml");
- longReport = opts.isSet("--long-report");
-
- localeExtension = "";
- if (this.locales.size() == 1 && this.localeGroups.isEmpty()) {
- LocaleProxy singleLocale = this.locales.iterator().next();
- localeExtension += Messages.getString("Characters_underscore") + singleLocale.getName(); //$NON-NLS-1$
- }
- }
-
- private List<Filter> buildFilterList(String specifier){
- List<Filter> filters = new LinkedList<Filter>();
-
- for(String filter : specifier.split(" ")){
- filters.add(new Filter(filter));
- }
-
- return filters;
- }
+ public class Times {
+ public long eclipseInstallPopulation;
+ public long translationCataloguePopulation;
+ public long languagePackGeneration;
+ }
- public EclipseTarget eclipseInstall() {
- try {
- if (eclipseInstall == null){
- long startEclipseArchivePopulation = System.currentTimeMillis();
- eclipseInstall = new EclipseTarget(eclipseRoot, this.excludeList);
- System.out.println(Messages.getString("Messages_parsing_eclipse_target")); //$NON-NLS-1$
- eclipseInstall.populatePlugins();
- System.out.println("Plugins: " + eclipseInstall.getPlugins().size() + " Features: " + eclipseInstall.getFeatures().size()); //$NON-NLS-1$ $NON-NLS-2$
- times.eclipseInstallPopulation = System.currentTimeMillis() - startEclipseArchivePopulation;
- }
- } catch (InvalidLocationException i) {
- System.out.println( Messages.getString("Error_invalid_eclipse_target") ); //$NON-NLS-1$
- System.exit(0);
- } catch (MissingLocationException m) {
- System.out.println( Messages.getString("Error_missing_eclipse_target") ); //$NON-NLS-1$
- System.exit(0);
- } catch (InvalidFilenameException i) {
- System.out.println( Messages.getString("Error_invalid_eclipse_target_name") ); //$NON-NLS-1$
- System.exit(0);
- } catch (Exception e) {
- e.printStackTrace();
- System.out.println( Messages.getString("Error_eclipse_target") ); //$NON-NLS-1$
- System.exit(0);
- }
- return eclipseInstall;
- }
-
- public Range compatibilityRange() {
- // TODO Auto-generated method stub
- return null;
- }
+ private EclipseTarget eclipseInstall = null;
+ private TranslationCatalogue translationCatalogue = null;
+ private final Set<LocaleProxy> locales;
+ private final Set<LocaleGroup> localeGroups;
+ private final File workingDirectory;
+ private final File eclipseRoot;
+ private final File translationsRoot;
+ final Times times = new Times();
+ private File report;
+ private final Set<String> excludeList;
+ private List<Filter> reportFilters;
- public List<Filter> filters() {
- return reportFilters;
- }
+ private final boolean includeXmlReport;
+ private final boolean longReport;
+ private String localeExtension;
- public boolean includePseudoTranslations() {
- // TODO Auto-generated method stub
- return false;
- }
+ final static String TOKEN = Messages.getString("Characters_locale_token"); //$NON-NLS-1$
- public boolean includeResource(PluginProxy plugin, ResourceProxy resource) {
- for(Filter filter : reportFilters){
- if(filter.matches(plugin, resource)){
- return filter.isInclusive();
- }
- }
- return true;
- }
+ public CommandLineConfiguration(String... args) {
+ Options opts = new Options("--working-directory=", "--locales=",
+ "--translation-archive=!", "--eclipse-archive=!",
+ "--coverage-report=", "--exclude-list=",
+ "--report-ignore-list=", "--xml", "--long-report").parse(args);
- public Set<LocaleProxy> locales() {
- return locales;
- }
+ Set<LocaleProxy> locales = helper.getLocales(opts.get("--locales"));
+ Set<LocaleGroup> localeGroups = helper.getLocaleGroups(opts
+ .get("--locales"));
+ Set<String> excludeList = getExcludeList(opts.get("--exclude-list"));
+ this.eclipseRoot = new File(opts.get("--eclipse-archive"));
+ this.locales = locales;
+ this.localeGroups = localeGroups;
+ this.translationsRoot = new File(opts.get("--translation-archive"));
+ this.workingDirectory = new File(opts.get("--working-directory", "."));
- public Set<LocaleGroup> localeGroups() {
- return localeGroups;
- }
+ this.excludeList = excludeList;
+ report = new File(opts.get("--coverage-report", new File(
+ workingDirectory, "coverage.xml").getAbsolutePath()));
- public Set<String> excludeList() {
- return excludeList;
- }
+ if (!report.isAbsolute()) {
+ report = new File(workingDirectory, report.getPath());
+ }
- public File reportLocation() {
- return report;
- }
+ reportFilters = buildFilterList(opts.get("--report-ignore-list", ""));
- public Date timestamp() {
- return new Date();
- }
+ includeXmlReport = opts.isSet("--xml");
+ longReport = opts.isSet("--long-report");
- public TranslationCatalogue translations() {
- if (translationCatalogue == null){
- try {
- if (localeGroups.isEmpty()) {
- translationCatalogue = new TranslationCatalogue(translationsRoot, locales);
- } else {
- locales.clear();
- translationCatalogue = new TranslationCatalogue(translationsRoot, localeGroups);
- locales.addAll(translationCatalogue.getAllLocales());
- }
- } catch (MissingLocationException m) {
- System.out.println( Messages.getString("Error_missing_translation_catalogue") ); //$NON-NLS-1$
- System.exit(0);
- } catch (InvalidLocationException i) {
- System.out.println( i.getMessage() );
- System.exit(0);
- } catch (InvalidFilenameException i) {
- System.out.println( Messages.getString("Error_invalid_translation_catalogue_name") ); //$NON-NLS-1$
- System.exit(0);
- }
- }
- return translationCatalogue;
- }
+ localeExtension = "";
+ if (this.locales.size() == 1 && this.localeGroups.isEmpty()) {
+ LocaleProxy singleLocale = this.locales.iterator().next();
+ localeExtension += Messages.getString("Characters_underscore") + singleLocale.getName(); //$NON-NLS-1$
+ }
+ }
- public File workingDirectory() {
- return workingDirectory;
- }
+ private List<Filter> buildFilterList(String specifier) {
+ List<Filter> filters = new LinkedList<Filter>();
- private static Set<String> getExcludeList(String specifier){
- Set<String> excludeList = new HashSet<String>();
-
- if(null == specifier){
- return excludeList;
- }
-
- for(String suffix : specifier.split( TOKEN )){
- excludeList.add(suffix);
- }
+ for (String filter : specifier.split(" ")) {
+ filters.add(new Filter(filter));
+ }
- return excludeList;
- }
+ return filters;
+ }
- public void notifyProgress(String fragmentName) {
- // TODO Auto-generated method stub
- }
+ public EclipseTarget eclipseInstall() {
+ try {
+ if (eclipseInstall == null) {
+ long startEclipseArchivePopulation = System.currentTimeMillis();
+ eclipseInstall = new EclipseTarget(eclipseRoot,
+ this.excludeList);
+ System.out.println(Messages
+ .getString("Messages_parsing_eclipse_target")); //$NON-NLS-1$
+ eclipseInstall.populatePlugins();
+ System.out
+ .println("Plugins: " + eclipseInstall.getPlugins().size() + " Features: " + eclipseInstall.getFeatures().size()); //$NON-NLS-1$ $NON-NLS-2$
+ times.eclipseInstallPopulation = System.currentTimeMillis()
+ - startEclipseArchivePopulation;
+ }
+ } catch (InvalidLocationException i) {
+ System.out.println(Messages
+ .getString("Error_invalid_eclipse_target")); //$NON-NLS-1$
+ System.exit(0);
+ } catch (MissingLocationException m) {
+ System.out.println(Messages
+ .getString("Error_missing_eclipse_target")); //$NON-NLS-1$
+ System.exit(0);
+ } catch (InvalidFilenameException i) {
+ System.out.println(Messages
+ .getString("Error_invalid_eclipse_target_name")); //$NON-NLS-1$
+ System.exit(0);
+ } catch (Exception e) {
+ e.printStackTrace();
+ System.out.println(Messages.getString("Error_eclipse_target")); //$NON-NLS-1$
+ System.exit(0);
+ }
+ return eclipseInstall;
+ }
- public boolean includeXmlReport() {
- return includeXmlReport;
- }
+ public Range compatibilityRange() {
+ // TODO Auto-generated method stub
+ return null;
+ }
- public boolean longReport() {
- return longReport;
- }
-
- public final String localeExtension() {
- return localeExtension;
- }
+ public List<Filter> filters() {
+ return reportFilters;
+ }
+
+ public boolean includePseudoTranslations() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public boolean includeResource(PluginProxy plugin, ResourceProxy resource) {
+ for (Filter filter : reportFilters) {
+ if (filter.matches(plugin, resource)) {
+ return filter.isInclusive();
+ }
+ }
+ return true;
+ }
+
+ public Set<LocaleProxy> locales() {
+ return locales;
+ }
+
+ public Set<LocaleGroup> localeGroups() {
+ return localeGroups;
+ }
+
+ public Set<String> excludeList() {
+ return excludeList;
+ }
+
+ public File reportLocation() {
+ return report;
+ }
+
+ public Date timestamp() {
+ return new Date();
+ }
+
+ public TranslationCatalogue translations() {
+ if (translationCatalogue == null) {
+ try {
+ if (localeGroups.isEmpty()) {
+ translationCatalogue = new TranslationCatalogue(
+ translationsRoot, locales);
+ } else {
+ locales.clear();
+ translationCatalogue = new TranslationCatalogue(
+ translationsRoot, localeGroups);
+ locales.addAll(translationCatalogue.getAllLocales());
+ }
+ } catch (MissingLocationException m) {
+ System.out.println(Messages
+ .getString("Error_missing_translation_catalogue")); //$NON-NLS-1$
+ System.exit(0);
+ } catch (InvalidLocationException i) {
+ System.out.println(i.getMessage());
+ System.exit(0);
+ } catch (InvalidFilenameException i) {
+ System.out.println(Messages
+ .getString("Error_invalid_translation_catalogue_name")); //$NON-NLS-1$
+ System.exit(0);
+ }
+ }
+ return translationCatalogue;
+ }
+
+ public File workingDirectory() {
+ return workingDirectory;
+ }
+
+ private static Set<String> getExcludeList(String specifier) {
+ Set<String> excludeList = new HashSet<String>();
+
+ if (null == specifier) {
+ return excludeList;
+ }
+
+ for (String suffix : specifier.split(TOKEN)) {
+ excludeList.add(suffix);
+ }
+
+ return excludeList;
+ }
+
+ public void notifyProgress(String fragmentName) {
+ // TODO Auto-generated method stub
+ }
+
+ public boolean includeXmlReport() {
+ return includeXmlReport;
+ }
+
+ public boolean longReport() {
+ return longReport;
+ }
+
+ public final String localeExtension() {
+ return localeExtension;
+ }
}
\ No newline at end of file
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Configuration.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Configuration.java
index c9d9258..a7d595d 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Configuration.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Configuration.java
@@ -26,204 +26,238 @@
import org.eclipse.babel.build.core.reports.XmlCoverageReport;
import org.eclipse.babel.build.core.translationcatalogue.TranslationCatalogue;
-
-
/**
* Defines the parameters which configure a run of the tool.
*/
public interface Configuration {
- public static class helper{
- /**
- * This class should not be instantiated.
- */
- private helper(){}
-
- /**
- * Serializes a given configuration to an output stream so that it can be reused.
- *
- * @param out The output stream to which the configuration should be serialized.
- */
- public static void serialize(OutputStream out){
- // TODO: stub
- }
-
- /**
- * Parses a stored configuration.
- *
- * @param in The input stream from which a configuration should be deserialized.
- * @return The configuration obtained from parsing the provided input stream.
- */
- public static Configuration parse(InputStream in){
- // TODO: stub
- return null;
- }
-
- public static Set<LocaleProxy> parseLocales(String specifier){
- if(null == specifier || "*".equals(specifier)){
- return LocaleProxy.ALL;
- }
-
- Set<LocaleProxy> set = new HashSet<LocaleProxy>();
- for(String name : specifier.split(",")){
- set.add(new LocaleProxy(name));
- }
- return set;
- }
-
- public static void printCoverageReport(CoverageReport report, File file) throws Exception{
-
- FileOutputStream out = new FileOutputStream(file);
- try{
- report.render(out);
- } finally {
- out.close();
- }
- }
-
- public static void printLanguagePackResult(final Configuration config, LanguagePackCoverageReport coverage) throws Exception {
- XmlCoverageReport report = new XmlCoverageReport(config, coverage);
- HtmlCoverageReport htmlReport = new HtmlCoverageReport(config, coverage);
-
- if(config.includeXmlReport()){
- printCoverageReport(report, config.reportLocation());
- }
-
- printCoverageReport(htmlReport, new File(config.reportLocation().getParent(), "coverage.html"));
- }
+ public static class helper {
+ /**
+ * This class should not be instantiated.
+ */
+ private helper() {
+ }
- public static Set<LocaleProxy> getLocales(String specifier){
- if(null == specifier || LocaleGroup.GROUP_ALL.getName().equals(specifier)){
- return LocaleProxy.ALL;
- }
-
- Set<LocaleProxy> locales = new HashSet<LocaleProxy>();
- for(String locale : specifier.split( CommandLineConfiguration.TOKEN )){
- if (! LocaleGroup.isValidGroupName(locale) && !LocaleGroup.isValidGroupFullName(locale)){
- locales.add(new LocaleProxy(locale));
- }
- }
-
- return locales;
- }
+ /**
+ * Serializes a given configuration to an output stream so that it can
+ * be reused.
+ *
+ * @param out
+ * The output stream to which the configuration should be
+ * serialized.
+ */
+ public static void serialize(OutputStream out) {
+ // TODO: stub
+ }
- public static Set<LocaleGroup> getLocaleGroups(String specifier){
- Set<LocaleGroup> set = new HashSet<LocaleGroup>();
- if(null == specifier) {
- return set;
- }
-
- if (LocaleGroup.GROUP_ALL.getName().equals(specifier)){
- set.add(LocaleGroup.GROUP_ALL);
- }
-
- for(String token : specifier.split( CommandLineConfiguration.TOKEN )){
- if (LocaleGroup.isValidGroupName(token)) {
- set.add(LocaleGroup.get(token));
- }
- else if(LocaleGroup.isValidGroupFullName(token)) {
- set.add(LocaleGroup.getByFullName(token));
- }
- }
-
- return set;
- }
- }
-
- /**
- * Retrieve the eclipse install for which the language pack should be generated.
- *
- * @return The eclipse install for which the language pack should be generated.
- */
- public EclipseTarget eclipseInstall();
-
- /**
- * Retrieve the translations from which the translated resources should be retrieved.
- *
- * @return The translations from which the translated resources should be retrieved.
- */
- public TranslationCatalogue translations();
-
- /**
- * Retrieve the timestamp to use in output files.
- *
- * @return Timestamp to use in output files.
- */
- public Date timestamp();
-
- /**
- * Retrieve the working directory into which generated artifacts should be stored.
- *
- * @return The working directory into which generated artifacts should be stored.
- */
- public File workingDirectory();
-
- /**
- * Retrieve whether or not to include pseudo-translations for missing strings in the generated language pack.
- *
- * @return Whether or not to include pseudo-translations for missing strings in the generated lanaguage pack.
- */
- public boolean includePseudoTranslations();
-
- /**
- * Retrieve the range of Eclipse versions the generated lanaguage pack will be compatible with.
- *
- * @return The range of Eclipse versions the generated language pack will be compatible with.
- */
- public Range compatibilityRange();
-
- /**
- * Retrieve the location of where the coverage report should be stored.
- *
- * @return The location to which the coverage report should be stored.
- */
- public File reportLocation();
-
- /**
- * Queries the configuration as to whether a resource should be included in the coverage report.
- *
- * @param resouce The resource whose inclusion is at question.
- * @return Whether or not the resource should be included in the coverage report.
- */
- public boolean includeResource(PluginProxy plugin, ResourceProxy resouce);
-
- /**
- * Retrieve the list of filters which specify which resources should be included in the coverage report.
- *
- * @return The list of filters used to select which resources should be included in the coverage report.
- */
- public List<Filter> filters();
-
- /**
- * Retrieve the set of locales that should be included in the generated language pack.
- *
- * @return The set of locales that should be included in the generated language pack.
- */
- public Set<LocaleProxy> locales();
-
- /**
- * Retrieve the locale groups that should be included in the generated language pack.
- *
- * @return The locale groups that should be included in the generated language pack.
- */
- public Set<LocaleGroup> localeGroups();
-
- /**
- * Retrieve the list of filename suffixes that should be excluded when parsing the eclipse target.
- *
- * @return The list of filename suffixes that should be excluded when parsing the eclipse target.
- */
- public Set<String> excludeList();
-
- /**
- * Provides notification regarding progress.
- *
- * @param fragmentName The name of the plugin/feature for which a fragement is being created.
- */
- public void notifyProgress(String fragmentName);
-
- public boolean includeXmlReport();
-
- public boolean longReport();
-
- public String localeExtension();
+ /**
+ * Parses a stored configuration.
+ *
+ * @param in
+ * The input stream from which a configuration should be
+ * deserialized.
+ * @return The configuration obtained from parsing the provided input
+ * stream.
+ */
+ public static Configuration parse(InputStream in) {
+ // TODO: stub
+ return null;
+ }
+
+ public static Set<LocaleProxy> parseLocales(String specifier) {
+ if (null == specifier || "*".equals(specifier)) {
+ return LocaleProxy.ALL;
+ }
+
+ Set<LocaleProxy> set = new HashSet<LocaleProxy>();
+ for (String name : specifier.split(",")) {
+ set.add(new LocaleProxy(name));
+ }
+ return set;
+ }
+
+ public static void printCoverageReport(CoverageReport report, File file)
+ throws Exception {
+
+ FileOutputStream out = new FileOutputStream(file);
+ try {
+ report.render(out);
+ } finally {
+ out.close();
+ }
+ }
+
+ public static void printLanguagePackResult(final Configuration config,
+ LanguagePackCoverageReport coverage) throws Exception {
+ XmlCoverageReport report = new XmlCoverageReport(config, coverage);
+ HtmlCoverageReport htmlReport = new HtmlCoverageReport(config,
+ coverage);
+
+ if (config.includeXmlReport()) {
+ printCoverageReport(report, config.reportLocation());
+ }
+
+ printCoverageReport(htmlReport, new File(config.reportLocation()
+ .getParent(), "coverage.html"));
+ }
+
+ public static Set<LocaleProxy> getLocales(String specifier) {
+ if (null == specifier
+ || LocaleGroup.GROUP_ALL.getName().equals(specifier)) {
+ return LocaleProxy.ALL;
+ }
+
+ Set<LocaleProxy> locales = new HashSet<LocaleProxy>();
+ for (String locale : specifier
+ .split(CommandLineConfiguration.TOKEN)) {
+ if (!LocaleGroup.isValidGroupName(locale)
+ && !LocaleGroup.isValidGroupFullName(locale)) {
+ locales.add(new LocaleProxy(locale));
+ }
+ }
+
+ return locales;
+ }
+
+ public static Set<LocaleGroup> getLocaleGroups(String specifier) {
+ Set<LocaleGroup> set = new HashSet<LocaleGroup>();
+ if (null == specifier) {
+ return set;
+ }
+
+ if (LocaleGroup.GROUP_ALL.getName().equals(specifier)) {
+ set.add(LocaleGroup.GROUP_ALL);
+ }
+
+ for (String token : specifier.split(CommandLineConfiguration.TOKEN)) {
+ if (LocaleGroup.isValidGroupName(token)) {
+ set.add(LocaleGroup.get(token));
+ } else if (LocaleGroup.isValidGroupFullName(token)) {
+ set.add(LocaleGroup.getByFullName(token));
+ }
+ }
+
+ return set;
+ }
+ }
+
+ /**
+ * Retrieve the eclipse install for which the language pack should be
+ * generated.
+ *
+ * @return The eclipse install for which the language pack should be
+ * generated.
+ */
+ public EclipseTarget eclipseInstall();
+
+ /**
+ * Retrieve the translations from which the translated resources should be
+ * retrieved.
+ *
+ * @return The translations from which the translated resources should be
+ * retrieved.
+ */
+ public TranslationCatalogue translations();
+
+ /**
+ * Retrieve the timestamp to use in output files.
+ *
+ * @return Timestamp to use in output files.
+ */
+ public Date timestamp();
+
+ /**
+ * Retrieve the working directory into which generated artifacts should be
+ * stored.
+ *
+ * @return The working directory into which generated artifacts should be
+ * stored.
+ */
+ public File workingDirectory();
+
+ /**
+ * Retrieve whether or not to include pseudo-translations for missing
+ * strings in the generated language pack.
+ *
+ * @return Whether or not to include pseudo-translations for missing strings
+ * in the generated lanaguage pack.
+ */
+ public boolean includePseudoTranslations();
+
+ /**
+ * Retrieve the range of Eclipse versions the generated lanaguage pack will
+ * be compatible with.
+ *
+ * @return The range of Eclipse versions the generated language pack will be
+ * compatible with.
+ */
+ public Range compatibilityRange();
+
+ /**
+ * Retrieve the location of where the coverage report should be stored.
+ *
+ * @return The location to which the coverage report should be stored.
+ */
+ public File reportLocation();
+
+ /**
+ * Queries the configuration as to whether a resource should be included in
+ * the coverage report.
+ *
+ * @param resouce
+ * The resource whose inclusion is at question.
+ * @return Whether or not the resource should be included in the coverage
+ * report.
+ */
+ public boolean includeResource(PluginProxy plugin, ResourceProxy resouce);
+
+ /**
+ * Retrieve the list of filters which specify which resources should be
+ * included in the coverage report.
+ *
+ * @return The list of filters used to select which resources should be
+ * included in the coverage report.
+ */
+ public List<Filter> filters();
+
+ /**
+ * Retrieve the set of locales that should be included in the generated
+ * language pack.
+ *
+ * @return The set of locales that should be included in the generated
+ * language pack.
+ */
+ public Set<LocaleProxy> locales();
+
+ /**
+ * Retrieve the locale groups that should be included in the generated
+ * language pack.
+ *
+ * @return The locale groups that should be included in the generated
+ * language pack.
+ */
+ public Set<LocaleGroup> localeGroups();
+
+ /**
+ * Retrieve the list of filename suffixes that should be excluded when
+ * parsing the eclipse target.
+ *
+ * @return The list of filename suffixes that should be excluded when
+ * parsing the eclipse target.
+ */
+ public Set<String> excludeList();
+
+ /**
+ * Provides notification regarding progress.
+ *
+ * @param fragmentName
+ * The name of the plugin/feature for which a fragement is being
+ * created.
+ */
+ public void notifyProgress(String fragmentName);
+
+ public boolean includeXmlReport();
+
+ public boolean longReport();
+
+ public String localeExtension();
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Filter.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Filter.java
index acb4d8d..47583d3 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Filter.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Filter.java
@@ -13,26 +13,27 @@
import java.util.regex.Pattern;
public class Filter {
- private final Pattern pattern;
- private final String specifier;
+ private final Pattern pattern;
+ private final String specifier;
- public Filter(String pattern) {
- specifier = pattern;
- this.pattern = Pattern.compile(pattern);
- }
+ public Filter(String pattern) {
+ specifier = pattern;
+ this.pattern = Pattern.compile(pattern);
+ }
- public String getPattern(){
- return specifier;
- }
+ public String getPattern() {
+ return specifier;
+ }
- public boolean matches(PluginProxy plugin, ResourceProxy resource){
- String relativePath = resource.getRelativePath();
- boolean relative = pattern.matcher(relativePath).matches();
- boolean absolute = pattern.matcher(plugin.getName() + "/" + relativePath).matches();
- return relative || absolute;
- }
-
- public boolean isInclusive(){
- return false;
- }
+ public boolean matches(PluginProxy plugin, ResourceProxy resource) {
+ String relativePath = resource.getRelativePath();
+ boolean relative = pattern.matcher(relativePath).matches();
+ boolean absolute = pattern.matcher(
+ plugin.getName() + "/" + relativePath).matches();
+ return relative || absolute;
+ }
+
+ public boolean isInclusive() {
+ return false;
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/LazyConfiguration.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/LazyConfiguration.java
index a307495..a31555d 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/LazyConfiguration.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/LazyConfiguration.java
@@ -20,315 +20,346 @@
import org.eclipse.babel.build.core.eclipsetarget.EclipseTarget;
import org.eclipse.babel.build.core.translationcatalogue.TranslationCatalogue;
-
/**
- * Implements a configuration that can be built up incrementally.
- * It has two states:
+ * Implements a configuration that can be built up incrementally. It has two
+ * states:
* <ul>
- * <li>Unvalidated</li>
- * <li>Validated</li>
+ * <li>Unvalidated</li>
+ * <li>Validated</li>
* </ul>
*
- * When it is initially created it is in the unvalidated state, in this state the setX, isValidated and validate methods may
- * be called, but all other methods will throw an IllegalStateException. Once the validate method is called, the
- * state of each field will be validated, and if all fields are valid, it will transition to the validated state.
- * Otherwise, a {@link azure.build.core.ValidationException} will be thrown.
+ * When it is initially created it is in the unvalidated state, in this state
+ * the setX, isValidated and validate methods may be called, but all other
+ * methods will throw an IllegalStateException. Once the validate method is
+ * called, the state of each field will be validated, and if all fields are
+ * valid, it will transition to the validated state. Otherwise, a
+ * {@link azure.build.core.ValidationException} will be thrown.
*
- * Once in the validated state, the setX methods may not be called, but the other methods can be called normally.
+ * Once in the validated state, the setX methods may not be called, but the
+ * other methods can be called normally.
*/
public class LazyConfiguration implements Configuration {
- public class ValidationException extends Exception{
- public ValidationException(String string) {
- super(string);
- }
+ public class ValidationException extends Exception {
+ public ValidationException(String string) {
+ super(string);
+ }
- private static final long serialVersionUID = 4547650327498908947L;
- }
-
-
- private EclipseTarget eclipseTarget = null;
- private TranslationCatalogue translationCatalogue = null;
-
- private File workingDirectory = new File(".");
- private File report = null;
- private File eclipseRoot;
- private File translationsRoot;
-
- private boolean validated = false;
- private boolean includePseudoTranslations = false;
- private boolean includeXmlReport = false;
- private boolean longReport = false;
- private String localeExtension;
-
- private final List<Filter> filters = new LinkedList<Filter>();
- private final Set<LocaleProxy> locales = new HashSet<LocaleProxy>();
- private final Set<LocaleGroup> localeGroups = new HashSet<LocaleGroup>();
- private final Set<String> excludeList = new HashSet<String>();
-
- public EclipseTarget eclipseInstall() {
- if(!isValidated()){
- throw new IllegalStateException("LazyConfiguration must be validated before this method may be called");
- }
- try {
- if(eclipseTarget == null){
- eclipseTarget = new EclipseTarget(eclipseRoot, new HashSet<String>());
- eclipseTarget.populatePlugins();
- }
- } catch (Exception e) {}
- return eclipseTarget;
- }
-
- public void setArchiveRoot(File root){
- if(isValidated()){
- throw new IllegalStateException("setX methods cannot be called once the instance has been validated.");
- }
-
- eclipseRoot = root;
- }
+ private static final long serialVersionUID = 4547650327498908947L;
+ }
- public Range compatibilityRange() {
- if(!isValidated()){
- throw new IllegalStateException("LazyConfiguration must be validated before this method may be called");
- }
-
- // TODO Auto-generated method stub
- throw new UnsupportedOperationException("Not implemented yet!");
- }
-
- public void setCompatibilityRange(String range){
- if(isValidated()){
- throw new IllegalStateException("setX methods cannot be called once the instance has been validated.");
- }
-
- // TODO
- throw new UnsupportedOperationException("Not implemented yet!");
- }
+ private EclipseTarget eclipseTarget = null;
+ private TranslationCatalogue translationCatalogue = null;
- public List<Filter> filters() {
- if(!isValidated()){
- throw new IllegalStateException("LazyConfiguration must be validated before this method may be called");
- }
-
- return filters ;
- }
-
- public void addFilters(List<Filter> filters){
- if(isValidated()){
- throw new IllegalStateException("setX methods cannot be called once the instance has been validated.");
- }
- this.filters.addAll(filters);
- }
+ private File workingDirectory = new File(".");
+ private File report = null;
+ private File eclipseRoot;
+ private File translationsRoot;
- public boolean includePseudoTranslations() {
- if(!isValidated()){
- throw new IllegalStateException("LazyConfiguration must be validated before this method may be called");
- }
-
- return includePseudoTranslations;
- }
-
- public void setIncludePseudoTranslations(boolean include){
- if(isValidated()){
- throw new IllegalStateException("setX methods cannot be called once the instance has been validated.");
- }
-
- this.includePseudoTranslations = include;
- }
-
- public boolean includeResource(PluginProxy plugin, ResourceProxy resource) {
- if(!isValidated()){
- throw new IllegalStateException("LazyConfiguration must be validated before this method may be called");
- }
-
- for(Filter filter : filters){
- if(filter.matches(plugin, resource)){
- return filter.isInclusive();
- }
- }
-
- return true;
- }
+ private boolean validated = false;
+ private boolean includePseudoTranslations = false;
+ private boolean includeXmlReport = false;
+ private boolean longReport = false;
+ private String localeExtension;
- public Set<LocaleProxy> locales() {
- if(!isValidated()){
- throw new IllegalStateException("LazyConfiguration must be validated before this method may be called");
- }
-
- return locales;
- }
-
- public void addLocales(Set<LocaleProxy> locales){
- if(isValidated()){
- throw new IllegalStateException("setX methods cannot be called once the instance has been validated.");
- }
-
- this.locales.addAll(locales);
- }
+ private final List<Filter> filters = new LinkedList<Filter>();
+ private final Set<LocaleProxy> locales = new HashSet<LocaleProxy>();
+ private final Set<LocaleGroup> localeGroups = new HashSet<LocaleGroup>();
+ private final Set<String> excludeList = new HashSet<String>();
- public File reportLocation() {
- if(!isValidated()){
- throw new IllegalStateException("LazyConfiguration must be validated before this method may be called");
- }
-
- if(report == null){
- return new File(workingDirectory, "coverage.xml");
- }
-
- return report;
- }
-
- public void setReportLocation(File file){
- if(isValidated()){
- throw new IllegalStateException("setX methods cannot be called once the instance has been validated.");
- }
-
- report = file;
- }
+ public EclipseTarget eclipseInstall() {
+ if (!isValidated()) {
+ throw new IllegalStateException(
+ "LazyConfiguration must be validated before this method may be called");
+ }
+ try {
+ if (eclipseTarget == null) {
+ eclipseTarget = new EclipseTarget(eclipseRoot,
+ new HashSet<String>());
+ eclipseTarget.populatePlugins();
+ }
+ } catch (Exception e) {
+ }
+ return eclipseTarget;
+ }
- public Date timestamp() {
- if(!isValidated()){
- throw new IllegalStateException("LazyConfiguration must be validated before this method may be called");
- }
- return new Date();
- }
+ public void setArchiveRoot(File root) {
+ if (isValidated()) {
+ throw new IllegalStateException(
+ "setX methods cannot be called once the instance has been validated.");
+ }
- public TranslationCatalogue translations() {
- if(!isValidated()){
- throw new IllegalStateException("LazyConfiguration must be validated before this method may be called");
- }
-
- try {
- if(translationCatalogue == null){
- if(localeGroups.isEmpty()){
- translationCatalogue = new TranslationCatalogue(translationsRoot, locales);
- } else {
- locales.clear();
- translationCatalogue = new TranslationCatalogue(translationsRoot, localeGroups);
- locales.addAll(translationCatalogue.getAllLocales());
- }
- }
- } catch (Exception ex) {
- throw new RuntimeException(ex);
- }
-
- return translationCatalogue;
- }
-
- public void setTranslationsRoot(File translations){
- if(isValidated()){
- throw new IllegalStateException("setX methods cannot be called once the instance has been validated.");
- }
- this.translationsRoot = translations;
- }
+ eclipseRoot = root;
+ }
- public File workingDirectory() {
- if(!isValidated()){
- throw new IllegalStateException("LazyConfiguration must be validated before this method may be called");
- }
-
- return workingDirectory;
- }
-
- public void setWorkingDirectory(File file){
- if(isValidated()){
- throw new IllegalStateException("setX methods cannot be called once the instance has been validated.");
- }
- workingDirectory = file;
- }
+ public Range compatibilityRange() {
+ if (!isValidated()) {
+ throw new IllegalStateException(
+ "LazyConfiguration must be validated before this method may be called");
+ }
- public void validate() throws ValidationException{
- if(eclipseRoot == null || !eclipseRoot.exists()){
- throw new ValidationException("Eclipse root does not exist.");
- }
-
- if(translationsRoot == null || !translationsRoot.exists()){
- throw new ValidationException("Translation root does not exist.");
- }
-
- if(workingDirectory == null || !workingDirectory.exists()){
- throw new ValidationException("Working directory does not exist.");
- }
-
- validated = true;
- }
-
- public boolean isValidated() {
- return validated;
- }
+ // TODO Auto-generated method stub
+ throw new UnsupportedOperationException("Not implemented yet!");
+ }
- public Set<LocaleGroup> localeGroups() {
- if(!isValidated()){
- throw new IllegalStateException("LazyConfiguration must be validated before this method may be called");
- }
-
- return localeGroups;
- }
-
- public void addLocaleGroups(Set<LocaleGroup> localeGroups){
- if(isValidated()){
- throw new IllegalStateException("setX methods cannot be called once the instance has been validated.");
- }
-
- this.localeGroups.addAll(localeGroups);
- }
-
- public Set<String> excludeList() {
- if(!isValidated()){
- throw new IllegalStateException("LazyConfiguration must be validated before this method may be called");
- }
-
- return excludeList;
- }
-
- public void addExclude(String exclude){
- this.excludeList.add(exclude);
- }
+ public void setCompatibilityRange(String range) {
+ if (isValidated()) {
+ throw new IllegalStateException(
+ "setX methods cannot be called once the instance has been validated.");
+ }
- public void addFilter(Filter filter) {
- filters.add(filter);
- }
+ // TODO
+ throw new UnsupportedOperationException("Not implemented yet!");
+ }
- public void notifyProgress(String fragmentName) {
- // TODO Auto-generated method stub
- }
+ public List<Filter> filters() {
+ if (!isValidated()) {
+ throw new IllegalStateException(
+ "LazyConfiguration must be validated before this method may be called");
+ }
- public boolean includeXmlReport() {
- if(!isValidated()){
- throw new IllegalStateException("LazyConfiguration must be validated before this method may be called");
- }
-
- return includeXmlReport;
- }
-
- public void setIncludeXmlReport(boolean include){
- if(isValidated()){
- throw new IllegalStateException("setX methods cannot be called once the instance has been validated.");
- }
-
- includeXmlReport = include;
- }
+ return filters;
+ }
- public boolean longReport() {
- if(!isValidated()){
- throw new IllegalStateException("LazyConfiguration must be validated before this method may be called");
- }
-
- return longReport;
- }
-
- public void setLongReport(boolean longReport){
- if(isValidated()){
- throw new IllegalStateException("setX methods cannot be called once the instance has been validated.");
- }
-
- this.longReport = longReport;
- }
-
- public String localeExtension() {
- if(!isValidated()){
- throw new IllegalStateException("LazyConfiguration must be validated before this method may be called");
- }
-
- return localeExtension;
- }
+ public void addFilters(List<Filter> filters) {
+ if (isValidated()) {
+ throw new IllegalStateException(
+ "setX methods cannot be called once the instance has been validated.");
+ }
+ this.filters.addAll(filters);
+ }
+
+ public boolean includePseudoTranslations() {
+ if (!isValidated()) {
+ throw new IllegalStateException(
+ "LazyConfiguration must be validated before this method may be called");
+ }
+
+ return includePseudoTranslations;
+ }
+
+ public void setIncludePseudoTranslations(boolean include) {
+ if (isValidated()) {
+ throw new IllegalStateException(
+ "setX methods cannot be called once the instance has been validated.");
+ }
+
+ this.includePseudoTranslations = include;
+ }
+
+ public boolean includeResource(PluginProxy plugin, ResourceProxy resource) {
+ if (!isValidated()) {
+ throw new IllegalStateException(
+ "LazyConfiguration must be validated before this method may be called");
+ }
+
+ for (Filter filter : filters) {
+ if (filter.matches(plugin, resource)) {
+ return filter.isInclusive();
+ }
+ }
+
+ return true;
+ }
+
+ public Set<LocaleProxy> locales() {
+ if (!isValidated()) {
+ throw new IllegalStateException(
+ "LazyConfiguration must be validated before this method may be called");
+ }
+
+ return locales;
+ }
+
+ public void addLocales(Set<LocaleProxy> locales) {
+ if (isValidated()) {
+ throw new IllegalStateException(
+ "setX methods cannot be called once the instance has been validated.");
+ }
+
+ this.locales.addAll(locales);
+ }
+
+ public File reportLocation() {
+ if (!isValidated()) {
+ throw new IllegalStateException(
+ "LazyConfiguration must be validated before this method may be called");
+ }
+
+ if (report == null) {
+ return new File(workingDirectory, "coverage.xml");
+ }
+
+ return report;
+ }
+
+ public void setReportLocation(File file) {
+ if (isValidated()) {
+ throw new IllegalStateException(
+ "setX methods cannot be called once the instance has been validated.");
+ }
+
+ report = file;
+ }
+
+ public Date timestamp() {
+ if (!isValidated()) {
+ throw new IllegalStateException(
+ "LazyConfiguration must be validated before this method may be called");
+ }
+ return new Date();
+ }
+
+ public TranslationCatalogue translations() {
+ if (!isValidated()) {
+ throw new IllegalStateException(
+ "LazyConfiguration must be validated before this method may be called");
+ }
+
+ try {
+ if (translationCatalogue == null) {
+ if (localeGroups.isEmpty()) {
+ translationCatalogue = new TranslationCatalogue(
+ translationsRoot, locales);
+ } else {
+ locales.clear();
+ translationCatalogue = new TranslationCatalogue(
+ translationsRoot, localeGroups);
+ locales.addAll(translationCatalogue.getAllLocales());
+ }
+ }
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+
+ return translationCatalogue;
+ }
+
+ public void setTranslationsRoot(File translations) {
+ if (isValidated()) {
+ throw new IllegalStateException(
+ "setX methods cannot be called once the instance has been validated.");
+ }
+ this.translationsRoot = translations;
+ }
+
+ public File workingDirectory() {
+ if (!isValidated()) {
+ throw new IllegalStateException(
+ "LazyConfiguration must be validated before this method may be called");
+ }
+
+ return workingDirectory;
+ }
+
+ public void setWorkingDirectory(File file) {
+ if (isValidated()) {
+ throw new IllegalStateException(
+ "setX methods cannot be called once the instance has been validated.");
+ }
+ workingDirectory = file;
+ }
+
+ public void validate() throws ValidationException {
+ if (eclipseRoot == null || !eclipseRoot.exists()) {
+ throw new ValidationException("Eclipse root does not exist.");
+ }
+
+ if (translationsRoot == null || !translationsRoot.exists()) {
+ throw new ValidationException("Translation root does not exist.");
+ }
+
+ if (workingDirectory == null || !workingDirectory.exists()) {
+ throw new ValidationException("Working directory does not exist.");
+ }
+
+ validated = true;
+ }
+
+ public boolean isValidated() {
+ return validated;
+ }
+
+ public Set<LocaleGroup> localeGroups() {
+ if (!isValidated()) {
+ throw new IllegalStateException(
+ "LazyConfiguration must be validated before this method may be called");
+ }
+
+ return localeGroups;
+ }
+
+ public void addLocaleGroups(Set<LocaleGroup> localeGroups) {
+ if (isValidated()) {
+ throw new IllegalStateException(
+ "setX methods cannot be called once the instance has been validated.");
+ }
+
+ this.localeGroups.addAll(localeGroups);
+ }
+
+ public Set<String> excludeList() {
+ if (!isValidated()) {
+ throw new IllegalStateException(
+ "LazyConfiguration must be validated before this method may be called");
+ }
+
+ return excludeList;
+ }
+
+ public void addExclude(String exclude) {
+ this.excludeList.add(exclude);
+ }
+
+ public void addFilter(Filter filter) {
+ filters.add(filter);
+ }
+
+ public void notifyProgress(String fragmentName) {
+ // TODO Auto-generated method stub
+ }
+
+ public boolean includeXmlReport() {
+ if (!isValidated()) {
+ throw new IllegalStateException(
+ "LazyConfiguration must be validated before this method may be called");
+ }
+
+ return includeXmlReport;
+ }
+
+ public void setIncludeXmlReport(boolean include) {
+ if (isValidated()) {
+ throw new IllegalStateException(
+ "setX methods cannot be called once the instance has been validated.");
+ }
+
+ includeXmlReport = include;
+ }
+
+ public boolean longReport() {
+ if (!isValidated()) {
+ throw new IllegalStateException(
+ "LazyConfiguration must be validated before this method may be called");
+ }
+
+ return longReport;
+ }
+
+ public void setLongReport(boolean longReport) {
+ if (isValidated()) {
+ throw new IllegalStateException(
+ "setX methods cannot be called once the instance has been validated.");
+ }
+
+ this.longReport = longReport;
+ }
+
+ public String localeExtension() {
+ if (!isValidated()) {
+ throw new IllegalStateException(
+ "LazyConfiguration must be validated before this method may be called");
+ }
+
+ return localeExtension;
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/LocaleGroup.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/LocaleGroup.java
index c37a192..fba6a0e 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/LocaleGroup.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/LocaleGroup.java
@@ -12,76 +12,81 @@
public enum LocaleGroup {
- GROUP_ALL (Messages.getString("Groups_all"), Messages.getString("Groups_all_full"), 0), //$NON-NLS-1$
- GROUP_1 (Messages.getString("Groups_group1"), Messages.getString("Groups_group1_full"), 1), //$NON-NLS-1$
- GROUP_2 (Messages.getString("Groups_group2"), Messages.getString("Groups_group2_full"), 2), //$NON-NLS-1$
- GROUP_2A (Messages.getString("Groups_group2a"), Messages.getString("Groups_group2a_full"), 3), //$NON-NLS-1$
- GROUP_BIDI (Messages.getString("Groups_groupBidi"), Messages.getString("Groups_groupBidi_full"), 4); //$NON-NLS-1$
-
- private String name;
- private String fullName;
- private int number;
+ GROUP_ALL(
+ Messages.getString("Groups_all"), Messages.getString("Groups_all_full"), 0), //$NON-NLS-1$
+ GROUP_1(
+ Messages.getString("Groups_group1"), Messages.getString("Groups_group1_full"), 1), //$NON-NLS-1$
+ GROUP_2(
+ Messages.getString("Groups_group2"), Messages.getString("Groups_group2_full"), 2), //$NON-NLS-1$
+ GROUP_2A(
+ Messages.getString("Groups_group2a"), Messages.getString("Groups_group2a_full"), 3), //$NON-NLS-1$
+ GROUP_BIDI(
+ Messages.getString("Groups_groupBidi"), Messages.getString("Groups_groupBidi_full"), 4); //$NON-NLS-1$
- private LocaleGroup(String name, String fullName, int number) {
- this.name = name;
- this.fullName = fullName;
- this.number = number;
- }
-
- public String getName() {
- return name;
- }
-
- public String getFullName() {
- return fullName;
- }
+ private String name;
+ private String fullName;
+ private int number;
- public int getNumber() {
- return number;
- }
-
- public static LocaleGroup get(String name) {
- for (LocaleGroup group : LocaleGroup.values()) {
- if (group.name.compareToIgnoreCase(name) == 0) {
- return group;
- }
- }
- return LocaleGroup.GROUP_ALL;
- }
-
- public static LocaleGroup getByFullName(String fullName) {
- for (LocaleGroup group : LocaleGroup.values()) {
- if (group.fullName.compareToIgnoreCase(fullName) == 0) {
- return group;
- }
- }
- return LocaleGroup.GROUP_ALL;
- }
-
- public static LocaleGroup get(Integer number) {
- for (LocaleGroup group : LocaleGroup.values()) {
- if (group.number == number) {
- return group;
- }
- }
- return LocaleGroup.GROUP_ALL;
- }
-
- public static boolean isValidGroupName(String name) {
- for (LocaleGroup group : LocaleGroup.values()) {
- if (group.name.compareToIgnoreCase(name) == 0) {
- return true;
- }
- }
- return false;
- }
-
- public static boolean isValidGroupFullName(String fullName) {
- for (LocaleGroup group : LocaleGroup.values()) {
- if (group.fullName.compareToIgnoreCase(fullName) == 0) {
- return true;
- }
- }
- return false;
- }
+ private LocaleGroup(String name, String fullName, int number) {
+ this.name = name;
+ this.fullName = fullName;
+ this.number = number;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getFullName() {
+ return fullName;
+ }
+
+ public int getNumber() {
+ return number;
+ }
+
+ public static LocaleGroup get(String name) {
+ for (LocaleGroup group : LocaleGroup.values()) {
+ if (group.name.compareToIgnoreCase(name) == 0) {
+ return group;
+ }
+ }
+ return LocaleGroup.GROUP_ALL;
+ }
+
+ public static LocaleGroup getByFullName(String fullName) {
+ for (LocaleGroup group : LocaleGroup.values()) {
+ if (group.fullName.compareToIgnoreCase(fullName) == 0) {
+ return group;
+ }
+ }
+ return LocaleGroup.GROUP_ALL;
+ }
+
+ public static LocaleGroup get(Integer number) {
+ for (LocaleGroup group : LocaleGroup.values()) {
+ if (group.number == number) {
+ return group;
+ }
+ }
+ return LocaleGroup.GROUP_ALL;
+ }
+
+ public static boolean isValidGroupName(String name) {
+ for (LocaleGroup group : LocaleGroup.values()) {
+ if (group.name.compareToIgnoreCase(name) == 0) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public static boolean isValidGroupFullName(String fullName) {
+ for (LocaleGroup group : LocaleGroup.values()) {
+ if (group.fullName.compareToIgnoreCase(fullName) == 0) {
+ return true;
+ }
+ }
+ return false;
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/LocaleProxy.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/LocaleProxy.java
index b261bec..18ef5e9 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/LocaleProxy.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/LocaleProxy.java
@@ -15,28 +15,28 @@
import java.util.Set;
public class LocaleProxy {
- public static final Set<LocaleProxy> ALL = new HashSet<LocaleProxy>();
- public static final Comparator<LocaleProxy> NAME_COMPARATOR = new Comparator<LocaleProxy>(){
- public int compare(LocaleProxy o1, LocaleProxy o2) {
- return o1.name.compareTo(o2.name);
- }
- };
- private String name;
-
- public LocaleProxy(String name) {
- this.name = name;
- }
-
- public String getName(){
- return name;
- }
-
- public boolean equals(Object object) {
- LocaleProxy locale = (LocaleProxy)object;
- return locale.getName().equals(this.name);
- }
-
- public int hashCode() {
- return this.name.hashCode();
- }
+ public static final Set<LocaleProxy> ALL = new HashSet<LocaleProxy>();
+ public static final Comparator<LocaleProxy> NAME_COMPARATOR = new Comparator<LocaleProxy>() {
+ public int compare(LocaleProxy o1, LocaleProxy o2) {
+ return o1.name.compareTo(o2.name);
+ }
+ };
+ private String name;
+
+ public LocaleProxy(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public boolean equals(Object object) {
+ LocaleProxy locale = (LocaleProxy) object;
+ return locale.getName().equals(this.name);
+ }
+
+ public int hashCode() {
+ return this.name.hashCode();
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Main.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Main.java
index de0f8bd..5322759 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Main.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Main.java
@@ -17,42 +17,51 @@
import org.eclipse.babel.build.core.exceptions.InvalidFilenameException;
import org.eclipse.babel.build.core.languagepack.LanguagePack;
-
public class Main {
- public static void main (String[] args) {
- try {
- CommandLineConfiguration config = new CommandLineConfiguration(args);
-
- long startLanguagePackGeneration = System.currentTimeMillis();
- LanguagePack languagePack = new LanguagePack(config);
- System.out.println();
- System.out.println(Messages.getString("Messages_generating_language_pack")); //$NON-NLS-1$
-
- LanguagePackCoverageReport coverage;
- coverage = languagePack.generate();
- Configuration.helper.printLanguagePackResult(config, coverage);
-
- config.times.languagePackGeneration = System.currentTimeMillis() - startLanguagePackGeneration;
-
- System.out.println("\nEclipse Target parsed in: " + config.times.eclipseInstallPopulation); //$NON-NLS-1$
- System.out.println("Language Pack generated in: " + config.times.languagePackGeneration); //$NON-NLS-1$
-
- } catch (MissingArgument e) {
- System.out.println(Messages.getString("Error_missing_argument") + e.getMessage()); //$NON-NLS-1$
- System.exit(-1);
- } catch (UnsetMandatoryOption e) {
- System.out.println(Messages.getString("Error_unset_mandatory_exception") + e.getMessage()); //$NON-NLS-1$
- System.exit(-1);
- } catch (InvalidFilenameException i) {
- System.out.println( Messages.getString("Error_invalid_working_directory_name") ); //$NON-NLS-1$
- System.exit(0);
- } catch (FailedDeletionException f) {
- System.out.println( Messages.getString("Error_deleting_working_directory") ); //$NON-NLS-1$
- System.exit(0);
- } catch (Exception e) {
- System.out.println( Messages.getString("Error_language_pack") + ": " + e.getMessage()); //$NON-NLS-1$ $NON-NLS-2$
- System.exit(0);
- }
- }
+ public static void main(String[] args) {
+ try {
+ CommandLineConfiguration config = new CommandLineConfiguration(args);
+
+ long startLanguagePackGeneration = System.currentTimeMillis();
+ LanguagePack languagePack = new LanguagePack(config);
+ System.out.println();
+ System.out.println(Messages
+ .getString("Messages_generating_language_pack")); //$NON-NLS-1$
+
+ LanguagePackCoverageReport coverage;
+ coverage = languagePack.generate();
+ Configuration.helper.printLanguagePackResult(config, coverage);
+
+ config.times.languagePackGeneration = System.currentTimeMillis()
+ - startLanguagePackGeneration;
+
+ System.out
+ .println("\nEclipse Target parsed in: " + config.times.eclipseInstallPopulation); //$NON-NLS-1$
+ System.out
+ .println("Language Pack generated in: " + config.times.languagePackGeneration); //$NON-NLS-1$
+
+ } catch (MissingArgument e) {
+ System.out
+ .println(Messages.getString("Error_missing_argument") + e.getMessage()); //$NON-NLS-1$
+ System.exit(-1);
+ } catch (UnsetMandatoryOption e) {
+ System.out
+ .println(Messages
+ .getString("Error_unset_mandatory_exception") + e.getMessage()); //$NON-NLS-1$
+ System.exit(-1);
+ } catch (InvalidFilenameException i) {
+ System.out.println(Messages
+ .getString("Error_invalid_working_directory_name")); //$NON-NLS-1$
+ System.exit(0);
+ } catch (FailedDeletionException f) {
+ System.out.println(Messages
+ .getString("Error_deleting_working_directory")); //$NON-NLS-1$
+ System.exit(0);
+ } catch (Exception e) {
+ System.out
+ .println(Messages.getString("Error_language_pack") + ": " + e.getMessage()); //$NON-NLS-1$ $NON-NLS-2$
+ System.exit(0);
+ }
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Messages.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Messages.java
index cfda238..40fa840 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Messages.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Messages.java
@@ -14,19 +14,19 @@
import java.util.ResourceBundle;
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.babel.build.core.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.babel.build.core.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Options.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Options.java
index 90e6454..c7fdc85 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Options.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Options.java
@@ -16,108 +16,109 @@
import java.util.Map;
public class Options {
- public static class UnknownOption extends RuntimeException{
- private static final long serialVersionUID = 5843082921291728978L;
-
- public UnknownOption(String name) {
- super(name);
- }
- }
-
- public static class UnsetMandatoryOption extends RuntimeException{
- private static final long serialVersionUID = 4112908586458361303L;
+ public static class UnknownOption extends RuntimeException {
+ private static final long serialVersionUID = 5843082921291728978L;
- public UnsetMandatoryOption(String name){
- super(name);
- }
- }
-
- public static class MissingArgument extends RuntimeException{
- private static final long serialVersionUID = 4845067566513625318L;
-
- public MissingArgument(String message){
- super(message);
- }
- }
-
- private class Option {
- private final String name;
- private String value = null;
- private final boolean needsArg;
- private final boolean mandatory;
-
- public Option(String specifier){
- mandatory = specifier.endsWith("!");
- needsArg = specifier.endsWith("=") || specifier.endsWith("=!");
- name = specifier.substring(0, specifier.length() - (needsArg ? 1 : 0) - (mandatory ? 1 : 0));
- }
- }
-
- private final Map<String, Option> values = new HashMap<String, Option>();
- private final List<String> params = new LinkedList<String>();
-
- public Options(String... opts) {
- for(String opt : opts){
- Option o = new Option(opt);
- values.put(o.name, o);
- }
- }
-
- public Options parse(String... args) {
- for(int i = 0; i < args.length; i++){
- Option opt = values.get(args[i]);
-
- if(opt == null){
- params.add(args[i]);
- } else {
- if(opt.needsArg){
- if(i < args.length - 1){
- opt.value = args[i + 1];
- } else {
- throw new MissingArgument(args[i]);
- }
- i++;
- } else {
- opt.value = "";
- }
- }
- }
-
- for(String name : values.keySet()){
- Option opt = values.get(name);
- if(opt.mandatory && opt.value == null){
- throw new UnsetMandatoryOption(name);
- }
- }
-
- return this;
- }
-
- public boolean isSet(String name){
- try{
- return values.get(name).value != null;
- } catch (NullPointerException ex){
- throw new UnknownOption(name);
- }
- }
+ public UnknownOption(String name) {
+ super(name);
+ }
+ }
- public List<String> getParams() {
- return params;
- }
+ public static class UnsetMandatoryOption extends RuntimeException {
+ private static final long serialVersionUID = 4112908586458361303L;
- public String get(String name) {
- return get(name, null);
- }
+ public UnsetMandatoryOption(String name) {
+ super(name);
+ }
+ }
- public String get(String name, String default_) {
- try{
- String value = values.get(name).value;
- if(value == null){
- return default_;
- }
- return value;
- } catch (NullPointerException ex){
- throw new UnknownOption(name);
- }
- }
+ public static class MissingArgument extends RuntimeException {
+ private static final long serialVersionUID = 4845067566513625318L;
+
+ public MissingArgument(String message) {
+ super(message);
+ }
+ }
+
+ private class Option {
+ private final String name;
+ private String value = null;
+ private final boolean needsArg;
+ private final boolean mandatory;
+
+ public Option(String specifier) {
+ mandatory = specifier.endsWith("!");
+ needsArg = specifier.endsWith("=") || specifier.endsWith("=!");
+ name = specifier.substring(0, specifier.length()
+ - (needsArg ? 1 : 0) - (mandatory ? 1 : 0));
+ }
+ }
+
+ private final Map<String, Option> values = new HashMap<String, Option>();
+ private final List<String> params = new LinkedList<String>();
+
+ public Options(String... opts) {
+ for (String opt : opts) {
+ Option o = new Option(opt);
+ values.put(o.name, o);
+ }
+ }
+
+ public Options parse(String... args) {
+ for (int i = 0; i < args.length; i++) {
+ Option opt = values.get(args[i]);
+
+ if (opt == null) {
+ params.add(args[i]);
+ } else {
+ if (opt.needsArg) {
+ if (i < args.length - 1) {
+ opt.value = args[i + 1];
+ } else {
+ throw new MissingArgument(args[i]);
+ }
+ i++;
+ } else {
+ opt.value = "";
+ }
+ }
+ }
+
+ for (String name : values.keySet()) {
+ Option opt = values.get(name);
+ if (opt.mandatory && opt.value == null) {
+ throw new UnsetMandatoryOption(name);
+ }
+ }
+
+ return this;
+ }
+
+ public boolean isSet(String name) {
+ try {
+ return values.get(name).value != null;
+ } catch (NullPointerException ex) {
+ throw new UnknownOption(name);
+ }
+ }
+
+ public List<String> getParams() {
+ return params;
+ }
+
+ public String get(String name) {
+ return get(name, null);
+ }
+
+ public String get(String name, String default_) {
+ try {
+ String value = values.get(name).value;
+ if (value == null) {
+ return default_;
+ }
+ return value;
+ } catch (NullPointerException ex) {
+ throw new UnknownOption(name);
+ }
+ }
}
\ No newline at end of file
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/PluginProxy.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/PluginProxy.java
index 3f17b4e..bf84651 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/PluginProxy.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/PluginProxy.java
@@ -14,54 +14,61 @@
import java.util.List;
public class PluginProxy {
- private String name;
- private File pluginLocation;
- private String version;
- private boolean isJar;
- private boolean isFeature;
- private List<ResourceProxy> resources;
-
- public PluginProxy(File pluginLocation, List<ResourceProxy> resources, boolean isJar, boolean isFeature){
- this.pluginLocation = pluginLocation;
- if(pluginLocation.getName().matches(Messages.getString("Patterns_plugin_name"))) { //$NON-NLS-1$
- this.name = pluginLocation.getName().substring(0, pluginLocation.getName().indexOf(Messages.getString("Characters_underscore"))); //$NON-NLS-1$
- this.version = pluginLocation.getName().substring(pluginLocation.getName().indexOf(Messages.getString("Characters_underscore")) + 1); //$NON-NLS-1$
- if(isJar) {
- this.version = version.replaceAll(Messages.getString("Extensions_jar"), ""); //$NON-NLS-1$
- }
- }
- else {
- this.name = pluginLocation.getName();
- this.version = ""; //$NON-NLS-1$
- }
- this.resources = resources;
- this.isJar = isJar;
- this.isFeature = isFeature;
- }
-
- public String getName(){
- //TODO: stub
- return this.name;
- }
-
- public String getVersion(){
- //TODO: stub
- return this.version;
- }
-
- public List<ResourceProxy> getResources() {
- return resources;
- }
+ private String name;
+ private File pluginLocation;
+ private String version;
+ private boolean isJar;
+ private boolean isFeature;
+ private List<ResourceProxy> resources;
- public boolean isJar() {
- return isJar;
- }
+ public PluginProxy(File pluginLocation, List<ResourceProxy> resources,
+ boolean isJar, boolean isFeature) {
+ this.pluginLocation = pluginLocation;
+ if (pluginLocation.getName().matches(
+ Messages.getString("Patterns_plugin_name"))) { //$NON-NLS-1$
+ this.name = pluginLocation.getName().substring(
+ 0,
+ pluginLocation.getName().indexOf(
+ Messages.getString("Characters_underscore"))); //$NON-NLS-1$
+ this.version = pluginLocation.getName().substring(
+ pluginLocation.getName().indexOf(
+ Messages.getString("Characters_underscore")) + 1); //$NON-NLS-1$
+ if (isJar) {
+ this.version = version.replaceAll(
+ Messages.getString("Extensions_jar"), ""); //$NON-NLS-1$
+ }
+ } else {
+ this.name = pluginLocation.getName();
+ this.version = ""; //$NON-NLS-1$
+ }
+ this.resources = resources;
+ this.isJar = isJar;
+ this.isFeature = isFeature;
+ }
- public File getPluginLocation() {
- return pluginLocation;
- }
+ public String getName() {
+ // TODO: stub
+ return this.name;
+ }
- public boolean isFeature() {
- return isFeature;
- }
+ public String getVersion() {
+ // TODO: stub
+ return this.version;
+ }
+
+ public List<ResourceProxy> getResources() {
+ return resources;
+ }
+
+ public boolean isJar() {
+ return isJar;
+ }
+
+ public File getPluginLocation() {
+ return pluginLocation;
+ }
+
+ public boolean isFeature() {
+ return isFeature;
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Range.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Range.java
index 1ed7b83..fb8bc52 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Range.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/Range.java
@@ -11,19 +11,18 @@
package org.eclipse.babel.build.core;
public class Range {
- public boolean contains(String version){
- //TODO: stub
- return false;
- }
-
- public String toString(){
- //TODO: stub
- return "";
- }
-
-
- public static Range parse(String range){
- //TODO: stub
- return null;
- }
+ public boolean contains(String version) {
+ // TODO: stub
+ return false;
+ }
+
+ public String toString() {
+ // TODO: stub
+ return "";
+ }
+
+ public static Range parse(String range) {
+ // TODO: stub
+ return null;
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/ResourceProxy.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/ResourceProxy.java
index 6481294..e03802d 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/ResourceProxy.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/ResourceProxy.java
@@ -13,35 +13,37 @@
import java.io.File;
public class ResourceProxy {
- private File fileResource; /** From translation catalogue */
- private String relativePath; /** From eclipse target */
- private String canonicalPath;
-
- public ResourceProxy(File fileResource) {
- this.fileResource = fileResource;
- }
-
- public ResourceProxy(String relativePath) {
- this.relativePath = relativePath;
- this.relativePath = this.relativePath.replace('/', File.separatorChar);
- this.canonicalPath = relativePath.replace(File.separatorChar, '/');
- }
-
- public ResourceProxy(File fileResource, String relativePath) {
- this.fileResource = fileResource;
- this.relativePath = relativePath.replace('/', File.separatorChar);
- this.canonicalPath = relativePath.replace(File.separatorChar, '/');
- }
+ private File fileResource;
+ /** From translation catalogue */
+ private String relativePath;
+ /** From eclipse target */
+ private String canonicalPath;
- public File getFileResource() {
- return fileResource;
- }
+ public ResourceProxy(File fileResource) {
+ this.fileResource = fileResource;
+ }
- public String getRelativePath() {
- return relativePath;
- }
+ public ResourceProxy(String relativePath) {
+ this.relativePath = relativePath;
+ this.relativePath = this.relativePath.replace('/', File.separatorChar);
+ this.canonicalPath = relativePath.replace(File.separatorChar, '/');
+ }
- public String getCanonicalPath() {
- return canonicalPath;
- }
+ public ResourceProxy(File fileResource, String relativePath) {
+ this.fileResource = fileResource;
+ this.relativePath = relativePath.replace('/', File.separatorChar);
+ this.canonicalPath = relativePath.replace(File.separatorChar, '/');
+ }
+
+ public File getFileResource() {
+ return fileResource;
+ }
+
+ public String getRelativePath() {
+ return relativePath;
+ }
+
+ public String getCanonicalPath() {
+ return canonicalPath;
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/coverage/CoverageReport.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/coverage/CoverageReport.java
index 36271f7..b337203 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/coverage/CoverageReport.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/coverage/CoverageReport.java
@@ -14,22 +14,19 @@
import java.io.OutputStream;
public interface CoverageReport {
- public static class helper{
- public static void serialize(OutputStream out){
- // TODO: stub
- }
-
- public static CoverageReport parse(InputStream in){
- // TODO: stub
- return null;
- }
- }
- /**
- public List<LocaleProxy> locales();
- public List<PluginProxy> plugins();
- public Date timestamp();
- public EclipseArchive archive();
- public TranslationArchive translations();
- public LanguagePack catalogue();
- */
+ public static class helper {
+ public static void serialize(OutputStream out) {
+ // TODO: stub
+ }
+
+ public static CoverageReport parse(InputStream in) {
+ // TODO: stub
+ return null;
+ }
+ }
+ /**
+ * public List<LocaleProxy> locales(); public List<PluginProxy> plugins();
+ * public Date timestamp(); public EclipseArchive archive(); public
+ * TranslationArchive translations(); public LanguagePack catalogue();
+ */
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/coverage/LanguagePackCoverageReport.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/coverage/LanguagePackCoverageReport.java
index c44586b..da5ebb5 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/coverage/LanguagePackCoverageReport.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/coverage/LanguagePackCoverageReport.java
@@ -18,42 +18,51 @@
import org.eclipse.babel.build.core.LocaleProxy;
-
public class LanguagePackCoverageReport implements CoverageReport {
- private List<PluginCoverageInformation> pluginCoverageReports = new ArrayList<PluginCoverageInformation>();
- private Map<LocaleProxy, Integer> matchesPerLocale = new HashMap<LocaleProxy, Integer>();
- private List<LocaleProxy> locales = new ArrayList<LocaleProxy>();
-
- public LanguagePackCoverageReport(Collection<LocaleProxy> locales) {
- super();
- this.locales.addAll(locales);
- initializeMap();
- }
-
- /** Adds coverage information about a single plug-in to overall coverage report. */
- public void addPluginCoverageToReport(PluginCoverageInformation pluginCoverageInformation) {
- this.pluginCoverageReports.add(pluginCoverageInformation);
-
- for (LocaleProxy locale : pluginCoverageInformation.getPluginMatchingPerLocale().keySet()) {
- if (pluginCoverageInformation.getPluginMatchingPerLocale().get(locale)) {
- this.matchesPerLocale.put(locale, this.matchesPerLocale.get(locale) + 1);
- }
- }
- }
+ private List<PluginCoverageInformation> pluginCoverageReports = new ArrayList<PluginCoverageInformation>();
+ private Map<LocaleProxy, Integer> matchesPerLocale = new HashMap<LocaleProxy, Integer>();
+ private List<LocaleProxy> locales = new ArrayList<LocaleProxy>();
- /** Returns coverage information about each individual plug-in in the Eclipse install. */
- public List<PluginCoverageInformation> getPluginCoverageReports() {
- return pluginCoverageReports;
- }
-
- /** Returns number of matched plug-ins for each locale. */
- public Map<LocaleProxy, Integer> getMatchesPerLocale() {
- return matchesPerLocale;
- }
-
- private void initializeMap() {
- for (LocaleProxy locale : locales) {
- this.matchesPerLocale.put(locale, 0);
- }
- }
+ public LanguagePackCoverageReport(Collection<LocaleProxy> locales) {
+ super();
+ this.locales.addAll(locales);
+ initializeMap();
+ }
+
+ /**
+ * Adds coverage information about a single plug-in to overall coverage
+ * report.
+ */
+ public void addPluginCoverageToReport(
+ PluginCoverageInformation pluginCoverageInformation) {
+ this.pluginCoverageReports.add(pluginCoverageInformation);
+
+ for (LocaleProxy locale : pluginCoverageInformation
+ .getPluginMatchingPerLocale().keySet()) {
+ if (pluginCoverageInformation.getPluginMatchingPerLocale().get(
+ locale)) {
+ this.matchesPerLocale.put(locale,
+ this.matchesPerLocale.get(locale) + 1);
+ }
+ }
+ }
+
+ /**
+ * Returns coverage information about each individual plug-in in the Eclipse
+ * install.
+ */
+ public List<PluginCoverageInformation> getPluginCoverageReports() {
+ return pluginCoverageReports;
+ }
+
+ /** Returns number of matched plug-ins for each locale. */
+ public Map<LocaleProxy, Integer> getMatchesPerLocale() {
+ return matchesPerLocale;
+ }
+
+ private void initializeMap() {
+ for (LocaleProxy locale : locales) {
+ this.matchesPerLocale.put(locale, 0);
+ }
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/coverage/PluginCoverageInformation.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/coverage/PluginCoverageInformation.java
index d7d631f..c74c4c3 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/coverage/PluginCoverageInformation.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/coverage/PluginCoverageInformation.java
@@ -18,82 +18,102 @@
import org.eclipse.babel.build.core.PluginProxy;
import org.eclipse.babel.build.core.ResourceProxy;
-
public class PluginCoverageInformation {
- public static final Comparator<PluginCoverageInformation> NAME_COMPARATOR = new Comparator<PluginCoverageInformation>(){
- public int compare(PluginCoverageInformation o1, PluginCoverageInformation o2) {
- String name1 = o1.getEclipseArchivePlugin().getName();
- String name2 = o2.getEclipseArchivePlugin().getName();
- return name1.compareTo(name2);
- }
- };
-
- private final PluginProxy eclipseArchivePlugin;
- private Map<String, ResourceCoverageInformation> resourceCoverage =
- new HashMap<String, ResourceCoverageInformation>();
- private Map<LocaleProxy, Boolean> pluginMatchingPerLocale = new HashMap<LocaleProxy, Boolean>();
-
- public PluginCoverageInformation(PluginProxy eclipseArchivePlugin) {
- super();
- this.eclipseArchivePlugin = eclipseArchivePlugin;
- }
+ public static final Comparator<PluginCoverageInformation> NAME_COMPARATOR = new Comparator<PluginCoverageInformation>() {
+ public int compare(PluginCoverageInformation o1,
+ PluginCoverageInformation o2) {
+ String name1 = o1.getEclipseArchivePlugin().getName();
+ String name2 = o2.getEclipseArchivePlugin().getName();
+ return name1.compareTo(name2);
+ }
+ };
- /** Returns a PluginProxy which represents the plug-in in question. */
- public PluginProxy getEclipseArchivePlugin() {
- return eclipseArchivePlugin;
- }
+ private final PluginProxy eclipseArchivePlugin;
+ private Map<String, ResourceCoverageInformation> resourceCoverage = new HashMap<String, ResourceCoverageInformation>();
+ private Map<LocaleProxy, Boolean> pluginMatchingPerLocale = new HashMap<LocaleProxy, Boolean>();
- /** Returns a map which, for each locale, indicates whether or not plug-in was matched. */
- public Map<LocaleProxy, Boolean> getPluginMatchingPerLocale() {
- return this.pluginMatchingPerLocale;
- }
-
- /** Given a specific locale, indicates whether or not plug-in was matched. */
- public Boolean getPluginMatchingForLocale(String locale) {
- for (LocaleProxy localeFromList: pluginMatchingPerLocale.keySet()) {
- if (localeFromList.getName().compareToIgnoreCase(locale) == 0) {
- return this.pluginMatchingPerLocale.get(localeFromList);
- }
- }
-
- return false;
- }
-
- /** Records whether or not the plug-in in question was matched to a specific locale. */
- public void setPluginMatchingForLocale(LocaleProxy locale, Boolean matched) {
- this.pluginMatchingPerLocale.put(locale, matched);
- }
-
- /** Records whether or not a resource belonging to the plug-in in question was matched to a specific locale. */
- public void setResourceCoverageForLocale(LocaleProxy locale, ResourceProxy resource, Boolean matched) {
- if (this.resourceCoverage.containsKey(resource.getRelativePath())) {
- ResourceCoverageInformation info = this.resourceCoverage.get(resource.getRelativePath());
- info.setMatchingForLocale(locale, matched);
- } else {
- ResourceCoverageInformation info = new ResourceCoverageInformation(resource);
- info.setMatchingForLocale(locale, matched);
- this.resourceCoverage.put(resource.getRelativePath(), info);
-
- }
- }
-
- /** Records whether or not a resource belonging to the plug-in in question was matched to a specific locale. */
- public void setResourceCoverageForLocale(LocaleProxy locale, ResourceProxy resource, Boolean matched, int propertiesCoverage) {
- if (this.resourceCoverage.containsKey(resource.getRelativePath())) {
- ResourceCoverageInformation info = this.resourceCoverage.get(resource.getRelativePath());
- info.setMatchingForLocale(locale, matched);
- info.setMatchedPercentageForLocale(locale, propertiesCoverage);
- } else {
- ResourceCoverageInformation info = new ResourceCoverageInformation(resource);
- info.setMatchingForLocale(locale, matched);
- info.setMatchedPercentageForLocale(locale, propertiesCoverage);
- this.resourceCoverage.put(resource.getRelativePath(), info);
-
- }
- }
+ public PluginCoverageInformation(PluginProxy eclipseArchivePlugin) {
+ super();
+ this.eclipseArchivePlugin = eclipseArchivePlugin;
+ }
- /** Returns coverage information about resource belonging to the plug-in in question */
- public Map<String, ResourceCoverageInformation> getResourceCoverage() {
- return resourceCoverage;
- }
+ /** Returns a PluginProxy which represents the plug-in in question. */
+ public PluginProxy getEclipseArchivePlugin() {
+ return eclipseArchivePlugin;
+ }
+
+ /**
+ * Returns a map which, for each locale, indicates whether or not plug-in
+ * was matched.
+ */
+ public Map<LocaleProxy, Boolean> getPluginMatchingPerLocale() {
+ return this.pluginMatchingPerLocale;
+ }
+
+ /** Given a specific locale, indicates whether or not plug-in was matched. */
+ public Boolean getPluginMatchingForLocale(String locale) {
+ for (LocaleProxy localeFromList : pluginMatchingPerLocale.keySet()) {
+ if (localeFromList.getName().compareToIgnoreCase(locale) == 0) {
+ return this.pluginMatchingPerLocale.get(localeFromList);
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Records whether or not the plug-in in question was matched to a specific
+ * locale.
+ */
+ public void setPluginMatchingForLocale(LocaleProxy locale, Boolean matched) {
+ this.pluginMatchingPerLocale.put(locale, matched);
+ }
+
+ /**
+ * Records whether or not a resource belonging to the plug-in in question
+ * was matched to a specific locale.
+ */
+ public void setResourceCoverageForLocale(LocaleProxy locale,
+ ResourceProxy resource, Boolean matched) {
+ if (this.resourceCoverage.containsKey(resource.getRelativePath())) {
+ ResourceCoverageInformation info = this.resourceCoverage
+ .get(resource.getRelativePath());
+ info.setMatchingForLocale(locale, matched);
+ } else {
+ ResourceCoverageInformation info = new ResourceCoverageInformation(
+ resource);
+ info.setMatchingForLocale(locale, matched);
+ this.resourceCoverage.put(resource.getRelativePath(), info);
+
+ }
+ }
+
+ /**
+ * Records whether or not a resource belonging to the plug-in in question
+ * was matched to a specific locale.
+ */
+ public void setResourceCoverageForLocale(LocaleProxy locale,
+ ResourceProxy resource, Boolean matched, int propertiesCoverage) {
+ if (this.resourceCoverage.containsKey(resource.getRelativePath())) {
+ ResourceCoverageInformation info = this.resourceCoverage
+ .get(resource.getRelativePath());
+ info.setMatchingForLocale(locale, matched);
+ info.setMatchedPercentageForLocale(locale, propertiesCoverage);
+ } else {
+ ResourceCoverageInformation info = new ResourceCoverageInformation(
+ resource);
+ info.setMatchingForLocale(locale, matched);
+ info.setMatchedPercentageForLocale(locale, propertiesCoverage);
+ this.resourceCoverage.put(resource.getRelativePath(), info);
+
+ }
+ }
+
+ /**
+ * Returns coverage information about resource belonging to the plug-in in
+ * question
+ */
+ public Map<String, ResourceCoverageInformation> getResourceCoverage() {
+ return resourceCoverage;
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/coverage/ResourceCoverageInformation.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/coverage/ResourceCoverageInformation.java
index cff9c47..70931e0 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/coverage/ResourceCoverageInformation.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/coverage/ResourceCoverageInformation.java
@@ -18,51 +18,50 @@
import org.eclipse.babel.build.core.LocaleProxy;
import org.eclipse.babel.build.core.ResourceProxy;
-
public class ResourceCoverageInformation {
- private final ResourceProxy resource;
- private Map<LocaleProxy, Boolean> matchingByLocale = new HashMap<LocaleProxy, Boolean>();
- private Map<LocaleProxy, Integer> matchedPercentageForLocale = new HashMap<LocaleProxy, Integer>();
-
- public ResourceCoverageInformation(ResourceProxy resource){
- this.resource = resource;
- }
+ private final ResourceProxy resource;
+ private Map<LocaleProxy, Boolean> matchingByLocale = new HashMap<LocaleProxy, Boolean>();
+ private Map<LocaleProxy, Integer> matchedPercentageForLocale = new HashMap<LocaleProxy, Integer>();
- public ResourceProxy getResource() {
- return resource;
- }
-
- public void setMatchingForLocale(LocaleProxy locale, Boolean matched) {
- this.matchingByLocale.put(locale, matched);
- }
-
- public Boolean getMatchingForLocale(LocaleProxy locale) {
- return this.matchingByLocale.get(locale);
- }
-
- public Boolean getMatchingForLocale(String locale) {
- for (LocaleProxy localeFromList: matchingByLocale.keySet()) {
- if (localeFromList.getName().compareToIgnoreCase(locale) == 0) {
- return this.matchingByLocale.get(localeFromList);
- }
- }
-
- return false;
- }
-
- public void setMatchedPercentageForLocale(LocaleProxy locale, Integer value) {
- this.matchedPercentageForLocale.put(locale, value);
- }
-
- public Integer getMatchedPercentageForLocale(LocaleProxy locale) {
- return this.matchedPercentageForLocale.get(locale);
- }
-
- public Set<LocaleProxy> getRecordedLocales() {
- return this.matchingByLocale.keySet();
- }
-
- public Map<LocaleProxy, Boolean> getLocaleMatchMap(){
- return Collections.unmodifiableMap(matchingByLocale);
- }
+ public ResourceCoverageInformation(ResourceProxy resource) {
+ this.resource = resource;
+ }
+
+ public ResourceProxy getResource() {
+ return resource;
+ }
+
+ public void setMatchingForLocale(LocaleProxy locale, Boolean matched) {
+ this.matchingByLocale.put(locale, matched);
+ }
+
+ public Boolean getMatchingForLocale(LocaleProxy locale) {
+ return this.matchingByLocale.get(locale);
+ }
+
+ public Boolean getMatchingForLocale(String locale) {
+ for (LocaleProxy localeFromList : matchingByLocale.keySet()) {
+ if (localeFromList.getName().compareToIgnoreCase(locale) == 0) {
+ return this.matchingByLocale.get(localeFromList);
+ }
+ }
+
+ return false;
+ }
+
+ public void setMatchedPercentageForLocale(LocaleProxy locale, Integer value) {
+ this.matchedPercentageForLocale.put(locale, value);
+ }
+
+ public Integer getMatchedPercentageForLocale(LocaleProxy locale) {
+ return this.matchedPercentageForLocale.get(locale);
+ }
+
+ public Set<LocaleProxy> getRecordedLocales() {
+ return this.matchingByLocale.keySet();
+ }
+
+ public Map<LocaleProxy, Boolean> getLocaleMatchMap() {
+ return Collections.unmodifiableMap(matchingByLocale);
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/EclipseArchiveInstallParser.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/EclipseArchiveInstallParser.java
index 5866fd6..a7986c1 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/EclipseArchiveInstallParser.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/EclipseArchiveInstallParser.java
@@ -29,331 +29,381 @@
import org.eclipse.babel.build.core.ResourceProxy;
import org.eclipse.babel.build.core.exceptions.InvalidLocationException;
-
public class EclipseArchiveInstallParser implements EclipseParser {
- private ZipFile eclipseArchive;
- private File archiveLocation;
-
- //The lists of plug-ins/features will be stored in maps for faster lookup
- private Map<String, PluginProxy> plugins = new HashMap<String, PluginProxy>();
- private Map<String, PluginProxy> features = new HashMap<String, PluginProxy>();
-
- private Set<String> excludeList;
-
- public EclipseArchiveInstallParser(ZipFile eclipseArchive, File archiveLocation) throws InvalidLocationException {
- this.eclipseArchive = eclipseArchive;
- this.archiveLocation = archiveLocation;
-
- validateTarget();
- useDefaultList();
- }
-
- public EclipseArchiveInstallParser(ZipFile eclipseArchive, File archiveLocation, Set<String> excludeList) throws InvalidLocationException {
- this.eclipseArchive = eclipseArchive;
- this.archiveLocation = archiveLocation;
-
- validateTarget();
-
- useDefaultList();
- this.excludeList.addAll(excludeList);
- }
-
- @SuppressWarnings("unchecked")
- private void validateTarget() throws InvalidLocationException {
- boolean foundPluginsPath = false;
- boolean foundFeaturesPath = false;
- for (Enumeration entries = eclipseArchive.entries(); entries.hasMoreElements();) {
- ZipEntry entry = (ZipEntry)entries.nextElement();
-
- if (entry.getName().contains(PLUGINS_PATH)) {
- foundPluginsPath = true;
- } else if (entry.getName().contains(FEATURES_PATH)) {
- foundFeaturesPath = true;
- }
- }
- if ( (!foundFeaturesPath) || (!foundPluginsPath) ) {
- throw new InvalidLocationException();
- }
- }
-
- private class ExtractionParameters {
- List<ResourceProxy> resourcesOfLastPlugin = new LinkedList<ResourceProxy>();
- ZipEntry entry;
- ZipEntry lastPluginOrFeatureEntry = null;
- String name;
- String tempPluginOrFeaturePath;
- String lastPluginOrFeature = PLUGIN_MASK;
- String lastPluginOrFeaturePath = ""; //$NON-NLS-1$
-
- public List<ResourceProxy> getResourcesOfLastPlugin() {
- return resourcesOfLastPlugin;
- }
- public ZipEntry getEntry() {
- return entry;
- }
- public ZipEntry getLastPluginOrFeatureEntry() {
- return lastPluginOrFeatureEntry;
- }
- public String getName() {
- return name;
- }
- public String getTempPluginOrFeaturePath() {
- return tempPluginOrFeaturePath;
- }
- public String getLastPluginOrFeature() {
- return lastPluginOrFeature;
- }
- public String getLastPluginOrFeaturePath() {
- return lastPluginOrFeaturePath;
- }
- public void setResourcesOfLastPlugin(List<ResourceProxy> resourcesOfLastPlugin) {
- this.resourcesOfLastPlugin = resourcesOfLastPlugin;
- }
- public void setEntry(ZipEntry entry) {
- this.entry = entry;
- }
- public void setLastPluginOrFeatureEntry(ZipEntry lastPluginOrFeatureEntry) {
- this.lastPluginOrFeatureEntry = lastPluginOrFeatureEntry;
- }
- public void setName(String name) {
- this.name = name;
- }
- public void setTempPluginOrFeaturePath(String tempPluginOrFeaturePath) {
- this.tempPluginOrFeaturePath = tempPluginOrFeaturePath;
- }
- public void setLastPluginOrFeature(String lastPluginOrFeature) {
- this.lastPluginOrFeature = lastPluginOrFeature;
- }
- public void setLastPluginOrFeaturePath(String lastPluginOrFeaturePath) {
- this.lastPluginOrFeaturePath = lastPluginOrFeaturePath;
- }
- }
-
- @SuppressWarnings("unchecked")
- public void parse() throws Exception {
- ExtractionParameters parameters = new ExtractionParameters();
-
- boolean ignorePlugin = false;
-
- for (Enumeration entries = eclipseArchive.entries(); entries.hasMoreElements();) {
- parameters.setEntry( (ZipEntry)entries.nextElement() );
- parameters.setName( parameters.getEntry().getName() );
-
- if (parameters.getName().equalsIgnoreCase(PLUGINS_PATH)
- || parameters.getName().equalsIgnoreCase(FEATURES_PATH)) {
- //Ignore case
- }
- /** Potential Non-JARed Plug-in or Feature */
- else if (parameters.getName().endsWith(DIRECTORY_SUFFIX) && (parameters.getName().contains(PLUGINS_PATH)
- || parameters.getName().contains(FEATURES_PATH))) {
-
- if (parameters.getName().contains(PLUGINS_PATH)) {
- parameters.setTempPluginOrFeaturePath(PLUGINS_PATH);
- }
- else {
- parameters.setTempPluginOrFeaturePath(FEATURES_PATH);
- }
- parameters.setName( removePluginOrFeaturePath(parameters.getName(), 1) );
-
- /** Non-JARed Plug-in */
- if (!parameters.getName().contains(DIRECTORY_SUFFIX)) {
- boolean ignorePrevious = ignorePlugin;
- if (!isValidPlugin(parameters.getName())) {
- ignorePlugin = true;
- } else {
- ignorePlugin = false;
- }
- handleNonJarPluginOrFeature(parameters, ignorePrevious);
- }
- }
- /** Plug-in JAR */
- else if ( parameters.getName().endsWith(JAR_EXTENSION) &&
- (!parameters.getName().contains(parameters.getLastPluginOrFeature())) &&
- (isValidPlugin(parameters.getName())) ) {
- handleJarPlugin(parameters);
- }
- else if ( parameters.getName().endsWith(JAR_EXTENSION) &&
- (parameters.getName().contains(parameters.getLastPluginOrFeature())) &&
- (isValidResource(parameters.getName())) ) {
- handleJarResource(parameters);
- }
- /** Translatable Resource for Non-JARed Plug-in or Feature*/
- else if ( isTranslatableResource(parameters.getName(), parameters) && (!ignorePlugin) ) {
- handleTranslatableResource(parameters);
- }
- }
-
- handleLastPluginOrFeatureEntry(parameters);
- }
-
- private void handleJarResource(ExtractionParameters parameters) throws Exception {
- List<ResourceProxy> jarResources = new ArrayList<ResourceProxy>();
-
- String frontRelativePath = "";
-
- if (parameters.getName().contains(DIRECTORY_SUFFIX)) {
- frontRelativePath = parameters.getName().substring(parameters.getName().lastIndexOf(DIRECTORY_SUFFIX)+1);
- }
- frontRelativePath = frontRelativePath.replaceAll(JAR_EXTENSION, "");
- frontRelativePath += "_jar";
-
- InputStream input = eclipseArchive.getInputStream(parameters.getEntry());
- ZipInputStream zipInput = new ZipInputStream(input);
-
- ZipEntry zipEntry = zipInput.getNextEntry();
- while(zipEntry != null) {
- String resourceEntryName = zipEntry.getName();
-
- if ( isValidResource(resourceEntryName) && (!resourceEntryName.contains(META_INF_DIR_NAME))) {
- String relativePath = frontRelativePath + File.separator + resourceEntryName;
- relativePath = relativePath.replace("\\", File.separator);
- relativePath = relativePath.replace("/", File.separator);
- jarResources.add(new ResourceProxy(
- new File(archiveLocation.getAbsolutePath() + SLASH
- + parameters.getName() + SLASH + resourceEntryName), relativePath)); //$NON-NLS-1$ //$NON-NLS-2$
- }
+ private ZipFile eclipseArchive;
+ private File archiveLocation;
- zipEntry = zipInput.getNextEntry();
- }
-
- parameters.getResourcesOfLastPlugin().addAll(jarResources);
- }
-
- private void handleNonJarPluginOrFeature(ExtractionParameters parameters, boolean ignorePrevious) {
- //If it's not the first plug-in/feature that we come across
- if (!parameters.getLastPluginOrFeature().equals(PLUGIN_MASK) && (!ignorePrevious)) {
- PluginProxy newPlugin;
-
- String lastEntryName = parameters.getLastPluginOrFeatureEntry().getName();
- if (!lastEntryName.startsWith(File.separator)) {
- lastEntryName = File.separator + lastEntryName;
- }
-
- if (parameters.getLastPluginOrFeaturePath().equals(PLUGINS_PATH)) {
- newPlugin = new PluginProxy(new File(archiveLocation.getAbsolutePath(),
- lastEntryName),
- parameters.getResourcesOfLastPlugin(), false, false);
- plugins.put(newPlugin.getName(), newPlugin);
- }
- else {
- newPlugin = new PluginProxy(new File(archiveLocation.getAbsolutePath(),
- lastEntryName),
- parameters.getResourcesOfLastPlugin(), false, true);
- features.put(newPlugin.getName(), newPlugin);
- }
- parameters.setResourcesOfLastPlugin( new LinkedList<ResourceProxy>() );
- }
-
- parameters.setLastPluginOrFeature( parameters.getName() );
- parameters.setLastPluginOrFeatureEntry( parameters.getEntry() );
- parameters.setLastPluginOrFeaturePath( parameters.getTempPluginOrFeaturePath() );
- }
-
- private void handleJarPlugin(ExtractionParameters parameters) throws Exception {
- List<ResourceProxy> jarResources = new LinkedList<ResourceProxy>();
- parameters.setName( removePluginOrFeaturePath(parameters.getName(), 0) );
- parameters.setName( parameters.getName().replaceAll(JAR_EXTENSION, "") ); //$NON-NLS-1$
-
- InputStream input = eclipseArchive.getInputStream(parameters.getEntry());
- ZipInputStream zipInput = new ZipInputStream(input);
-
- ZipEntry zipEntry = zipInput.getNextEntry();
- while(zipEntry != null) {
- String resourceEntryName = zipEntry.getName();
-
- if ( isValidResource(resourceEntryName) ) {
- jarResources.add(new ResourceProxy(
- new File(archiveLocation.getAbsolutePath() + File.separator +
- parameters.getEntry().getName() + File.separator + resourceEntryName), resourceEntryName)); //$NON-NLS-1$ //$NON-NLS-2$
- }
+ // The lists of plug-ins/features will be stored in maps for faster lookup
+ private Map<String, PluginProxy> plugins = new HashMap<String, PluginProxy>();
+ private Map<String, PluginProxy> features = new HashMap<String, PluginProxy>();
- zipEntry = zipInput.getNextEntry();
- }
-
- PluginProxy newPlugin = new PluginProxy(new File(archiveLocation.getAbsolutePath(),
- parameters.getEntry().getName()), jarResources, true, false);
- plugins.put(newPlugin.getName(), newPlugin);
- }
-
- private boolean isTranslatableResource(String resourceName, ExtractionParameters parameters) {
- return isValidResource(resourceName)
- && (resourceName.startsWith(PLUGINS_PATH) || resourceName.startsWith(FEATURES_PATH));
- }
-
- private boolean isValidPlugin(String name) {
- name = removePluginOrFeaturePath(name, 0);
- for (String exclude : this.excludeList) {
- if (name.matches(exclude)) {
- return false;
- }
- }
- return true;
- }
-
- private boolean isValidResource(String name) {
- if (name.contains(DIRECTORY_SUFFIX)) {
- name = name.substring(name.lastIndexOf(DIRECTORY_SUFFIX)+1);
-
- if (name.length() == 0) {
- return false;
- }
- }
- for (String exclude : this.excludeList) {
- if (name.matches(exclude)) {
- return false;
- }
- }
- return true;
- }
-
- private void handleTranslatableResource(ExtractionParameters parameters) {
- String resource = removePluginOrFeaturePath(parameters.getName(), 0);
- resource = resource.replaceAll(parameters.getLastPluginOrFeature(), ""); //$NON-NLS-1$
- parameters.getResourcesOfLastPlugin().add(new ResourceProxy(new File(eclipseArchive.getName() +
- Messages.getString("Characters_entry_separator") + parameters.getName()), resource.substring(1))); //$NON-NLS-1$
- }
-
- private void handleLastPluginOrFeatureEntry(ExtractionParameters parameters) {
- if (parameters.getLastPluginOrFeatureEntry() != null) {
- //Add last feature or plug-in
- PluginProxy newPlugin;
- if (parameters.getLastPluginOrFeaturePath().equals(PLUGINS_PATH)) {
- newPlugin = new PluginProxy(new File(archiveLocation.getAbsolutePath(),
- parameters.getLastPluginOrFeatureEntry().getName()), parameters.getResourcesOfLastPlugin(), false, false);
- plugins.put(newPlugin.getName(), newPlugin);
- }
- else {
- newPlugin = new PluginProxy(new File(archiveLocation.getAbsolutePath(),
- parameters.getLastPluginOrFeatureEntry().getName()), parameters.getResourcesOfLastPlugin(), false, true);
- features.put(newPlugin.getName(), newPlugin);
- }
- }
- parameters.setResourcesOfLastPlugin( new LinkedList<ResourceProxy>() );
- }
-
- private String removePluginOrFeaturePath(String name, int charactersToRemoveAtEnd) {
- name = name.replaceAll(PLUGINS_PATH, ""); //$NON-NLS-1$
- name = name.replaceAll(FEATURES_PATH, ""); //$NON-NLS-1$
- name = name.substring(0, name.length() - charactersToRemoveAtEnd);
- return name;
- }
-
- private void useDefaultList() {
- this.excludeList = new HashSet<String>();
- for ( String exclude : DEFAULT_EXCLUDE_LIST) {
- this.excludeList.add(exclude);
- }
+ private Set<String> excludeList;
- this.excludeList.add(PATTERN_DIR);
+ public EclipseArchiveInstallParser(ZipFile eclipseArchive,
+ File archiveLocation) throws InvalidLocationException {
+ this.eclipseArchive = eclipseArchive;
+ this.archiveLocation = archiveLocation;
- }
-
- public Map<String, PluginProxy> getPlugins() {
- return plugins;
- }
+ validateTarget();
+ useDefaultList();
+ }
- public Map<String, PluginProxy> getFeatures() {
- return features;
- }
+ public EclipseArchiveInstallParser(ZipFile eclipseArchive,
+ File archiveLocation, Set<String> excludeList)
+ throws InvalidLocationException {
+ this.eclipseArchive = eclipseArchive;
+ this.archiveLocation = archiveLocation;
+
+ validateTarget();
+
+ useDefaultList();
+ this.excludeList.addAll(excludeList);
+ }
+
+ @SuppressWarnings("unchecked")
+ private void validateTarget() throws InvalidLocationException {
+ boolean foundPluginsPath = false;
+ boolean foundFeaturesPath = false;
+ for (Enumeration entries = eclipseArchive.entries(); entries
+ .hasMoreElements();) {
+ ZipEntry entry = (ZipEntry) entries.nextElement();
+
+ if (entry.getName().contains(PLUGINS_PATH)) {
+ foundPluginsPath = true;
+ } else if (entry.getName().contains(FEATURES_PATH)) {
+ foundFeaturesPath = true;
+ }
+ }
+ if ((!foundFeaturesPath) || (!foundPluginsPath)) {
+ throw new InvalidLocationException();
+ }
+ }
+
+ private class ExtractionParameters {
+ List<ResourceProxy> resourcesOfLastPlugin = new LinkedList<ResourceProxy>();
+ ZipEntry entry;
+ ZipEntry lastPluginOrFeatureEntry = null;
+ String name;
+ String tempPluginOrFeaturePath;
+ String lastPluginOrFeature = PLUGIN_MASK;
+ String lastPluginOrFeaturePath = ""; //$NON-NLS-1$
+
+ public List<ResourceProxy> getResourcesOfLastPlugin() {
+ return resourcesOfLastPlugin;
+ }
+
+ public ZipEntry getEntry() {
+ return entry;
+ }
+
+ public ZipEntry getLastPluginOrFeatureEntry() {
+ return lastPluginOrFeatureEntry;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getTempPluginOrFeaturePath() {
+ return tempPluginOrFeaturePath;
+ }
+
+ public String getLastPluginOrFeature() {
+ return lastPluginOrFeature;
+ }
+
+ public String getLastPluginOrFeaturePath() {
+ return lastPluginOrFeaturePath;
+ }
+
+ public void setResourcesOfLastPlugin(
+ List<ResourceProxy> resourcesOfLastPlugin) {
+ this.resourcesOfLastPlugin = resourcesOfLastPlugin;
+ }
+
+ public void setEntry(ZipEntry entry) {
+ this.entry = entry;
+ }
+
+ public void setLastPluginOrFeatureEntry(
+ ZipEntry lastPluginOrFeatureEntry) {
+ this.lastPluginOrFeatureEntry = lastPluginOrFeatureEntry;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setTempPluginOrFeaturePath(String tempPluginOrFeaturePath) {
+ this.tempPluginOrFeaturePath = tempPluginOrFeaturePath;
+ }
+
+ public void setLastPluginOrFeature(String lastPluginOrFeature) {
+ this.lastPluginOrFeature = lastPluginOrFeature;
+ }
+
+ public void setLastPluginOrFeaturePath(String lastPluginOrFeaturePath) {
+ this.lastPluginOrFeaturePath = lastPluginOrFeaturePath;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public void parse() throws Exception {
+ ExtractionParameters parameters = new ExtractionParameters();
+
+ boolean ignorePlugin = false;
+
+ for (Enumeration entries = eclipseArchive.entries(); entries
+ .hasMoreElements();) {
+ parameters.setEntry((ZipEntry) entries.nextElement());
+ parameters.setName(parameters.getEntry().getName());
+
+ if (parameters.getName().equalsIgnoreCase(PLUGINS_PATH)
+ || parameters.getName().equalsIgnoreCase(FEATURES_PATH)) {
+ // Ignore case
+ }
+ /** Potential Non-JARed Plug-in or Feature */
+ else if (parameters.getName().endsWith(DIRECTORY_SUFFIX)
+ && (parameters.getName().contains(PLUGINS_PATH) || parameters
+ .getName().contains(FEATURES_PATH))) {
+
+ if (parameters.getName().contains(PLUGINS_PATH)) {
+ parameters.setTempPluginOrFeaturePath(PLUGINS_PATH);
+ } else {
+ parameters.setTempPluginOrFeaturePath(FEATURES_PATH);
+ }
+ parameters.setName(removePluginOrFeaturePath(
+ parameters.getName(), 1));
+
+ /** Non-JARed Plug-in */
+ if (!parameters.getName().contains(DIRECTORY_SUFFIX)) {
+ boolean ignorePrevious = ignorePlugin;
+ if (!isValidPlugin(parameters.getName())) {
+ ignorePlugin = true;
+ } else {
+ ignorePlugin = false;
+ }
+ handleNonJarPluginOrFeature(parameters, ignorePrevious);
+ }
+ }
+ /** Plug-in JAR */
+ else if (parameters.getName().endsWith(JAR_EXTENSION)
+ && (!parameters.getName().contains(
+ parameters.getLastPluginOrFeature()))
+ && (isValidPlugin(parameters.getName()))) {
+ handleJarPlugin(parameters);
+ } else if (parameters.getName().endsWith(JAR_EXTENSION)
+ && (parameters.getName().contains(parameters
+ .getLastPluginOrFeature()))
+ && (isValidResource(parameters.getName()))) {
+ handleJarResource(parameters);
+ }
+ /** Translatable Resource for Non-JARed Plug-in or Feature */
+ else if (isTranslatableResource(parameters.getName(), parameters)
+ && (!ignorePlugin)) {
+ handleTranslatableResource(parameters);
+ }
+ }
+
+ handleLastPluginOrFeatureEntry(parameters);
+ }
+
+ private void handleJarResource(ExtractionParameters parameters)
+ throws Exception {
+ List<ResourceProxy> jarResources = new ArrayList<ResourceProxy>();
+
+ String frontRelativePath = "";
+
+ if (parameters.getName().contains(DIRECTORY_SUFFIX)) {
+ frontRelativePath = parameters.getName().substring(
+ parameters.getName().lastIndexOf(DIRECTORY_SUFFIX) + 1);
+ }
+ frontRelativePath = frontRelativePath.replaceAll(JAR_EXTENSION, "");
+ frontRelativePath += "_jar";
+
+ InputStream input = eclipseArchive
+ .getInputStream(parameters.getEntry());
+ ZipInputStream zipInput = new ZipInputStream(input);
+
+ ZipEntry zipEntry = zipInput.getNextEntry();
+ while (zipEntry != null) {
+ String resourceEntryName = zipEntry.getName();
+
+ if (isValidResource(resourceEntryName)
+ && (!resourceEntryName.contains(META_INF_DIR_NAME))) {
+ String relativePath = frontRelativePath + File.separator
+ + resourceEntryName;
+ relativePath = relativePath.replace("\\", File.separator);
+ relativePath = relativePath.replace("/", File.separator);
+ jarResources.add(new ResourceProxy(new File(archiveLocation
+ .getAbsolutePath()
+ + SLASH
+ + parameters.getName()
+ + SLASH + resourceEntryName), relativePath)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ zipEntry = zipInput.getNextEntry();
+ }
+
+ parameters.getResourcesOfLastPlugin().addAll(jarResources);
+ }
+
+ private void handleNonJarPluginOrFeature(ExtractionParameters parameters,
+ boolean ignorePrevious) {
+ // If it's not the first plug-in/feature that we come across
+ if (!parameters.getLastPluginOrFeature().equals(PLUGIN_MASK)
+ && (!ignorePrevious)) {
+ PluginProxy newPlugin;
+
+ String lastEntryName = parameters.getLastPluginOrFeatureEntry()
+ .getName();
+ if (!lastEntryName.startsWith(File.separator)) {
+ lastEntryName = File.separator + lastEntryName;
+ }
+
+ if (parameters.getLastPluginOrFeaturePath().equals(PLUGINS_PATH)) {
+ newPlugin = new PluginProxy(new File(
+ archiveLocation.getAbsolutePath(), lastEntryName),
+ parameters.getResourcesOfLastPlugin(), false, false);
+ plugins.put(newPlugin.getName(), newPlugin);
+ } else {
+ newPlugin = new PluginProxy(new File(
+ archiveLocation.getAbsolutePath(), lastEntryName),
+ parameters.getResourcesOfLastPlugin(), false, true);
+ features.put(newPlugin.getName(), newPlugin);
+ }
+ parameters
+ .setResourcesOfLastPlugin(new LinkedList<ResourceProxy>());
+ }
+
+ parameters.setLastPluginOrFeature(parameters.getName());
+ parameters.setLastPluginOrFeatureEntry(parameters.getEntry());
+ parameters.setLastPluginOrFeaturePath(parameters
+ .getTempPluginOrFeaturePath());
+ }
+
+ private void handleJarPlugin(ExtractionParameters parameters)
+ throws Exception {
+ List<ResourceProxy> jarResources = new LinkedList<ResourceProxy>();
+ parameters.setName(removePluginOrFeaturePath(parameters.getName(), 0));
+ parameters.setName(parameters.getName().replaceAll(JAR_EXTENSION, "")); //$NON-NLS-1$
+
+ InputStream input = eclipseArchive
+ .getInputStream(parameters.getEntry());
+ ZipInputStream zipInput = new ZipInputStream(input);
+
+ ZipEntry zipEntry = zipInput.getNextEntry();
+ while (zipEntry != null) {
+ String resourceEntryName = zipEntry.getName();
+
+ if (isValidResource(resourceEntryName)) {
+ jarResources.add(new ResourceProxy(new File(archiveLocation
+ .getAbsolutePath()
+ + File.separator
+ + parameters.getEntry().getName()
+ + File.separator
+ + resourceEntryName), resourceEntryName)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ zipEntry = zipInput.getNextEntry();
+ }
+
+ PluginProxy newPlugin = new PluginProxy(new File(
+ archiveLocation.getAbsolutePath(), parameters.getEntry()
+ .getName()), jarResources, true, false);
+ plugins.put(newPlugin.getName(), newPlugin);
+ }
+
+ private boolean isTranslatableResource(String resourceName,
+ ExtractionParameters parameters) {
+ return isValidResource(resourceName)
+ && (resourceName.startsWith(PLUGINS_PATH) || resourceName
+ .startsWith(FEATURES_PATH));
+ }
+
+ private boolean isValidPlugin(String name) {
+ name = removePluginOrFeaturePath(name, 0);
+ for (String exclude : this.excludeList) {
+ if (name.matches(exclude)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean isValidResource(String name) {
+ if (name.contains(DIRECTORY_SUFFIX)) {
+ name = name.substring(name.lastIndexOf(DIRECTORY_SUFFIX) + 1);
+
+ if (name.length() == 0) {
+ return false;
+ }
+ }
+ for (String exclude : this.excludeList) {
+ if (name.matches(exclude)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private void handleTranslatableResource(ExtractionParameters parameters) {
+ String resource = removePluginOrFeaturePath(parameters.getName(), 0);
+ resource = resource.replaceAll(parameters.getLastPluginOrFeature(), ""); //$NON-NLS-1$
+ parameters
+ .getResourcesOfLastPlugin()
+ .add(new ResourceProxy(
+ new File(
+ eclipseArchive.getName()
+ + Messages
+ .getString("Characters_entry_separator") + parameters.getName()), resource.substring(1))); //$NON-NLS-1$
+ }
+
+ private void handleLastPluginOrFeatureEntry(ExtractionParameters parameters) {
+ if (parameters.getLastPluginOrFeatureEntry() != null) {
+ // Add last feature or plug-in
+ PluginProxy newPlugin;
+ if (parameters.getLastPluginOrFeaturePath().equals(PLUGINS_PATH)) {
+ newPlugin = new PluginProxy(new File(
+ archiveLocation.getAbsolutePath(), parameters
+ .getLastPluginOrFeatureEntry().getName()),
+ parameters.getResourcesOfLastPlugin(), false, false);
+ plugins.put(newPlugin.getName(), newPlugin);
+ } else {
+ newPlugin = new PluginProxy(new File(
+ archiveLocation.getAbsolutePath(), parameters
+ .getLastPluginOrFeatureEntry().getName()),
+ parameters.getResourcesOfLastPlugin(), false, true);
+ features.put(newPlugin.getName(), newPlugin);
+ }
+ }
+ parameters.setResourcesOfLastPlugin(new LinkedList<ResourceProxy>());
+ }
+
+ private String removePluginOrFeaturePath(String name,
+ int charactersToRemoveAtEnd) {
+ name = name.replaceAll(PLUGINS_PATH, ""); //$NON-NLS-1$
+ name = name.replaceAll(FEATURES_PATH, ""); //$NON-NLS-1$
+ name = name.substring(0, name.length() - charactersToRemoveAtEnd);
+ return name;
+ }
+
+ private void useDefaultList() {
+ this.excludeList = new HashSet<String>();
+ for (String exclude : DEFAULT_EXCLUDE_LIST) {
+ this.excludeList.add(exclude);
+ }
+
+ this.excludeList.add(PATTERN_DIR);
+
+ }
+
+ public Map<String, PluginProxy> getPlugins() {
+ return plugins;
+ }
+
+ public Map<String, PluginProxy> getFeatures() {
+ return features;
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/EclipseInstallParser.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/EclipseInstallParser.java
index 6574c0d..321b53d 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/EclipseInstallParser.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/EclipseInstallParser.java
@@ -31,210 +31,234 @@
import org.eclipse.babel.build.core.ResourceProxy;
import org.eclipse.babel.build.core.exceptions.InvalidLocationException;
-
public class EclipseInstallParser implements EclipseParser {
- private final static String PLUGINS_PATH = Messages.getString("Paths_plugins_directory"); //$NON-NLS-1$
- private final static String FEATURES_PATH = Messages.getString("Paths_features_directory"); //$NON-NLS-1$
-
- private Set<String> excludeList = new HashSet<String>();
-
- private File eclipseInstallLocation;
- //The lists of plug-ins/features will be stored in maps for faster lookup
- private Map<String, PluginProxy> plugins = new HashMap<String, PluginProxy>();
- private Map<String, PluginProxy> features = new HashMap<String, PluginProxy>();
-
- public EclipseInstallParser(File eclipseInstallLocation) throws InvalidLocationException {
- this.eclipseInstallLocation = eclipseInstallLocation;
-
- validateTarget();
- useDefaultList();
- }
-
- public EclipseInstallParser(File eclipseInstallLocation, Set<String> excludeList) throws InvalidLocationException {
- this.eclipseInstallLocation = eclipseInstallLocation;
-
- validateTarget();
-
- useDefaultList();
- this.excludeList.addAll(excludeList);
- }
-
- private void validateTarget() throws InvalidLocationException {
- String pluginPath = Messages.getString("Paths_plugins_directory"); //$NON-NLS-1$
- pluginPath = pluginPath.replace(Messages.getString("Characters_entry_separator"), File.separator); //$NON-NLS-1$
- String featurePath = Messages.getString("Paths_features_directory"); //$NON-NLS-1$
- featurePath = featurePath.replace(Messages.getString("Characters_entry_separator"), File.separator); //$NON-NLS-1$
-
- File pluginDir = new File(this.eclipseInstallLocation.getAbsolutePath(), pluginPath);
- File featureDir = new File(this.eclipseInstallLocation.getAbsolutePath(), featurePath);
-
- if ( (!pluginDir.exists()) || (!featureDir.exists()) ) {
- throw new InvalidLocationException();
- }
- }
-
- public void parse() throws Exception {
-
- PluginProxy newPlugin;
- File pluginsRoot = new File(this.eclipseInstallLocation.getAbsolutePath() + File.separatorChar + PLUGINS_PATH);
-
- for (File plugin: pluginsRoot.listFiles()) {
- List<ResourceProxy> pluginResources;
- if (isValidPlugin(plugin.getName())) {
- if(plugin.isDirectory()) {
- pluginResources = extractResources(plugin, plugin.getName());
- newPlugin = new PluginProxy(plugin, pluginResources, false, false);
- plugins.put(newPlugin.getName(), newPlugin);
- } else {
- //Handle JAR Plug-in
- pluginResources = extractResourcesFromJar(plugin);
- newPlugin = new PluginProxy(plugin, pluginResources, true, false);
- plugins.put(newPlugin.getName(), newPlugin);
- }
- }
- }
-
- PluginProxy newFeature;
- File featuresRoot = new File(this.eclipseInstallLocation.getAbsolutePath() + File.separatorChar + FEATURES_PATH);
-
- for (File feature: featuresRoot.listFiles()) {
- List<ResourceProxy> featureResources;
- if (isValidPlugin(feature.getName())) {
- if(feature.isDirectory()) {
- featureResources = extractResources(feature, feature.getName());
- newFeature = new PluginProxy(feature, featureResources, false, true);
- features.put(newFeature.getName(), newFeature);
- } else {
- //Handle JAR Feature
- featureResources = extractResourcesFromJar(feature);
- newFeature = new PluginProxy(feature, featureResources, true, true);
- features.put(newFeature.getName(), newFeature);
- }
- }
- }
- }
-
- private List<ResourceProxy> extractResources(File file, String pluginName) throws Exception {
- List<ResourceProxy> resources = new LinkedList<ResourceProxy>();
- for (File subFile: file.listFiles()) {
- if (subFile.isDirectory()) {
- resources.addAll(extractResources(subFile, pluginName));
- }
- else {
- if (isValidResource(subFile.getName())) {
- if (subFile.getName().endsWith(JAR_EXTENSION)) {
- resources.addAll(handleJarResource(subFile));
- } else {
- String absolutePath = subFile.getAbsolutePath();
- String relativePath = absolutePath.substring(absolutePath.indexOf(pluginName));
- relativePath = relativePath.substring(pluginName.length() + 1);
- resources.add(new ResourceProxy(subFile, relativePath));
- }
- }
- }
- }
- return resources;
- }
-
- List<ResourceProxy> handleJarResource(File jarResource) throws Exception {
- List<ResourceProxy> jarResources = new ArrayList<ResourceProxy>();
-
- String frontRelativePath = jarResource.getName();
-
- frontRelativePath = frontRelativePath.replaceAll(JAR_EXTENSION, ""); //$NON-NLS-1$
- frontRelativePath += JAR_RESOURCE_SUFFIX;
-
- InputStream input = new FileInputStream(jarResource);
- JarInputStream zipInput = new JarInputStream(input);
-
- ZipEntry zipEntry = zipInput.getNextEntry();
- while(zipEntry != null) {
- String resourceEntryName = zipEntry.getName();
- resourceEntryName = resourceEntryName.replace("\\", SLASH); //$NON-NLS-1$
-
- if ( isValidResource(resourceEntryName) && (!resourceEntryName.contains(META_INF_DIR_NAME))) {
- String relativePath = frontRelativePath + File.separator + resourceEntryName;
- relativePath = relativePath.replace("\\", File.separator); //$NON-NLS-1$
- relativePath = relativePath.replace(SLASH, File.separator);
- jarResources.add(new ResourceProxy(new File(jarResource.getAbsolutePath() + SLASH
- + resourceEntryName), relativePath)); //$NON-NLS-1$ //$NON-NLS-2$
- }
+ private final static String PLUGINS_PATH = Messages
+ .getString("Paths_plugins_directory"); //$NON-NLS-1$
+ private final static String FEATURES_PATH = Messages
+ .getString("Paths_features_directory"); //$NON-NLS-1$
- zipEntry = zipInput.getNextEntry();
- }
-
- return jarResources;
- }
+ private Set<String> excludeList = new HashSet<String>();
- private List<ResourceProxy> extractResourcesFromJar(File file) {
- List<ResourceProxy> jarResources = new LinkedList<ResourceProxy>();
-
- try {
- JarFile jarPluginOrFeature = new JarFile(file);
-
- Enumeration<JarEntry> jarEntries = jarPluginOrFeature.entries();
-
- JarEntry jarEntry = jarEntries.nextElement();
- while (jarEntry != null) {
- String resourceEntryName = jarEntry.getName();
-
- if ( isValidResource(resourceEntryName) ) {
- jarResources.add(new ResourceProxy(
- new File(file.getAbsolutePath() + File.separator
- + resourceEntryName), resourceEntryName));
- }
-
- if (jarEntries.hasMoreElements()) {
- jarEntry = jarEntries.nextElement();
- } else {
- jarEntry = null;
- }
- }
-
- } catch (Exception e) {
- System.out.println(e.getMessage());
- }
-
- return jarResources;
- }
-
- private boolean isValidPlugin(String name) {
- for (String exclude : this.excludeList) {
- if (name.matches(exclude)) {
- return false;
- }
- }
- return true;
- }
-
- private boolean isValidResource(String name) {
- if (name.contains(DIRECTORY_SUFFIX)) {
- name = name.substring(name.lastIndexOf(DIRECTORY_SUFFIX)+1);
- if (name.length() == 0) {
- return false;
- }
- }
- for (String exclude : this.excludeList) {
- if (name.matches(exclude)) {
- return false;
- }
- }
- return true;
- }
-
- private void useDefaultList() {
- this.excludeList = new HashSet<String>();
- for ( String exclude : DEFAULT_EXCLUDE_LIST) {
- this.excludeList.add(exclude);
- }
- }
-
- public Map<String, PluginProxy> getPlugins() {
- return plugins;
- }
+ private File eclipseInstallLocation;
+ // The lists of plug-ins/features will be stored in maps for faster lookup
+ private Map<String, PluginProxy> plugins = new HashMap<String, PluginProxy>();
+ private Map<String, PluginProxy> features = new HashMap<String, PluginProxy>();
- public Map<String, PluginProxy> getFeatures() {
- return features;
- }
+ public EclipseInstallParser(File eclipseInstallLocation)
+ throws InvalidLocationException {
+ this.eclipseInstallLocation = eclipseInstallLocation;
+
+ validateTarget();
+ useDefaultList();
+ }
+
+ public EclipseInstallParser(File eclipseInstallLocation,
+ Set<String> excludeList) throws InvalidLocationException {
+ this.eclipseInstallLocation = eclipseInstallLocation;
+
+ validateTarget();
+
+ useDefaultList();
+ this.excludeList.addAll(excludeList);
+ }
+
+ private void validateTarget() throws InvalidLocationException {
+ String pluginPath = Messages.getString("Paths_plugins_directory"); //$NON-NLS-1$
+ pluginPath = pluginPath
+ .replace(
+ Messages.getString("Characters_entry_separator"), File.separator); //$NON-NLS-1$
+ String featurePath = Messages.getString("Paths_features_directory"); //$NON-NLS-1$
+ featurePath = featurePath
+ .replace(
+ Messages.getString("Characters_entry_separator"), File.separator); //$NON-NLS-1$
+
+ File pluginDir = new File(
+ this.eclipseInstallLocation.getAbsolutePath(), pluginPath);
+ File featureDir = new File(
+ this.eclipseInstallLocation.getAbsolutePath(), featurePath);
+
+ if ((!pluginDir.exists()) || (!featureDir.exists())) {
+ throw new InvalidLocationException();
+ }
+ }
+
+ public void parse() throws Exception {
+
+ PluginProxy newPlugin;
+ File pluginsRoot = new File(
+ this.eclipseInstallLocation.getAbsolutePath()
+ + File.separatorChar + PLUGINS_PATH);
+
+ for (File plugin : pluginsRoot.listFiles()) {
+ List<ResourceProxy> pluginResources;
+ if (isValidPlugin(plugin.getName())) {
+ if (plugin.isDirectory()) {
+ pluginResources = extractResources(plugin, plugin.getName());
+ newPlugin = new PluginProxy(plugin, pluginResources, false,
+ false);
+ plugins.put(newPlugin.getName(), newPlugin);
+ } else {
+ // Handle JAR Plug-in
+ pluginResources = extractResourcesFromJar(plugin);
+ newPlugin = new PluginProxy(plugin, pluginResources, true,
+ false);
+ plugins.put(newPlugin.getName(), newPlugin);
+ }
+ }
+ }
+
+ PluginProxy newFeature;
+ File featuresRoot = new File(
+ this.eclipseInstallLocation.getAbsolutePath()
+ + File.separatorChar + FEATURES_PATH);
+
+ for (File feature : featuresRoot.listFiles()) {
+ List<ResourceProxy> featureResources;
+ if (isValidPlugin(feature.getName())) {
+ if (feature.isDirectory()) {
+ featureResources = extractResources(feature,
+ feature.getName());
+ newFeature = new PluginProxy(feature, featureResources,
+ false, true);
+ features.put(newFeature.getName(), newFeature);
+ } else {
+ // Handle JAR Feature
+ featureResources = extractResourcesFromJar(feature);
+ newFeature = new PluginProxy(feature, featureResources,
+ true, true);
+ features.put(newFeature.getName(), newFeature);
+ }
+ }
+ }
+ }
+
+ private List<ResourceProxy> extractResources(File file, String pluginName)
+ throws Exception {
+ List<ResourceProxy> resources = new LinkedList<ResourceProxy>();
+ for (File subFile : file.listFiles()) {
+ if (subFile.isDirectory()) {
+ resources.addAll(extractResources(subFile, pluginName));
+ } else {
+ if (isValidResource(subFile.getName())) {
+ if (subFile.getName().endsWith(JAR_EXTENSION)) {
+ resources.addAll(handleJarResource(subFile));
+ } else {
+ String absolutePath = subFile.getAbsolutePath();
+ String relativePath = absolutePath
+ .substring(absolutePath.indexOf(pluginName));
+ relativePath = relativePath.substring(pluginName
+ .length() + 1);
+ resources.add(new ResourceProxy(subFile, relativePath));
+ }
+ }
+ }
+ }
+ return resources;
+ }
+
+ List<ResourceProxy> handleJarResource(File jarResource) throws Exception {
+ List<ResourceProxy> jarResources = new ArrayList<ResourceProxy>();
+
+ String frontRelativePath = jarResource.getName();
+
+ frontRelativePath = frontRelativePath.replaceAll(JAR_EXTENSION, ""); //$NON-NLS-1$
+ frontRelativePath += JAR_RESOURCE_SUFFIX;
+
+ InputStream input = new FileInputStream(jarResource);
+ JarInputStream zipInput = new JarInputStream(input);
+
+ ZipEntry zipEntry = zipInput.getNextEntry();
+ while (zipEntry != null) {
+ String resourceEntryName = zipEntry.getName();
+ resourceEntryName = resourceEntryName.replace("\\", SLASH); //$NON-NLS-1$
+
+ if (isValidResource(resourceEntryName)
+ && (!resourceEntryName.contains(META_INF_DIR_NAME))) {
+ String relativePath = frontRelativePath + File.separator
+ + resourceEntryName;
+ relativePath = relativePath.replace("\\", File.separator); //$NON-NLS-1$
+ relativePath = relativePath.replace(SLASH, File.separator);
+ jarResources.add(new ResourceProxy(new File(jarResource
+ .getAbsolutePath() + SLASH + resourceEntryName),
+ relativePath)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ zipEntry = zipInput.getNextEntry();
+ }
+
+ return jarResources;
+ }
+
+ private List<ResourceProxy> extractResourcesFromJar(File file) {
+ List<ResourceProxy> jarResources = new LinkedList<ResourceProxy>();
+
+ try {
+ JarFile jarPluginOrFeature = new JarFile(file);
+
+ Enumeration<JarEntry> jarEntries = jarPluginOrFeature.entries();
+
+ JarEntry jarEntry = jarEntries.nextElement();
+ while (jarEntry != null) {
+ String resourceEntryName = jarEntry.getName();
+
+ if (isValidResource(resourceEntryName)) {
+ jarResources.add(new ResourceProxy(new File(file
+ .getAbsolutePath()
+ + File.separator
+ + resourceEntryName), resourceEntryName));
+ }
+
+ if (jarEntries.hasMoreElements()) {
+ jarEntry = jarEntries.nextElement();
+ } else {
+ jarEntry = null;
+ }
+ }
+
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+
+ return jarResources;
+ }
+
+ private boolean isValidPlugin(String name) {
+ for (String exclude : this.excludeList) {
+ if (name.matches(exclude)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean isValidResource(String name) {
+ if (name.contains(DIRECTORY_SUFFIX)) {
+ name = name.substring(name.lastIndexOf(DIRECTORY_SUFFIX) + 1);
+ if (name.length() == 0) {
+ return false;
+ }
+ }
+ for (String exclude : this.excludeList) {
+ if (name.matches(exclude)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private void useDefaultList() {
+ this.excludeList = new HashSet<String>();
+ for (String exclude : DEFAULT_EXCLUDE_LIST) {
+ this.excludeList.add(exclude);
+ }
+ }
+
+ public Map<String, PluginProxy> getPlugins() {
+ return plugins;
+ }
+
+ public Map<String, PluginProxy> getFeatures() {
+ return features;
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/EclipseParser.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/EclipseParser.java
index 6d77077..363ce7f 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/EclipseParser.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/EclipseParser.java
@@ -15,33 +15,48 @@
import org.eclipse.babel.build.core.Messages;
import org.eclipse.babel.build.core.PluginProxy;
-
public interface EclipseParser {
-
- public final String JAR_EXTENSION = Messages.getString("Extensions_jar"); //$NON-NLS-1$
- public final String DIRECTORY_SUFFIX = Messages.getString("Suffixes_directory"); //$NON-NLS-1$
- public final String PLUGINS_PATH = Messages.getString("Paths_plugins_directory"); //$NON-NLS-1$
- public final String FEATURES_PATH = Messages.getString("Paths_features_directory"); //$NON-NLS-1$
- public final String SOURCE_SUFFIX = Messages.getString("Patterns_suffixes_source"); //$NON-NLS-1$
- public final String PLUGIN_MASK = Messages.getString("Masks_plugin"); //$NON-NLS-1$
- public final String JAVA_EXTENSION = Messages.getString("Extensions_java"); //$NON-NLS-1$
- public final String CLASS_EXTENSION = Messages.getString("Extensions_class"); //$NON-NLS-1$
- public final String PATTERN_DIR = Messages.getString("Patterns_non_jar_plugin"); //$NON-NLS-1$
- public final String META_INF_DIR_NAME = Messages.getString("Paths_meta_inf_directory"); //$NON-NLS-1$
- public final String JAR_RESOURCE_SUFFIX = Messages.getString("Suffixes_jar_resource_folder"); //$NON-NLS-1$
- public final String SLASH = Messages.getString("Characters_entry_separator"); //$NON-NLS-1$
-
- public final String[] DEFAULT_EXCLUDE_LIST = {PATTERN_DIR, SOURCE_SUFFIX, JAVA_EXTENSION, CLASS_EXTENSION};
-
- /** Parses an eclipse install and populates the plug-ins/features and their resources
- in maps to be accessed at runtime. */
- public void parse() throws Exception;
-
- /** Returns the map containing the eclipse install plug-ins and their translatable
- * resources. */
- public Map<String, PluginProxy> getPlugins();
-
- /** Returns the map containing the eclipse install features and their translatable
- * resources. */
- public Map<String, PluginProxy> getFeatures();
+
+ public final String JAR_EXTENSION = Messages.getString("Extensions_jar"); //$NON-NLS-1$
+ public final String DIRECTORY_SUFFIX = Messages
+ .getString("Suffixes_directory"); //$NON-NLS-1$
+ public final String PLUGINS_PATH = Messages
+ .getString("Paths_plugins_directory"); //$NON-NLS-1$
+ public final String FEATURES_PATH = Messages
+ .getString("Paths_features_directory"); //$NON-NLS-1$
+ public final String SOURCE_SUFFIX = Messages
+ .getString("Patterns_suffixes_source"); //$NON-NLS-1$
+ public final String PLUGIN_MASK = Messages.getString("Masks_plugin"); //$NON-NLS-1$
+ public final String JAVA_EXTENSION = Messages.getString("Extensions_java"); //$NON-NLS-1$
+ public final String CLASS_EXTENSION = Messages
+ .getString("Extensions_class"); //$NON-NLS-1$
+ public final String PATTERN_DIR = Messages
+ .getString("Patterns_non_jar_plugin"); //$NON-NLS-1$
+ public final String META_INF_DIR_NAME = Messages
+ .getString("Paths_meta_inf_directory"); //$NON-NLS-1$
+ public final String JAR_RESOURCE_SUFFIX = Messages
+ .getString("Suffixes_jar_resource_folder"); //$NON-NLS-1$
+ public final String SLASH = Messages
+ .getString("Characters_entry_separator"); //$NON-NLS-1$
+
+ public final String[] DEFAULT_EXCLUDE_LIST = { PATTERN_DIR, SOURCE_SUFFIX,
+ JAVA_EXTENSION, CLASS_EXTENSION };
+
+ /**
+ * Parses an eclipse install and populates the plug-ins/features and their
+ * resources in maps to be accessed at runtime.
+ */
+ public void parse() throws Exception;
+
+ /**
+ * Returns the map containing the eclipse install plug-ins and their
+ * translatable resources.
+ */
+ public Map<String, PluginProxy> getPlugins();
+
+ /**
+ * Returns the map containing the eclipse install features and their
+ * translatable resources.
+ */
+ public Map<String, PluginProxy> getFeatures();
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/EclipseTarget.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/EclipseTarget.java
index f66eb99..61d2c1e 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/EclipseTarget.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/EclipseTarget.java
@@ -23,79 +23,81 @@
import org.eclipse.babel.build.core.exceptions.InvalidLocationException;
import org.eclipse.babel.build.core.exceptions.MissingLocationException;
-
public class EclipseTarget {
- private final File location;
- private final boolean isArchive;
- //The lists of plug-ins/features will be stored in maps for faster lookup
- Map<String, PluginProxy> plugins = new HashMap<String, PluginProxy>();
- Map<String, PluginProxy> features = new HashMap<String, PluginProxy>();
-
- private Set<String> excludeList;
-
- /**
- * @param plugins - The list of plug-ins chosen via the wizard.
- */
- public EclipseTarget(List<PluginProxy> plugins) {
- for (PluginProxy plugin : plugins) {
- this.plugins.put(plugin.getName(), plugin);
- }
-
- this.isArchive = false;
- this.location = new File( plugins.get(0).getPluginLocation().getParent() );
- }
-
- public EclipseTarget(File location, Set<String> excludeList) throws MissingLocationException, InvalidFilenameException {
- this.location = location.getAbsoluteFile();
-
- if (!this.location.exists()) {
- throw new MissingLocationException();
- }
-
- this.excludeList = excludeList;
-
- if (location.isDirectory()) {
- this.isArchive = false;
- } else {
- this.isArchive = true;
- }
- }
-
- /**
- * Manipulates an EclipseParser to parse and populate the plug-ins and features
- * in an Eclipse Install.
- */
- public void populatePlugins() throws Exception, InvalidLocationException {
- EclipseParser parser;
-
- if (!this.isArchive) {
- parser = new EclipseInstallParser(location, excludeList);
- } else {
- ZipFile eclipseArchive = new ZipFile(location);
- parser = new EclipseArchiveInstallParser(eclipseArchive, location, excludeList);
- }
-
- parser.parse();
-
- this.plugins = parser.getPlugins();
- this.features = parser.getFeatures();
- }
-
- public File getLocation(){
- return location;
- }
+ private final File location;
+ private final boolean isArchive;
+ // The lists of plug-ins/features will be stored in maps for faster lookup
+ Map<String, PluginProxy> plugins = new HashMap<String, PluginProxy>();
+ Map<String, PluginProxy> features = new HashMap<String, PluginProxy>();
- public Map<String, PluginProxy> getPlugins() {
- return Collections.unmodifiableMap(plugins);
- }
+ private Set<String> excludeList;
- public Map<String, PluginProxy> getFeatures() {
- return Collections.unmodifiableMap(features);
- }
+ /**
+ * @param plugins
+ * - The list of plug-ins chosen via the wizard.
+ */
+ public EclipseTarget(List<PluginProxy> plugins) {
+ for (PluginProxy plugin : plugins) {
+ this.plugins.put(plugin.getName(), plugin);
+ }
- /** Returns whether or not EclipseInstall is an archive. */
- public boolean isArchive() {
- return isArchive;
- }
+ this.isArchive = false;
+ this.location = new File(plugins.get(0).getPluginLocation().getParent());
+ }
+
+ public EclipseTarget(File location, Set<String> excludeList)
+ throws MissingLocationException, InvalidFilenameException {
+ this.location = location.getAbsoluteFile();
+
+ if (!this.location.exists()) {
+ throw new MissingLocationException();
+ }
+
+ this.excludeList = excludeList;
+
+ if (location.isDirectory()) {
+ this.isArchive = false;
+ } else {
+ this.isArchive = true;
+ }
+ }
+
+ /**
+ * Manipulates an EclipseParser to parse and populate the plug-ins and
+ * features in an Eclipse Install.
+ */
+ public void populatePlugins() throws Exception, InvalidLocationException {
+ EclipseParser parser;
+
+ if (!this.isArchive) {
+ parser = new EclipseInstallParser(location, excludeList);
+ } else {
+ ZipFile eclipseArchive = new ZipFile(location);
+ parser = new EclipseArchiveInstallParser(eclipseArchive, location,
+ excludeList);
+ }
+
+ parser.parse();
+
+ this.plugins = parser.getPlugins();
+ this.features = parser.getFeatures();
+ }
+
+ public File getLocation() {
+ return location;
+ }
+
+ public Map<String, PluginProxy> getPlugins() {
+ return Collections.unmodifiableMap(plugins);
+ }
+
+ public Map<String, PluginProxy> getFeatures() {
+ return Collections.unmodifiableMap(features);
+ }
+
+ /** Returns whether or not EclipseInstall is an archive. */
+ public boolean isArchive() {
+ return isArchive;
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/FragmentEclipseArchiveMediator.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/FragmentEclipseArchiveMediator.java
index f20d776..889ee31 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/FragmentEclipseArchiveMediator.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/FragmentEclipseArchiveMediator.java
@@ -31,122 +31,141 @@
import org.eclipse.babel.build.core.PluginProxy;
import org.eclipse.babel.build.core.ResourceProxy;
-
public class FragmentEclipseArchiveMediator implements
- FragmentEclipseTargetMediator {
+ FragmentEclipseTargetMediator {
- private PluginProxy eclipseInstallPlugin;
- private ZipFile eclipseArchive;
- private File eclipseArchiveLocation;
-
- public FragmentEclipseArchiveMediator(PluginProxy eclipseInstallPlugin, File eclipseArchiveLocation) throws Exception {
- this.eclipseInstallPlugin = eclipseInstallPlugin;
- this.eclipseArchive = new ZipFile(eclipseArchiveLocation);
- this.eclipseArchiveLocation = eclipseArchiveLocation;
- }
+ private PluginProxy eclipseInstallPlugin;
+ private ZipFile eclipseArchive;
+ private File eclipseArchiveLocation;
- public Map<String, Set<Object>> extractEclipseTargetProperties()
- throws ZipException, IOException, FileNotFoundException {
-
- Map<String, Set<Object>> propertiesMap = new HashMap<String, Set<Object>>();
-
- // Determine the entry name of the JAR plug-in
- InputStream jarPluginInputStream;
- String jarPluginRelativePath = eclipseInstallPlugin.getPluginLocation().getAbsolutePath().replace(eclipseArchiveLocation.getAbsolutePath(), "");
- jarPluginRelativePath = jarPluginRelativePath.substring(1);
- jarPluginRelativePath = jarPluginRelativePath.replace(
- File.separator, Messages.getString("Characters_entry_separator")); //$NON-NLS-1$
-
- // Extract the JAR plug-in entry form the eclipse archive
- ZipEntry jarPluginEntry = eclipseArchive.getEntry(jarPluginRelativePath);
- jarPluginInputStream = eclipseArchive.getInputStream(jarPluginEntry);
-
- JarInputStream inputStream = new JarInputStream(jarPluginInputStream);
-
- // Iterate through the plug-ins resources and store data on the properties files
- JarEntry entry;
- while (( entry = inputStream.getNextJarEntry() ) != null) {
- String entryName = entry.getName();
- if (entryName.endsWith(Messages.getString("Extensions_properties"))) { //$NON-NLS-1$
- Properties properties = new Properties();
- properties.load(inputStream);
- propertiesMap.put(entry.getName(), new HashSet<Object>(properties.keySet()));
- }
- }
- inputStream.close();
- jarPluginInputStream.close();
-
- return propertiesMap;
- }
+ public FragmentEclipseArchiveMediator(PluginProxy eclipseInstallPlugin,
+ File eclipseArchiveLocation) throws Exception {
+ this.eclipseInstallPlugin = eclipseInstallPlugin;
+ this.eclipseArchive = new ZipFile(eclipseArchiveLocation);
+ this.eclipseArchiveLocation = eclipseArchiveLocation;
+ }
- public InputStream getResourceAsStream(ResourceProxy resource)
- throws ZipException, IOException, FileNotFoundException, Exception {
+ public Map<String, Set<Object>> extractEclipseTargetProperties()
+ throws ZipException, IOException, FileNotFoundException {
- String resourcePath = Messages.getString("Paths_eclipse_directory_name") + SLASH
- + (eclipseInstallPlugin.isFeature() ? "features" : "plugins")
- + SLASH + eclipseInstallPlugin.getName() + Messages.getString("Characters_underscore")
- + eclipseInstallPlugin.getVersion() + SLASH + resource.getCanonicalPath(); //$NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$ $NON-NLS-4$
-
- ZipEntry resourceFile = eclipseArchive.getEntry(resourcePath);
- if (resourceFile == null) {
- return null;
- }
- return eclipseArchive.getInputStream(resourceFile);
- }
+ Map<String, Set<Object>> propertiesMap = new HashMap<String, Set<Object>>();
- public boolean writeAboutHtmlFile(File resource, JarOutputStream out) throws Exception {
- String pluginRelativePath = eclipseInstallPlugin.getPluginLocation().getAbsolutePath().replace(eclipseArchiveLocation.getAbsolutePath(), "");
- pluginRelativePath = pluginRelativePath.substring(1);
- pluginRelativePath = pluginRelativePath.replace(
- File.separator, Messages.getString("Characters_entry_separator")); //$NON-NLS-1$
-
- ZipEntry archiveEntry;
- if (eclipseInstallPlugin.isJar()) {
- // Obtain an input stream for the jar resource
- archiveEntry = eclipseArchive.getEntry(pluginRelativePath);
- InputStream archiveInputStream = eclipseArchive.getInputStream(archiveEntry);
- JarInputStream entryInputStream = new JarInputStream(archiveInputStream);
-
- // Find the about.html entry within the jar resource
- JarEntry jarResourceEntry = entryInputStream.getNextJarEntry();
- boolean resourceFound = false;
- while(jarResourceEntry != null && !resourceFound) {
- String resourceEntryName = jarResourceEntry.getName();
- if (resourceEntryName.equalsIgnoreCase(resource.getName())) {
- resourceFound = true;
- } else {
- jarResourceEntry = entryInputStream.getNextJarEntry();
- }
- }
-
- // Add the file to the jar
- out.putNextEntry(new JarEntry(jarResourceEntry.getName()));
- writeToOutputStream(out, entryInputStream);
- archiveInputStream.close();
- entryInputStream.close();
- } else {
- // Obtain the about.html entry directly from the eclipse archive
- archiveEntry = eclipseArchive.getEntry(pluginRelativePath + SLASH + resource.getName());
- out.putNextEntry(new ZipEntry(resource.getName()));
- InputStream archiveInputStream = eclipseArchive.getInputStream(archiveEntry);
-
- // Add the file to the jar
- writeToOutputStream(out, archiveInputStream);
- archiveInputStream.close();
- }
-
- out.closeEntry();
-
- return true;
- }
-
- private void writeToOutputStream(OutputStream out, InputStream in) throws Exception {
- byte[] buf = new byte[1024];
+ // Determine the entry name of the JAR plug-in
+ InputStream jarPluginInputStream;
+ String jarPluginRelativePath = eclipseInstallPlugin.getPluginLocation()
+ .getAbsolutePath()
+ .replace(eclipseArchiveLocation.getAbsolutePath(), "");
+ jarPluginRelativePath = jarPluginRelativePath.substring(1);
+ jarPluginRelativePath = jarPluginRelativePath.replace(File.separator,
+ Messages.getString("Characters_entry_separator")); //$NON-NLS-1$
+
+ // Extract the JAR plug-in entry form the eclipse archive
+ ZipEntry jarPluginEntry = eclipseArchive
+ .getEntry(jarPluginRelativePath);
+ jarPluginInputStream = eclipseArchive.getInputStream(jarPluginEntry);
+
+ JarInputStream inputStream = new JarInputStream(jarPluginInputStream);
+
+ // Iterate through the plug-ins resources and store data on the
+ // properties files
+ JarEntry entry;
+ while ((entry = inputStream.getNextJarEntry()) != null) {
+ String entryName = entry.getName();
+ if (entryName.endsWith(Messages.getString("Extensions_properties"))) { //$NON-NLS-1$
+ Properties properties = new Properties();
+ properties.load(inputStream);
+ propertiesMap.put(entry.getName(), new HashSet<Object>(
+ properties.keySet()));
+ }
+ }
+ inputStream.close();
+ jarPluginInputStream.close();
+
+ return propertiesMap;
+ }
+
+ public InputStream getResourceAsStream(ResourceProxy resource)
+ throws ZipException, IOException, FileNotFoundException, Exception {
+
+ String resourcePath = Messages
+ .getString("Paths_eclipse_directory_name")
+ + SLASH
+ + (eclipseInstallPlugin.isFeature() ? "features" : "plugins")
+ + SLASH
+ + eclipseInstallPlugin.getName()
+ + Messages.getString("Characters_underscore")
+ + eclipseInstallPlugin.getVersion()
+ + SLASH
+ + resource.getCanonicalPath(); //$NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$ $NON-NLS-4$
+
+ ZipEntry resourceFile = eclipseArchive.getEntry(resourcePath);
+ if (resourceFile == null) {
+ return null;
+ }
+ return eclipseArchive.getInputStream(resourceFile);
+ }
+
+ public boolean writeAboutHtmlFile(File resource, JarOutputStream out)
+ throws Exception {
+ String pluginRelativePath = eclipseInstallPlugin.getPluginLocation()
+ .getAbsolutePath()
+ .replace(eclipseArchiveLocation.getAbsolutePath(), "");
+ pluginRelativePath = pluginRelativePath.substring(1);
+ pluginRelativePath = pluginRelativePath.replace(File.separator,
+ Messages.getString("Characters_entry_separator")); //$NON-NLS-1$
+
+ ZipEntry archiveEntry;
+ if (eclipseInstallPlugin.isJar()) {
+ // Obtain an input stream for the jar resource
+ archiveEntry = eclipseArchive.getEntry(pluginRelativePath);
+ InputStream archiveInputStream = eclipseArchive
+ .getInputStream(archiveEntry);
+ JarInputStream entryInputStream = new JarInputStream(
+ archiveInputStream);
+
+ // Find the about.html entry within the jar resource
+ JarEntry jarResourceEntry = entryInputStream.getNextJarEntry();
+ boolean resourceFound = false;
+ while (jarResourceEntry != null && !resourceFound) {
+ String resourceEntryName = jarResourceEntry.getName();
+ if (resourceEntryName.equalsIgnoreCase(resource.getName())) {
+ resourceFound = true;
+ } else {
+ jarResourceEntry = entryInputStream.getNextJarEntry();
+ }
+ }
+
+ // Add the file to the jar
+ out.putNextEntry(new JarEntry(jarResourceEntry.getName()));
+ writeToOutputStream(out, entryInputStream);
+ archiveInputStream.close();
+ entryInputStream.close();
+ } else {
+ // Obtain the about.html entry directly from the eclipse archive
+ archiveEntry = eclipseArchive.getEntry(pluginRelativePath + SLASH
+ + resource.getName());
+ out.putNextEntry(new ZipEntry(resource.getName()));
+ InputStream archiveInputStream = eclipseArchive
+ .getInputStream(archiveEntry);
+
+ // Add the file to the jar
+ writeToOutputStream(out, archiveInputStream);
+ archiveInputStream.close();
+ }
+
+ out.closeEntry();
+
+ return true;
+ }
+
+ private void writeToOutputStream(OutputStream out, InputStream in)
+ throws Exception {
+ byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
- }
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/FragmentEclipseInstallMediator.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/FragmentEclipseInstallMediator.java
index dc97553..fb06be1 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/FragmentEclipseInstallMediator.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/FragmentEclipseInstallMediator.java
@@ -31,98 +31,108 @@
import org.eclipse.babel.build.core.PluginProxy;
import org.eclipse.babel.build.core.ResourceProxy;
-
public class FragmentEclipseInstallMediator implements
- FragmentEclipseTargetMediator {
-
- private PluginProxy eclipseInstallPlugin;
+ FragmentEclipseTargetMediator {
- public FragmentEclipseInstallMediator(PluginProxy eclipseInstallPlugin) {
- this.eclipseInstallPlugin = eclipseInstallPlugin;
- }
+ private PluginProxy eclipseInstallPlugin;
- public Map<String, Set<Object>> extractEclipseTargetProperties() throws ZipException,
- IOException, FileNotFoundException {
-
- Map<String, Set<Object>> propertiesMap = new HashMap<String, Set<Object>>();
- InputStream jarPluginInputStream = new FileInputStream(eclipseInstallPlugin.getPluginLocation());
-
- ZipInputStream inputStream = new ZipInputStream(jarPluginInputStream);
-
- ZipEntry entry;
- while (( entry = inputStream.getNextEntry() ) != null) {
- String entryName = entry.getName();
- if (entryName.endsWith(Messages.getString("Extensions_properties"))) { //$NON-NLS-1$
- Properties properties = new Properties();
- properties.load(inputStream);
- propertiesMap.put(entry.getName(), new HashSet<Object>(properties.keySet()));
- }
- }
-
- return propertiesMap;
- }
+ public FragmentEclipseInstallMediator(PluginProxy eclipseInstallPlugin) {
+ this.eclipseInstallPlugin = eclipseInstallPlugin;
+ }
- public InputStream getResourceAsStream(ResourceProxy resource) throws ZipException, IOException,
- FileNotFoundException {
-
- InputStream stream;
- // If it's a resource that was in a jar resource file
- if (!resource.getFileResource().exists()) {
-
- // Determine the resource's entry name within the jar
- String entryPath = resource.getCanonicalPath();
- if (entryPath.contains(JAR_RESOURCE_SUFFIX + SLASH)) {
- String target = entryPath.substring(0, entryPath.indexOf
- (JAR_RESOURCE_SUFFIX + SLASH) + JAR_RESOURCE_SUFFIX.length());
- entryPath = entryPath.replace(target + SLASH, ""); //$NON-NLS-1$
- }
-
- // Determine the location of the jar resource file
- int jarResourceEndIndex = resource.getFileResource().getAbsolutePath().indexOf(JAR_EXTENSION) + JAR_EXTENSION.length();
- String jarResourcePath = resource.getFileResource().getAbsolutePath().substring(0, jarResourceEndIndex);
-
- // Return an input stream of the resource entry within the jar
- JarFile jarFile = new JarFile(new File(jarResourcePath));
- JarEntry resourceEntry = jarFile.getJarEntry(entryPath);
- stream = jarFile.getInputStream(resourceEntry);
- } else {
- stream = new FileInputStream(resource.getFileResource());
- }
- return stream;
- }
+ public Map<String, Set<Object>> extractEclipseTargetProperties()
+ throws ZipException, IOException, FileNotFoundException {
- public boolean writeAboutHtmlFile(File resource, JarOutputStream out) throws Exception {
- try {
- ZipEntry newEntry;
- InputStream inputStream;
-
- if (eclipseInstallPlugin.isJar()) {
- JarFile pluginJar = new JarFile(this.eclipseInstallPlugin.getPluginLocation());
- newEntry = pluginJar.getJarEntry(ABOUT_FILE);
- out.putNextEntry(newEntry);
- inputStream = pluginJar.getInputStream(newEntry);
- } else {
- newEntry = new ZipEntry(resource.getName());
- out.putNextEntry(newEntry);
- inputStream = new FileInputStream(resource);
- }
-
- writeToOutputStream(out, inputStream);
-
- out.closeEntry();
-
- return true;
- }
- catch(IOException e) { System.out.println(e.getMessage()); return false;}
- }
-
- private void writeToOutputStream(JarOutputStream out, InputStream in) throws Exception {
- byte[] buf = new byte[1024];
+ Map<String, Set<Object>> propertiesMap = new HashMap<String, Set<Object>>();
+ InputStream jarPluginInputStream = new FileInputStream(
+ eclipseInstallPlugin.getPluginLocation());
+
+ ZipInputStream inputStream = new ZipInputStream(jarPluginInputStream);
+
+ ZipEntry entry;
+ while ((entry = inputStream.getNextEntry()) != null) {
+ String entryName = entry.getName();
+ if (entryName.endsWith(Messages.getString("Extensions_properties"))) { //$NON-NLS-1$
+ Properties properties = new Properties();
+ properties.load(inputStream);
+ propertiesMap.put(entry.getName(), new HashSet<Object>(
+ properties.keySet()));
+ }
+ }
+
+ return propertiesMap;
+ }
+
+ public InputStream getResourceAsStream(ResourceProxy resource)
+ throws ZipException, IOException, FileNotFoundException {
+
+ InputStream stream;
+ // If it's a resource that was in a jar resource file
+ if (!resource.getFileResource().exists()) {
+
+ // Determine the resource's entry name within the jar
+ String entryPath = resource.getCanonicalPath();
+ if (entryPath.contains(JAR_RESOURCE_SUFFIX + SLASH)) {
+ String target = entryPath.substring(0,
+ entryPath.indexOf(JAR_RESOURCE_SUFFIX + SLASH)
+ + JAR_RESOURCE_SUFFIX.length());
+ entryPath = entryPath.replace(target + SLASH, ""); //$NON-NLS-1$
+ }
+
+ // Determine the location of the jar resource file
+ int jarResourceEndIndex = resource.getFileResource()
+ .getAbsolutePath().indexOf(JAR_EXTENSION)
+ + JAR_EXTENSION.length();
+ String jarResourcePath = resource.getFileResource()
+ .getAbsolutePath().substring(0, jarResourceEndIndex);
+
+ // Return an input stream of the resource entry within the jar
+ JarFile jarFile = new JarFile(new File(jarResourcePath));
+ JarEntry resourceEntry = jarFile.getJarEntry(entryPath);
+ stream = jarFile.getInputStream(resourceEntry);
+ } else {
+ stream = new FileInputStream(resource.getFileResource());
+ }
+ return stream;
+ }
+
+ public boolean writeAboutHtmlFile(File resource, JarOutputStream out)
+ throws Exception {
+ try {
+ ZipEntry newEntry;
+ InputStream inputStream;
+
+ if (eclipseInstallPlugin.isJar()) {
+ JarFile pluginJar = new JarFile(
+ this.eclipseInstallPlugin.getPluginLocation());
+ newEntry = pluginJar.getJarEntry(ABOUT_FILE);
+ out.putNextEntry(newEntry);
+ inputStream = pluginJar.getInputStream(newEntry);
+ } else {
+ newEntry = new ZipEntry(resource.getName());
+ out.putNextEntry(newEntry);
+ inputStream = new FileInputStream(resource);
+ }
+
+ writeToOutputStream(out, inputStream);
+
+ out.closeEntry();
+
+ return true;
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ return false;
+ }
+ }
+
+ private void writeToOutputStream(JarOutputStream out, InputStream in)
+ throws Exception {
+ byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
- }
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/FragmentEclipseTargetMediator.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/FragmentEclipseTargetMediator.java
index 54b3e4c..a3772bd 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/FragmentEclipseTargetMediator.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/eclipsetarget/FragmentEclipseTargetMediator.java
@@ -22,19 +22,21 @@
import org.eclipse.babel.build.core.Messages;
import org.eclipse.babel.build.core.ResourceProxy;
-
public interface FragmentEclipseTargetMediator {
-
- public final String SLASH = Messages.getString("Characters_entry_separator"); //$NON-NLS-1$
- public final String JAR_RESOURCE_SUFFIX = Messages.getString("Suffixes_jar_resource_folder"); //$NON-NLS-1$
- public final String JAR_EXTENSION = Messages.getString("Extensions_jar"); //$NON-NLS-1$
- public final String ABOUT_FILE = Messages.getString("Paths_about_html"); //$NON-NLS-1$
-
- public InputStream getResourceAsStream(ResourceProxy resource) throws ZipException,
- IOException, FileNotFoundException, Exception;
-
- public Map<String, Set<Object>> extractEclipseTargetProperties()
- throws ZipException, IOException, FileNotFoundException;
- public boolean writeAboutHtmlFile(File resource, JarOutputStream out) throws Exception;
+ public final String SLASH = Messages
+ .getString("Characters_entry_separator"); //$NON-NLS-1$
+ public final String JAR_RESOURCE_SUFFIX = Messages
+ .getString("Suffixes_jar_resource_folder"); //$NON-NLS-1$
+ public final String JAR_EXTENSION = Messages.getString("Extensions_jar"); //$NON-NLS-1$
+ public final String ABOUT_FILE = Messages.getString("Paths_about_html"); //$NON-NLS-1$
+
+ public InputStream getResourceAsStream(ResourceProxy resource)
+ throws ZipException, IOException, FileNotFoundException, Exception;
+
+ public Map<String, Set<Object>> extractEclipseTargetProperties()
+ throws ZipException, IOException, FileNotFoundException;
+
+ public boolean writeAboutHtmlFile(File resource, JarOutputStream out)
+ throws Exception;
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/exceptions/FailedDeletionException.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/exceptions/FailedDeletionException.java
index 800ed24..c06eb63 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/exceptions/FailedDeletionException.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/exceptions/FailedDeletionException.java
@@ -11,22 +11,22 @@
package org.eclipse.babel.build.core.exceptions;
public class FailedDeletionException extends Exception {
-
- static final long serialVersionUID = 3L;
- public FailedDeletionException() {
- }
+ static final long serialVersionUID = 3L;
- public FailedDeletionException(String arg0) {
- super(arg0);
- }
+ public FailedDeletionException() {
+ }
- public FailedDeletionException(Throwable arg0) {
- super(arg0);
- }
+ public FailedDeletionException(String arg0) {
+ super(arg0);
+ }
- public FailedDeletionException(String arg0, Throwable arg1) {
- super(arg0, arg1);
- }
+ public FailedDeletionException(Throwable arg0) {
+ super(arg0);
+ }
+
+ public FailedDeletionException(String arg0, Throwable arg1) {
+ super(arg0, arg1);
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/exceptions/InvalidFilenameException.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/exceptions/InvalidFilenameException.java
index 3a7c7dd..673a417 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/exceptions/InvalidFilenameException.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/exceptions/InvalidFilenameException.java
@@ -11,22 +11,22 @@
package org.eclipse.babel.build.core.exceptions;
public class InvalidFilenameException extends Exception {
-
- static final long serialVersionUID = 3L;
-
- public InvalidFilenameException() {
- }
- public InvalidFilenameException(String arg0) {
- super(arg0);
- }
+ static final long serialVersionUID = 3L;
- public InvalidFilenameException(Throwable arg0) {
- super(arg0);
- }
+ public InvalidFilenameException() {
+ }
- public InvalidFilenameException(String arg0, Throwable arg1) {
- super(arg0, arg1);
- }
+ public InvalidFilenameException(String arg0) {
+ super(arg0);
+ }
+
+ public InvalidFilenameException(Throwable arg0) {
+ super(arg0);
+ }
+
+ public InvalidFilenameException(String arg0, Throwable arg1) {
+ super(arg0, arg1);
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/exceptions/InvalidLocationException.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/exceptions/InvalidLocationException.java
index b020030..1ae12ca 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/exceptions/InvalidLocationException.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/exceptions/InvalidLocationException.java
@@ -11,21 +11,21 @@
package org.eclipse.babel.build.core.exceptions;
public class InvalidLocationException extends Exception {
-
- static final long serialVersionUID = 3L;
- public InvalidLocationException() {
- }
-
- public InvalidLocationException(String message, Throwable cause) {
- super(message, cause);
- }
+ static final long serialVersionUID = 3L;
- public InvalidLocationException(Throwable cause) {
- super(cause);
- }
+ public InvalidLocationException() {
+ }
- public InvalidLocationException(String message) {
- super(message);
- }
+ public InvalidLocationException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public InvalidLocationException(Throwable cause) {
+ super(cause);
+ }
+
+ public InvalidLocationException(String message) {
+ super(message);
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/exceptions/MissingLocationException.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/exceptions/MissingLocationException.java
index 03239a3..0c0661f 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/exceptions/MissingLocationException.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/exceptions/MissingLocationException.java
@@ -12,21 +12,21 @@
public class MissingLocationException extends Exception {
- static final long serialVersionUID = 4L;
-
- public MissingLocationException() {
- }
+ static final long serialVersionUID = 4L;
- public MissingLocationException(String message) {
- super(message);
- }
+ public MissingLocationException() {
+ }
- public MissingLocationException(Throwable cause) {
- super(cause);
- }
+ public MissingLocationException(String message) {
+ super(message);
+ }
- public MissingLocationException(String message, Throwable cause) {
- super(message, cause);
- }
+ public MissingLocationException(Throwable cause) {
+ super(cause);
+ }
+
+ public MissingLocationException(String message, Throwable cause) {
+ super(message, cause);
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/languagepack/JarNLFragment.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/languagepack/JarNLFragment.java
index 6babd19..d1e5f4e 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/languagepack/JarNLFragment.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/languagepack/JarNLFragment.java
@@ -37,248 +37,308 @@
import org.eclipse.babel.build.core.eclipsetarget.FragmentEclipseTargetMediator;
import org.eclipse.babel.build.core.translationcatalogue.TranslationCatalogue;
-
/**
*
- * Responsible for generating an NL Fragment as a jar in the language pack.
- *
+ * Responsible for generating an NL Fragment as a jar in the language pack.
+ *
*/
public class JarNLFragment implements NLFragment {
- private File directory;
- private PluginProxy eclipseInstallPlugin;
-
- private Map<String, Set<Object>> propertiesMap = new HashMap<String, Set<Object>>();
- private FragmentEclipseTargetMediator mediator;
-
- public JarNLFragment(File directory, PluginProxy eclipseInstallPlugin, EclipseTarget eclipseTarget) throws Exception {
- this.directory = new File(directory.getAbsolutePath() + JAR_EXTENSION);
- this.eclipseInstallPlugin = eclipseInstallPlugin;
- if (eclipseTarget.isArchive()) {
- mediator = new FragmentEclipseArchiveMediator(this.eclipseInstallPlugin, eclipseTarget.getLocation());
- } else {
- mediator = new FragmentEclipseInstallMediator(this.eclipseInstallPlugin);
- }
- }
-
- public PluginCoverageInformation generateFragment(Configuration config) throws Exception {
-
- // Keeps track of whether or not the about.html file has been added to the fragment
- boolean aboutAdded = false;
-
- TranslationCatalogue translationCatalogue = config.translations();
- Set <LocaleProxy> locales = config.locales();
-
- // An empty list of locales means all of them should be parsed
- if(locales.isEmpty() && config.localeGroups().isEmpty()) {
- locales.addAll(translationCatalogue.getAllLocales());
- }
-
- Map<String, PluginProxy> translationCataloguePluginMap =
- getPluginOrFeatureForSpecifiedLocales(config, eclipseInstallPlugin);
-
- // The output stream that will be used to write to the jar nl fragment
- JarOutputStream out = null;
- FileOutputStream fileOut = null;
-
- PluginCoverageInformation coverage = new PluginCoverageInformation(eclipseInstallPlugin);
-
- try {
- /* If the eclipse target plug-in is a jar, then the set of properties for all
- of its properties files are stored in a map for quick access, in order to avoid
- having to open and close a stream for each properties file */
- if (this.eclipseInstallPlugin.isJar()) {
- this.propertiesMap = mediator.extractEclipseTargetProperties();
- }
-
- for(LocaleProxy locale: locales) {
-
- boolean pluginIsMatchedToThisLocale =
- translationCataloguePluginMap.containsKey(locale.getName());
-
- if ( pluginIsMatchedToThisLocale ) {
- PluginProxy translationArchivePlugin =
- translationCataloguePluginMap.get(locale.getName());
-
- for(ResourceProxy resource: eclipseInstallPlugin.getResources()){
- //If the resource is the about.html file
- if (resource.getRelativePath().equalsIgnoreCase(ABOUT_FILE) && !aboutAdded) {
- if(out == null) {
- fileOut = new FileOutputStream(directory);
- out = new JarOutputStream(fileOut, composeManifestContent(config.localeExtension()));
- }
- aboutAdded = mediator.writeAboutHtmlFile(resource.getFileResource(), out);
- }
- //Want to make sure that this block of code is not executed for a Manifest file
- else if (!resource.getRelativePath().equalsIgnoreCase(MANIFEST_PATH)) {
- ResourceProxy translationResource = translationCatalogue.
- getResourceTranslation(translationArchivePlugin, resource);
-
- if(translationResource != null) {
- if(out == null) {
- fileOut = new FileOutputStream(directory);
- out = new JarOutputStream(fileOut, composeManifestContent(config.localeExtension()));
- }
- writeResource(out, translationResource, locale);
-
- if (resource.getRelativePath().endsWith(Messages.getString("Extensions_properties"))) { //$NON-NLS-1$
- // If the resource is a properties file, then compute property coverage
- int value = computePropertyCoverageForLocale(resource, translationResource);
- coverage.setResourceCoverageForLocale(locale, resource, true, value);
- }
- else {
- //Mark that this resource has been matched for this locale
- coverage.setResourceCoverageForLocale(locale, resource, true);
- }
- }
- else {
- //Mark that this resource has NOT been matched for this locale
- coverage.setResourceCoverageForLocale(locale, resource, false);
- }
- }
- }
- }
- coverage.setPluginMatchingForLocale(locale, pluginIsMatchedToThisLocale);
- }
- // Complete the ZIP file
- if(out != null) {
- out.close();
- fileOut.close();
- }
- }
- catch (IOException e) {
- System.out.println(e.getMessage());
- }
-
- return coverage;
- }
-
- private int computePropertyCoverageForLocale(ResourceProxy eclipseTargetResource, ResourceProxy translationResource) throws Exception {
- // Load the set of properties within the translated resource
- InputStream transIn = new FileInputStream(translationResource.getFileResource());
- Properties transProperty = new Properties();
- transProperty.load(transIn);
-
- // Load the set of properties within the eclipse target resource
- Set<Object> properties;
- if (this.eclipseInstallPlugin.isJar()) {
- properties = new HashSet<Object>(this.propertiesMap.get(eclipseTargetResource.getCanonicalPath()));
- } else {
- InputStream in = mediator.getResourceAsStream(eclipseTargetResource);
- Properties property = new Properties();
- if (in != null) {
- property.load(in);
- in.close();
- }
- properties = new HashSet<Object>(property.keySet());
- }
- transIn.close();
-
- // Compute the amount of eclipse target resource properties covered by the translation resource
- int initialSize = properties.size();
- initialSize = initialSize < 1 ? 1 : initialSize;
- properties.removeAll(transProperty.keySet());
- return (100*(initialSize - properties.size()))/initialSize;
- }
-
- private Manifest composeManifestContent(String localeExtension) throws Exception {
- Manifest manifest = new Manifest();
-
- Attributes attributes = manifest.getMainAttributes();
-
- attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); //$NON-NLS-1$
- attributes.putValue(Messages.getString("Manifest_key_bundle_name"), eclipseInstallPlugin.getName() + " " + Messages.getString("Suffixes_fragment_name")); //$NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$
- attributes.putValue(Messages.getString("Manifest_key_bundle_version"), eclipseInstallPlugin.getVersion()); //$NON-NLS-1$
- attributes.putValue( Messages.getString("Manifest_key_bundle_symbolic_name"), eclipseInstallPlugin.getName() +
- Messages.getString("Extensions_nl") + localeExtension + Messages.getString("Manifest_value_bundle_symbolic_name_suffix") ); //$NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$
-
- if ( eclipseInstallPlugin.getName().contains(( Messages.getString("Prefixes_eclipse_plugin") )) ) { //$NON-NLS-1$
- attributes.putValue(Messages.getString("Manifest_key_bundle_vendor"), Messages.getString("Provider_name_eclipse")); //$NON-NLS-1$ $NON-NLS-2$
- } else if ( eclipseInstallPlugin.getName().contains(( Messages.getString("Prefixes_ibm_plugin") )) ) { //$NON-NLS-1$
- attributes.putValue(Messages.getString("Manifest_key_bundle_vendor"), Messages.getString("Provider_name_ibm")); //$NON-NLS-1$ $NON-NLS-2$
- } else {
- attributes.putValue(Messages.getString("Manifest_key_bundle_vendor"), Messages.getString("Provider_name_unknown")); //$NON-NLS-1$ $NON-NLS-2$
- }
-
- attributes.putValue(Messages.getString("Manifest_key_fragment_host"), eclipseInstallPlugin.getName()); //$NON-NLS-1$
+ private File directory;
+ private PluginProxy eclipseInstallPlugin;
- return manifest;
- }
+ private Map<String, Set<Object>> propertiesMap = new HashMap<String, Set<Object>>();
+ private FragmentEclipseTargetMediator mediator;
- private boolean writeResource(JarOutputStream out,
- ResourceProxy translationResource, LocaleProxy locale) {
- try {
- byte[] buf = new byte[1024];
- FileInputStream in = new FileInputStream(new File(translationResource.getFileResource().getAbsolutePath()));
-
- // The path of the resource entry in the language pack
- String temp = determineTranslatedResourceName(translationResource, locale);
- temp = temp.replace(File.separator, Messages.getString("Characters_entry_separator")); //$NON-NLS-1$
-
- // Add ZIP entry to output stream.
- out.putNextEntry(new JarEntry(temp));
+ public JarNLFragment(File directory, PluginProxy eclipseInstallPlugin,
+ EclipseTarget eclipseTarget) throws Exception {
+ this.directory = new File(directory.getAbsolutePath() + JAR_EXTENSION);
+ this.eclipseInstallPlugin = eclipseInstallPlugin;
+ if (eclipseTarget.isArchive()) {
+ mediator = new FragmentEclipseArchiveMediator(
+ this.eclipseInstallPlugin, eclipseTarget.getLocation());
+ } else {
+ mediator = new FragmentEclipseInstallMediator(
+ this.eclipseInstallPlugin);
+ }
+ }
- // Transfer bytes from the translation archive file to the new language pack ZIP file
- int len;
- while ((len = in.read(buf)) > 0) {
- out.write(buf, 0, len);
- }
+ public PluginCoverageInformation generateFragment(Configuration config)
+ throws Exception {
- // Complete the entry
- out.closeEntry();
- in.close();
- return true;
- } catch (IOException e) {
- System.out.println(e.getMessage());
- return false;
- }
- }
+ // Keeps track of whether or not the about.html file has been added to
+ // the fragment
+ boolean aboutAdded = false;
- public String determineTranslatedResourceName(ResourceProxy resource, LocaleProxy locale) {
- String resourceName = resource.getRelativePath();
-
- /* If the resource was held in a jar resource within the plug-in, then the place-holder
- directory representing the jar resource (usually called pluginName_jar) must be removed
- from the path */
- if (resourceName.contains(JAR_RESOURCE_SUFFIX + File.separator)) {
- String target = resourceName.substring(0, resourceName.indexOf
- (JAR_RESOURCE_SUFFIX + File.separator) + JAR_RESOURCE_SUFFIX.length());
- resourceName = resourceName.replace(target + File.separator, ""); //$NON-NLS-1$
- }
-
- String resourceExtension = resourceName.substring(
- resourceName.lastIndexOf(Messages.getString("Characters_period"))); //$NON-NLS-1$
- return resourceName.substring(0, resourceName.lastIndexOf(Messages.getString("Characters_period")))
- + Messages.getString("Characters_underscore") + locale.getName() + resourceExtension; //$NON-NLS-1$ $NON-NLS-2$
- }
+ TranslationCatalogue translationCatalogue = config.translations();
+ Set<LocaleProxy> locales = config.locales();
- private Map<String, PluginProxy> getPluginOrFeatureForSpecifiedLocales(Configuration config, PluginProxy plugin) {
- if (plugin.isFeature()) {
- return config.translations().getFeatureForSpecifiedLocales(plugin);
- }
- return config.translations().getPluginForSpecifiedLocales(plugin);
- }
- /*
- private String incrementRelease(String oldVersion) {
- if (oldVersion.matches(VERSION_FORMAT_WITH_QUALIFIER)) {
- oldVersion = oldVersion.substring(0, oldVersion.lastIndexOf(PERIOD));
- }
+ // An empty list of locales means all of them should be parsed
+ if (locales.isEmpty() && config.localeGroups().isEmpty()) {
+ locales.addAll(translationCatalogue.getAllLocales());
+ }
- String newVersion = LEFT_SQUARE_BRACKET + oldVersion + ',';
- String oldMinor = oldVersion.substring(oldVersion.indexOf(PERIOD) + 1, oldVersion.lastIndexOf(PERIOD));
- String oldMicro = oldVersion.substring(oldVersion.lastIndexOf(PERIOD) + 1);
+ Map<String, PluginProxy> translationCataloguePluginMap = getPluginOrFeatureForSpecifiedLocales(
+ config, eclipseInstallPlugin);
- if (oldMinor.compareTo(MAX_MINOR) == 0) {
- String major = Integer.toString(Integer.parseInt(oldVersion.substring(0, oldVersion.indexOf(PERIOD))) + 1);
- newVersion += major + PERIOD + MIN_MINOR + PERIOD + oldMicro + RIGHT_PARENTHESIS;
- } else {
- String major = oldVersion.substring(0, oldVersion.indexOf(PERIOD));
- String newMinor = Integer.toString(Integer.parseInt(oldMinor) + 1);
- newVersion += major + PERIOD + newMinor + PERIOD + oldMicro + RIGHT_PARENTHESIS;
- }
+ // The output stream that will be used to write to the jar nl fragment
+ JarOutputStream out = null;
+ FileOutputStream fileOut = null;
- return newVersion;
- }
- */
+ PluginCoverageInformation coverage = new PluginCoverageInformation(
+ eclipseInstallPlugin);
+
+ try {
+ /*
+ * If the eclipse target plug-in is a jar, then the set of
+ * properties for all of its properties files are stored in a map
+ * for quick access, in order to avoid having to open and close a
+ * stream for each properties file
+ */
+ if (this.eclipseInstallPlugin.isJar()) {
+ this.propertiesMap = mediator.extractEclipseTargetProperties();
+ }
+
+ for (LocaleProxy locale : locales) {
+
+ boolean pluginIsMatchedToThisLocale = translationCataloguePluginMap
+ .containsKey(locale.getName());
+
+ if (pluginIsMatchedToThisLocale) {
+ PluginProxy translationArchivePlugin = translationCataloguePluginMap
+ .get(locale.getName());
+
+ for (ResourceProxy resource : eclipseInstallPlugin
+ .getResources()) {
+ // If the resource is the about.html file
+ if (resource.getRelativePath().equalsIgnoreCase(
+ ABOUT_FILE)
+ && !aboutAdded) {
+ if (out == null) {
+ fileOut = new FileOutputStream(directory);
+ out = new JarOutputStream(fileOut,
+ composeManifestContent(config
+ .localeExtension()));
+ }
+ aboutAdded = mediator.writeAboutHtmlFile(
+ resource.getFileResource(), out);
+ }
+ // Want to make sure that this block of code is not
+ // executed for a Manifest file
+ else if (!resource.getRelativePath().equalsIgnoreCase(
+ MANIFEST_PATH)) {
+ ResourceProxy translationResource = translationCatalogue
+ .getResourceTranslation(
+ translationArchivePlugin, resource);
+
+ if (translationResource != null) {
+ if (out == null) {
+ fileOut = new FileOutputStream(directory);
+ out = new JarOutputStream(fileOut,
+ composeManifestContent(config
+ .localeExtension()));
+ }
+ writeResource(out, translationResource, locale);
+
+ if (resource
+ .getRelativePath()
+ .endsWith(
+ Messages.getString("Extensions_properties"))) { //$NON-NLS-1$
+ // If the resource is a properties file,
+ // then compute property coverage
+ int value = computePropertyCoverageForLocale(
+ resource, translationResource);
+ coverage.setResourceCoverageForLocale(
+ locale, resource, true, value);
+ } else {
+ // Mark that this resource has been matched
+ // for this locale
+ coverage.setResourceCoverageForLocale(
+ locale, resource, true);
+ }
+ } else {
+ // Mark that this resource has NOT been matched
+ // for this locale
+ coverage.setResourceCoverageForLocale(locale,
+ resource, false);
+ }
+ }
+ }
+ }
+ coverage.setPluginMatchingForLocale(locale,
+ pluginIsMatchedToThisLocale);
+ }
+ // Complete the ZIP file
+ if (out != null) {
+ out.close();
+ fileOut.close();
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+
+ return coverage;
+ }
+
+ private int computePropertyCoverageForLocale(
+ ResourceProxy eclipseTargetResource,
+ ResourceProxy translationResource) throws Exception {
+ // Load the set of properties within the translated resource
+ InputStream transIn = new FileInputStream(
+ translationResource.getFileResource());
+ Properties transProperty = new Properties();
+ transProperty.load(transIn);
+
+ // Load the set of properties within the eclipse target resource
+ Set<Object> properties;
+ if (this.eclipseInstallPlugin.isJar()) {
+ properties = new HashSet<Object>(
+ this.propertiesMap.get(eclipseTargetResource
+ .getCanonicalPath()));
+ } else {
+ InputStream in = mediator
+ .getResourceAsStream(eclipseTargetResource);
+ Properties property = new Properties();
+ if (in != null) {
+ property.load(in);
+ in.close();
+ }
+ properties = new HashSet<Object>(property.keySet());
+ }
+ transIn.close();
+
+ // Compute the amount of eclipse target resource properties covered by
+ // the translation resource
+ int initialSize = properties.size();
+ initialSize = initialSize < 1 ? 1 : initialSize;
+ properties.removeAll(transProperty.keySet());
+ return (100 * (initialSize - properties.size())) / initialSize;
+ }
+
+ private Manifest composeManifestContent(String localeExtension)
+ throws Exception {
+ Manifest manifest = new Manifest();
+
+ Attributes attributes = manifest.getMainAttributes();
+
+ attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); //$NON-NLS-1$
+ attributes
+ .putValue(
+ Messages.getString("Manifest_key_bundle_name"), eclipseInstallPlugin.getName() + " " + Messages.getString("Suffixes_fragment_name")); //$NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$
+ attributes
+ .putValue(
+ Messages.getString("Manifest_key_bundle_version"), eclipseInstallPlugin.getVersion()); //$NON-NLS-1$
+ attributes
+ .putValue(
+ Messages.getString("Manifest_key_bundle_symbolic_name"),
+ eclipseInstallPlugin.getName()
+ + Messages.getString("Extensions_nl") + localeExtension + Messages.getString("Manifest_value_bundle_symbolic_name_suffix")); //$NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$
+
+ if (eclipseInstallPlugin.getName().contains(
+ (Messages.getString("Prefixes_eclipse_plugin")))) { //$NON-NLS-1$
+ attributes
+ .putValue(
+ Messages.getString("Manifest_key_bundle_vendor"), Messages.getString("Provider_name_eclipse")); //$NON-NLS-1$ $NON-NLS-2$
+ } else if (eclipseInstallPlugin.getName().contains(
+ (Messages.getString("Prefixes_ibm_plugin")))) { //$NON-NLS-1$
+ attributes
+ .putValue(
+ Messages.getString("Manifest_key_bundle_vendor"), Messages.getString("Provider_name_ibm")); //$NON-NLS-1$ $NON-NLS-2$
+ } else {
+ attributes
+ .putValue(
+ Messages.getString("Manifest_key_bundle_vendor"), Messages.getString("Provider_name_unknown")); //$NON-NLS-1$ $NON-NLS-2$
+ }
+
+ attributes
+ .putValue(
+ Messages.getString("Manifest_key_fragment_host"), eclipseInstallPlugin.getName()); //$NON-NLS-1$
+
+ return manifest;
+ }
+
+ private boolean writeResource(JarOutputStream out,
+ ResourceProxy translationResource, LocaleProxy locale) {
+ try {
+ byte[] buf = new byte[1024];
+ FileInputStream in = new FileInputStream(new File(
+ translationResource.getFileResource().getAbsolutePath()));
+
+ // The path of the resource entry in the language pack
+ String temp = determineTranslatedResourceName(translationResource,
+ locale);
+ temp = temp.replace(File.separator,
+ Messages.getString("Characters_entry_separator")); //$NON-NLS-1$
+
+ // Add ZIP entry to output stream.
+ out.putNextEntry(new JarEntry(temp));
+
+ // Transfer bytes from the translation archive file to the new
+ // language pack ZIP file
+ int len;
+ while ((len = in.read(buf)) > 0) {
+ out.write(buf, 0, len);
+ }
+
+ // Complete the entry
+ out.closeEntry();
+ in.close();
+ return true;
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ return false;
+ }
+ }
+
+ public String determineTranslatedResourceName(ResourceProxy resource,
+ LocaleProxy locale) {
+ String resourceName = resource.getRelativePath();
+
+ /*
+ * If the resource was held in a jar resource within the plug-in, then
+ * the place-holder directory representing the jar resource (usually
+ * called pluginName_jar) must be removed from the path
+ */
+ if (resourceName.contains(JAR_RESOURCE_SUFFIX + File.separator)) {
+ String target = resourceName.substring(0,
+ resourceName.indexOf(JAR_RESOURCE_SUFFIX + File.separator)
+ + JAR_RESOURCE_SUFFIX.length());
+ resourceName = resourceName.replace(target + File.separator, ""); //$NON-NLS-1$
+ }
+
+ String resourceExtension = resourceName.substring(resourceName
+ .lastIndexOf(Messages.getString("Characters_period"))); //$NON-NLS-1$
+ return resourceName.substring(0, resourceName.lastIndexOf(Messages
+ .getString("Characters_period")))
+ + Messages.getString("Characters_underscore") + locale.getName() + resourceExtension; //$NON-NLS-1$ $NON-NLS-2$
+ }
+
+ private Map<String, PluginProxy> getPluginOrFeatureForSpecifiedLocales(
+ Configuration config, PluginProxy plugin) {
+ if (plugin.isFeature()) {
+ return config.translations().getFeatureForSpecifiedLocales(plugin);
+ }
+ return config.translations().getPluginForSpecifiedLocales(plugin);
+ }
+ /*
+ * private String incrementRelease(String oldVersion) { if
+ * (oldVersion.matches(VERSION_FORMAT_WITH_QUALIFIER)) { oldVersion =
+ * oldVersion.substring(0, oldVersion.lastIndexOf(PERIOD)); }
+ *
+ * String newVersion = LEFT_SQUARE_BRACKET + oldVersion + ','; String
+ * oldMinor = oldVersion.substring(oldVersion.indexOf(PERIOD) + 1,
+ * oldVersion.lastIndexOf(PERIOD)); String oldMicro =
+ * oldVersion.substring(oldVersion.lastIndexOf(PERIOD) + 1);
+ *
+ * if (oldMinor.compareTo(MAX_MINOR) == 0) { String major =
+ * Integer.toString(Integer.parseInt(oldVersion.substring(0,
+ * oldVersion.indexOf(PERIOD))) + 1); newVersion += major + PERIOD +
+ * MIN_MINOR + PERIOD + oldMicro + RIGHT_PARENTHESIS; } else { String major
+ * = oldVersion.substring(0, oldVersion.indexOf(PERIOD)); String newMinor =
+ * Integer.toString(Integer.parseInt(oldMinor) + 1); newVersion += major +
+ * PERIOD + newMinor + PERIOD + oldMicro + RIGHT_PARENTHESIS; }
+ *
+ * return newVersion; }
+ */
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/languagepack/LanguagePack.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/languagepack/LanguagePack.java
index 5abf902..ef67a93 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/languagepack/LanguagePack.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/languagepack/LanguagePack.java
@@ -21,118 +21,142 @@
import org.eclipse.babel.build.core.exceptions.InvalidFilenameException;
public class LanguagePack {
-
- private Configuration config;
- private File absoluteWorkDirectory;
-
- public LanguagePack(Configuration config) {
- this.config = config;
- }
-
- /** Generates a language pack on disk and returns a report with coverage information. */
- public LanguagePackCoverageReport generate() throws InvalidFilenameException, FailedDeletionException, Exception {
- NLFragment fragment;
- File parentFragmentDirectory;
- EclipseTarget eclipseInstall = config.eclipseInstall();
- LanguagePackCoverageReport coverage;
-
- this.absoluteWorkDirectory = this.config.workingDirectory().getAbsoluteFile();
- setupLanguagePackLocation();
-
- coverage = new LanguagePackCoverageReport(config.translations().getAllLocales());
-
- //For each plugin in the eclipse archive
- for(PluginProxy plugin: eclipseInstall.getPlugins().values()) {
-
- String versionSuffix = "";
- if (!plugin.getVersion().equalsIgnoreCase("")) {
- versionSuffix = Messages.getString("Characters_underscore") + plugin.getVersion();
- }
-
- //Determine the file path in the language pack directory for this plug-in
- parentFragmentDirectory = new File(this.absoluteWorkDirectory.getAbsoluteFile()
- + File.separator + Messages.getString("Paths_plugins_directory") + plugin.getName()
- + Messages.getString("Extensions_nl") + config.localeExtension() + versionSuffix); //$NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$
-
- config.notifyProgress(plugin.getName());
- // At present, all NL fragments are jarred
- fragment = new JarNLFragment(parentFragmentDirectory, plugin, eclipseInstall);
+ private Configuration config;
+ private File absoluteWorkDirectory;
- coverage.addPluginCoverageToReport( fragment.generateFragment(this.config) );
- }
-
- //For each feature in the eclipse archive
- for(PluginProxy feature: eclipseInstall.getFeatures().values()) {
-
- String versionSuffix = "";
- if (!feature.getVersion().equalsIgnoreCase("")) {
- versionSuffix = Messages.getString("Characters_underscore") + feature.getVersion();
- }
-
- //Determine the file path in the language pack directory for this feature
- parentFragmentDirectory = new File(this.absoluteWorkDirectory.getAbsoluteFile()
- + File.separator + Messages.getString("Paths_features_directory") + feature.getName()
- + Messages.getString("Extensions_nl") + config.localeExtension() + versionSuffix); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- config.notifyProgress(feature.getName());
-
- //TODO: Determine if feature fragments should be jarred or not
- //Instantiate the new fragment with its directory, and generate it
- if(!feature.isJar()) {
- fragment = new NonJarNLFragment(parentFragmentDirectory, feature);
- }
- else {
- fragment = new JarNLFragment(parentFragmentDirectory, feature, eclipseInstall);
- }
- coverage.addPluginCoverageToReport( fragment.generateFragment(this.config) );
- }
-
- return coverage;
- }
-
- private void setupLanguagePackLocation() throws InvalidFilenameException, FailedDeletionException {
-
- if (this.absoluteWorkDirectory.exists())
- {
- try {
- File eclipseFolder = new File(this.absoluteWorkDirectory, Messages.getString("Paths_eclipse_directory_name")); //$NON-NLS-1$
- if (eclipseFolder.exists()) {
- //Find and remove eclipse folder in working directory folder (if exists)
- for (File file: eclipseFolder.listFiles()) {
- deleteDirectory(file);
- }
- }
- } catch (Exception e) {
- throw new FailedDeletionException();
- }
-
- } else {
- this.absoluteWorkDirectory.mkdirs();
- }
- generateBaseFolders();
- }
-
- private void generateBaseFolders() {
- File newDirectory = new File(this.absoluteWorkDirectory + File.separator + Messages.getString("Paths_plugins_directory")); //$NON-NLS-1$
- newDirectory.mkdirs();
-
- newDirectory = new File(this.absoluteWorkDirectory + File.separator + Messages.getString("Paths_features_directory")); //$NON-NLS-1$
- newDirectory.mkdirs();
- }
-
- private boolean deleteDirectory(File path) {
- if( path.exists() ) {
- File[] files = path.listFiles();
- for(int i=0; i<files.length; i++) {
- if(files[i].isDirectory()) {
- deleteDirectory(files[i]);
- }
- else {
- files[i].delete();
- }
- }
- }
- return( path.delete() );
+ public LanguagePack(Configuration config) {
+ this.config = config;
+ }
+
+ /**
+ * Generates a language pack on disk and returns a report with coverage
+ * information.
+ */
+ public LanguagePackCoverageReport generate()
+ throws InvalidFilenameException, FailedDeletionException, Exception {
+ NLFragment fragment;
+ File parentFragmentDirectory;
+ EclipseTarget eclipseInstall = config.eclipseInstall();
+ LanguagePackCoverageReport coverage;
+
+ this.absoluteWorkDirectory = this.config.workingDirectory()
+ .getAbsoluteFile();
+ setupLanguagePackLocation();
+
+ coverage = new LanguagePackCoverageReport(config.translations()
+ .getAllLocales());
+
+ // For each plugin in the eclipse archive
+ for (PluginProxy plugin : eclipseInstall.getPlugins().values()) {
+
+ String versionSuffix = "";
+ if (!plugin.getVersion().equalsIgnoreCase("")) {
+ versionSuffix = Messages.getString("Characters_underscore")
+ + plugin.getVersion();
+ }
+
+ // Determine the file path in the language pack directory for this
+ // plug-in
+ parentFragmentDirectory = new File(
+ this.absoluteWorkDirectory.getAbsoluteFile()
+ + File.separator
+ + Messages.getString("Paths_plugins_directory")
+ + plugin.getName()
+ + Messages.getString("Extensions_nl") + config.localeExtension() + versionSuffix); //$NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$
+
+ config.notifyProgress(plugin.getName());
+
+ // At present, all NL fragments are jarred
+ fragment = new JarNLFragment(parentFragmentDirectory, plugin,
+ eclipseInstall);
+
+ coverage.addPluginCoverageToReport(fragment
+ .generateFragment(this.config));
+ }
+
+ // For each feature in the eclipse archive
+ for (PluginProxy feature : eclipseInstall.getFeatures().values()) {
+
+ String versionSuffix = "";
+ if (!feature.getVersion().equalsIgnoreCase("")) {
+ versionSuffix = Messages.getString("Characters_underscore")
+ + feature.getVersion();
+ }
+
+ // Determine the file path in the language pack directory for this
+ // feature
+ parentFragmentDirectory = new File(
+ this.absoluteWorkDirectory.getAbsoluteFile()
+ + File.separator
+ + Messages.getString("Paths_features_directory")
+ + feature.getName()
+ + Messages.getString("Extensions_nl") + config.localeExtension() + versionSuffix); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ config.notifyProgress(feature.getName());
+
+ // TODO: Determine if feature fragments should be jarred or not
+ // Instantiate the new fragment with its directory, and generate it
+ if (!feature.isJar()) {
+ fragment = new NonJarNLFragment(parentFragmentDirectory,
+ feature);
+ } else {
+ fragment = new JarNLFragment(parentFragmentDirectory, feature,
+ eclipseInstall);
+ }
+ coverage.addPluginCoverageToReport(fragment
+ .generateFragment(this.config));
+ }
+
+ return coverage;
+ }
+
+ private void setupLanguagePackLocation() throws InvalidFilenameException,
+ FailedDeletionException {
+
+ if (this.absoluteWorkDirectory.exists()) {
+ try {
+ File eclipseFolder = new File(this.absoluteWorkDirectory,
+ Messages.getString("Paths_eclipse_directory_name")); //$NON-NLS-1$
+ if (eclipseFolder.exists()) {
+ // Find and remove eclipse folder in working directory
+ // folder (if exists)
+ for (File file : eclipseFolder.listFiles()) {
+ deleteDirectory(file);
+ }
+ }
+ } catch (Exception e) {
+ throw new FailedDeletionException();
+ }
+
+ } else {
+ this.absoluteWorkDirectory.mkdirs();
+ }
+ generateBaseFolders();
+ }
+
+ private void generateBaseFolders() {
+ File newDirectory = new File(this.absoluteWorkDirectory
+ + File.separator
+ + Messages.getString("Paths_plugins_directory")); //$NON-NLS-1$
+ newDirectory.mkdirs();
+
+ newDirectory = new File(this.absoluteWorkDirectory + File.separator
+ + Messages.getString("Paths_features_directory")); //$NON-NLS-1$
+ newDirectory.mkdirs();
+ }
+
+ private boolean deleteDirectory(File path) {
+ if (path.exists()) {
+ File[] files = path.listFiles();
+ for (int i = 0; i < files.length; i++) {
+ if (files[i].isDirectory()) {
+ deleteDirectory(files[i]);
+ } else {
+ files[i].delete();
+ }
+ }
+ }
+ return (path.delete());
}
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/languagepack/NLFragment.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/languagepack/NLFragment.java
index a595b9e..7ff01db 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/languagepack/NLFragment.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/languagepack/NLFragment.java
@@ -18,32 +18,44 @@
import org.eclipse.babel.build.core.ResourceProxy;
import org.eclipse.babel.build.core.coverage.PluginCoverageInformation;
-
-
public interface NLFragment {
-
- public final String META_INF_DIR_NAME = Messages.getString("Paths_meta_inf_directory"); //$NON-NLS-1$
- public final String MANIFEST_FILE_NAME = Messages.getString("Filename_manifest"); //$NON-NLS-1$
- public final String MANIFEST_PATH = META_INF_DIR_NAME + File.separator + MANIFEST_FILE_NAME;
- public final String MANIFEST_ASSIGN = Messages.getString("Characters_manifest_assign") + " "; //$NON-NLS-1$ $NON-NLS-2$
- public final String SLASH = Messages.getString("Characters_entry_separator"); //$NON-NLS-1$
- public final String JAR_RESOURCE_SUFFIX = Messages.getString("Suffixes_jar_resource_folder"); //$NON-NLS-1$
- public final String JAR_EXTENSION = Messages.getString("Extensions_jar"); //$NON-NLS-1$
- public final String ABOUT_FILE = Messages.getString("Paths_about_html"); //$NON-NLS-1$
-
- /*
- public final String PERIOD = "."; //$NON-NLS-1$
- public final String MIN_MINOR = "0"; //$NON-NLS-1$
- public final String MAX_MINOR = "9"; //$NON-NLS-1$
- public final String LEFT_SQUARE_BRACKET = "["; //$NON-NLS-1$
- public final String RIGHT_PARENTHESIS = ")"; //$NON-NLS-1$
- public final String DEFAULT_VERSION = "1.0.0"; //$NON-NLS-1$
- public final String VERSION_FORMAT_WITH_QUALIFIER = "\\d+\\.\\d+\\.\\d+\\..+"; //$NON-NLS-1$
- */
-
- /** Generates an NLFragment for a specific plug-in, and returns coverage information about that plug-in. */
- public PluginCoverageInformation generateFragment(Configuration config) throws Exception;
-
- /** Given a resource and locale, determines name of the resource generated in the language pack. */
- public String determineTranslatedResourceName(ResourceProxy resource, LocaleProxy locale);
+
+ public final String META_INF_DIR_NAME = Messages
+ .getString("Paths_meta_inf_directory"); //$NON-NLS-1$
+ public final String MANIFEST_FILE_NAME = Messages
+ .getString("Filename_manifest"); //$NON-NLS-1$
+ public final String MANIFEST_PATH = META_INF_DIR_NAME + File.separator
+ + MANIFEST_FILE_NAME;
+ public final String MANIFEST_ASSIGN = Messages
+ .getString("Characters_manifest_assign") + " "; //$NON-NLS-1$ $NON-NLS-2$
+ public final String SLASH = Messages
+ .getString("Characters_entry_separator"); //$NON-NLS-1$
+ public final String JAR_RESOURCE_SUFFIX = Messages
+ .getString("Suffixes_jar_resource_folder"); //$NON-NLS-1$
+ public final String JAR_EXTENSION = Messages.getString("Extensions_jar"); //$NON-NLS-1$
+ public final String ABOUT_FILE = Messages.getString("Paths_about_html"); //$NON-NLS-1$
+
+ /*
+ * public final String PERIOD = "."; //$NON-NLS-1$ public final String
+ * MIN_MINOR = "0"; //$NON-NLS-1$ public final String MAX_MINOR = "9";
+ * //$NON-NLS-1$ public final String LEFT_SQUARE_BRACKET = "[";
+ * //$NON-NLS-1$ public final String RIGHT_PARENTHESIS = ")"; //$NON-NLS-1$
+ * public final String DEFAULT_VERSION = "1.0.0"; //$NON-NLS-1$ public final
+ * String VERSION_FORMAT_WITH_QUALIFIER = "\\d+\\.\\d+\\.\\d+\\..+";
+ * //$NON-NLS-1$
+ */
+
+ /**
+ * Generates an NLFragment for a specific plug-in, and returns coverage
+ * information about that plug-in.
+ */
+ public PluginCoverageInformation generateFragment(Configuration config)
+ throws Exception;
+
+ /**
+ * Given a resource and locale, determines name of the resource generated in
+ * the language pack.
+ */
+ public String determineTranslatedResourceName(ResourceProxy resource,
+ LocaleProxy locale);
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/languagepack/NonJarNLFragment.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/languagepack/NonJarNLFragment.java
index 9a506e4..3d36176 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/languagepack/NonJarNLFragment.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/languagepack/NonJarNLFragment.java
@@ -36,244 +36,311 @@
import org.eclipse.babel.build.core.coverage.PluginCoverageInformation;
import org.eclipse.babel.build.core.translationcatalogue.TranslationCatalogue;
-
/**
*
- * Responsible for generating an NL Fragment as a directory in the language pack.
- * May be removed in the near future if it is confirmed that all nl fragments should be jars.
- *
+ * Responsible for generating an NL Fragment as a directory in the language
+ * pack. May be removed in the near future if it is confirmed that all nl
+ * fragments should be jars.
+ *
*/
public class NonJarNLFragment implements NLFragment {
- private File directory;
- private final String BUNDLE_CLASSPATH = Messages.getString("Filename_bundle_classpath"); //$NON-NLS-1$
- private JarOutputStream bundleClasspathStream = null;
- private PluginProxy eclipseInstallPlugin;
-
- public NonJarNLFragment(File directory, PluginProxy eclipseInstallPlugin ) {
- this.directory = directory;
- this.eclipseInstallPlugin = eclipseInstallPlugin;
- }
+ private File directory;
+ private final String BUNDLE_CLASSPATH = Messages
+ .getString("Filename_bundle_classpath"); //$NON-NLS-1$
+ private JarOutputStream bundleClasspathStream = null;
+ private PluginProxy eclipseInstallPlugin;
- public PluginCoverageInformation generateFragment(Configuration config) throws Exception {
-
- directory.mkdir();
-
- TranslationCatalogue translationCatalogue = config.translations();
- Set <LocaleProxy> locales = config.locales();
-
- //An empty list of locales means all of them should be parsed
- if(locales.isEmpty() && config.localeGroups().isEmpty()) {
- locales.addAll(translationCatalogue.getAllLocales());
- }
-
- Map<String, PluginProxy> translationCataloguePluginMap =
- getPluginOrFeatureForSpecifiedLocales(config, eclipseInstallPlugin);
-
- boolean pluginIsMatchedToAnyLocale = false;
-
- PluginCoverageInformation coverage = new PluginCoverageInformation(eclipseInstallPlugin);
-
- try {
- for(LocaleProxy locale: locales) {
- //Start by inspecting the plug-ins
- boolean pluginIsMatchedToThisLocale =
- translationCataloguePluginMap.containsKey(locale.getName());
-
- if ( pluginIsMatchedToThisLocale ) {
- PluginProxy translationCataloguePlugin =
- translationCataloguePluginMap.get(locale.getName());
- pluginIsMatchedToAnyLocale = true;
+ public NonJarNLFragment(File directory, PluginProxy eclipseInstallPlugin) {
+ this.directory = directory;
+ this.eclipseInstallPlugin = eclipseInstallPlugin;
+ }
- //For all the resources of the plug-in from the eclipse archive
- for(ResourceProxy resource: eclipseInstallPlugin.getResources()){
- //If the resource is the Manifest file
- if(resource.getRelativePath().equalsIgnoreCase(MANIFEST_PATH)) {
- FileOutputStream fileOut = new FileOutputStream(new File (directory, MANIFEST_PATH));
- Manifest manifest = composeManifestContent(config.localeExtension());
- manifest.write(fileOut);
- }
- else {
- //Retrieve the translation resource
- ResourceProxy translationResource = translationCatalogue.
- getResourceTranslation(translationCataloguePlugin, resource);
-
- /*
- * Write the resource... if the object is not null, that means
- * that a corresponding resource was found in the TranslationArchive
- */
- if(translationResource != null) {
- writeResource(eclipseInstallPlugin, translationResource, locale);
-
- //TODO: Look for percentage of coverage for property files only
- if (resource.getRelativePath().endsWith(Messages.getString("Extensions_properties"))) { //$NON-NLS-1$
+ public PluginCoverageInformation generateFragment(Configuration config)
+ throws Exception {
- int value = computePropertyCoverageForLocale(config, resource, translationResource);
- coverage.setResourceCoverageForLocale(locale, resource, true, value);
- }
- else {
- //Mark that this resource has been matched for this locale
- coverage.setResourceCoverageForLocale(locale, resource, true);
- }
- }
- else {
- //Mark that this resource has NOT been matched for this locale
- coverage.setResourceCoverageForLocale(locale, resource, false);
- }
- }
- }
- }
- coverage.setPluginMatchingForLocale(locale, pluginIsMatchedToThisLocale);
-
- }
+ directory.mkdir();
- if(!pluginIsMatchedToAnyLocale) {
- directory.delete();
- }
-
- if (bundleClasspathStream != null) {
- bundleClasspathStream.close();
- }
- } catch (IOException e) {
- System.out.println(e.getMessage());
- e.printStackTrace();
- }
-
- return coverage;
- }
-
- private int computePropertyCoverageForLocale(Configuration config, ResourceProxy eclipseTargetResource, ResourceProxy translationResource) throws Exception {
- InputStream in = getResourceAsStream(config, eclipseTargetResource);
- Properties property = new Properties();
- property.load(in);
-
- InputStream transIn = new FileInputStream(translationResource.getFileResource());
- Properties transProperty = new Properties();
- transProperty.load(transIn);
+ TranslationCatalogue translationCatalogue = config.translations();
+ Set<LocaleProxy> locales = config.locales();
- Set<Object> properties = new HashSet<Object>(property.keySet());
- int initialSize = properties.size();
- initialSize = initialSize < 1 ? 1 : initialSize;
- properties.removeAll(transProperty.keySet());
- return (100*(initialSize - properties.size()))/initialSize;
- }
+ // An empty list of locales means all of them should be parsed
+ if (locales.isEmpty() && config.localeGroups().isEmpty()) {
+ locales.addAll(translationCatalogue.getAllLocales());
+ }
- private InputStream getResourceAsStream(Configuration config,
- ResourceProxy resource) throws ZipException, IOException,
- FileNotFoundException {
-
- if (config.eclipseInstall().isArchive()) {
- ZipFile eclipseArchive = new ZipFile(config.eclipseInstall().getLocation());
+ Map<String, PluginProxy> translationCataloguePluginMap = getPluginOrFeatureForSpecifiedLocales(
+ config, eclipseInstallPlugin);
- String pluginPath = Messages.getString("Paths_eclipse_directory_name") + SLASH
- + (eclipseInstallPlugin.isFeature() ? "features" : "plugins")
- + SLASH + eclipseInstallPlugin.getName()+ Messages.getString("Characters_underscore")
- + eclipseInstallPlugin.getVersion() + SLASH + resource.getCanonicalPath(); //$NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$ $NON-NLS-4$
-
- ZipEntry resourceFile = eclipseArchive.getEntry(pluginPath);
- return eclipseArchive.getInputStream(resourceFile);
- }
-
- return new FileInputStream(resource.getFileResource());
- }
- /**
- private void addBundleClasspathInManifest(Manifest manifest) throws Exception {
- Manifest manifest = new Manifest();
-
- Attributes attributes = manifest.getMainAttributes();
-
- attributes.putValue(Messages.getString("Manifest_entry_bundle_classpath"), Messages.getString("Filename_bundle_classpath")); //$NON-NLS-1$ $NON-NLS-2$
- }*/
+ boolean pluginIsMatchedToAnyLocale = false;
- private Manifest composeManifestContent(String localeExtension) throws Exception {
- Manifest manifest = new Manifest();
-
- Attributes attributes = manifest.getMainAttributes();
-
- attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); //$NON-NLS-1$
- attributes.putValue(Messages.getString("Manifest_key_bundle_name"), eclipseInstallPlugin.getName() + " " + Messages.getString("Suffixes_fragment_name")); //$NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$
- attributes.putValue(Messages.getString("Manifest_key_bundle_version"), eclipseInstallPlugin.getVersion()); //$NON-NLS-1$
- attributes.putValue( Messages.getString("Manifest_key_bundle_symbolic_name"), eclipseInstallPlugin.getName() +
- Messages.getString("Extensions_nl") + localeExtension + Messages.getString("Manifest_value_bundle_symbolic_name_suffix") ); //$NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$
-
- if ( eclipseInstallPlugin.getName().contains(( Messages.getString("Prefixes_eclipse_plugin") )) ) { //$NON-NLS-1$
- attributes.putValue(Messages.getString("Manifest_key_bundle_vendor"), Messages.getString("Provider_name_eclipse")); //$NON-NLS-1$ $NON-NLS-2$
- } else if ( eclipseInstallPlugin.getName().contains(( Messages.getString("Prefixes_ibm_plugin") )) ) { //$NON-NLS-1$
- attributes.putValue(Messages.getString("Manifest_key_bundle_vendor"), Messages.getString("Provider_name_ibm")); //$NON-NLS-1$ $NON-NLS-2$
- } else {
- attributes.putValue(Messages.getString("Manifest_key_bundle_vendor"), Messages.getString("Provider_name_unknown")); //$NON-NLS-1$ $NON-NLS-2$
- }
-
- attributes.putValue(Messages.getString("Manifest_key_fragment_host"), eclipseInstallPlugin.getName()); //$NON-NLS-1$
+ PluginCoverageInformation coverage = new PluginCoverageInformation(
+ eclipseInstallPlugin);
- return manifest;
- }
+ try {
+ for (LocaleProxy locale : locales) {
+ // Start by inspecting the plug-ins
+ boolean pluginIsMatchedToThisLocale = translationCataloguePluginMap
+ .containsKey(locale.getName());
- private boolean writeResource(PluginProxy eclipseInstallPlugin, ResourceProxy translation, LocaleProxy locale) throws Exception {
- String translationResourceName = determineTranslatedResourceName(translation, locale);
- String pluginNameInDirFormat = eclipseInstallPlugin.getName().replace(Messages.getString("Characters_period"), File.separator); //$NON-NLS-1$
-
- if(translation.getRelativePath().contains(pluginNameInDirFormat)) {
- return writeResourceToBundleClasspath(translation, locale);
- }
- else if (translationResourceName.contains(File.separator)) {
- String resourcePath = translationResourceName.substring(0, translationResourceName.lastIndexOf(File.separatorChar));
- File resourcePathDirectory = new File(directory.getPath() + File.separatorChar + resourcePath);
- resourcePathDirectory.mkdirs();
- }
-
- File fragmentResource = new File(directory.getPath() + File.separatorChar + translationResourceName);
- File translatedResource = new File(translation.getFileResource().getAbsolutePath());
-
- FileChannel inputChannel = new FileInputStream(translatedResource).getChannel();
- FileChannel outputChannel = new FileOutputStream(fragmentResource).getChannel();
- inputChannel.transferTo(0, inputChannel.size(), outputChannel);
- inputChannel.close();
- outputChannel.close();
- return true;
- }
-
- private boolean writeResourceToBundleClasspath(ResourceProxy translation, LocaleProxy locale) throws Exception {
- if (bundleClasspathStream == null) {
- bundleClasspathStream = new JarOutputStream(
- new FileOutputStream(directory.getPath() + File.separator + BUNDLE_CLASSPATH));
- }
-
- byte[] buf = new byte[1024];
-
- FileInputStream in = new FileInputStream(new File(translation.getFileResource().getAbsolutePath()));
-
- // The path of the resource entry in the language pack
- String temp = determineTranslatedResourceName(translation, locale);
-
+ if (pluginIsMatchedToThisLocale) {
+ PluginProxy translationCataloguePlugin = translationCataloguePluginMap
+ .get(locale.getName());
+ pluginIsMatchedToAnyLocale = true;
+
+ // For all the resources of the plug-in from the eclipse
+ // archive
+ for (ResourceProxy resource : eclipseInstallPlugin
+ .getResources()) {
+ // If the resource is the Manifest file
+ if (resource.getRelativePath().equalsIgnoreCase(
+ MANIFEST_PATH)) {
+ FileOutputStream fileOut = new FileOutputStream(
+ new File(directory, MANIFEST_PATH));
+ Manifest manifest = composeManifestContent(config
+ .localeExtension());
+ manifest.write(fileOut);
+ } else {
+ // Retrieve the translation resource
+ ResourceProxy translationResource = translationCatalogue
+ .getResourceTranslation(
+ translationCataloguePlugin,
+ resource);
+
+ /*
+ * Write the resource... if the object is not null,
+ * that means that a corresponding resource was
+ * found in the TranslationArchive
+ */
+ if (translationResource != null) {
+ writeResource(eclipseInstallPlugin,
+ translationResource, locale);
+
+ // TODO: Look for percentage of coverage for
+ // property files only
+ if (resource
+ .getRelativePath()
+ .endsWith(
+ Messages.getString("Extensions_properties"))) { //$NON-NLS-1$
+
+ int value = computePropertyCoverageForLocale(
+ config, resource,
+ translationResource);
+ coverage.setResourceCoverageForLocale(
+ locale, resource, true, value);
+ } else {
+ // Mark that this resource has been matched
+ // for this locale
+ coverage.setResourceCoverageForLocale(
+ locale, resource, true);
+ }
+ } else {
+ // Mark that this resource has NOT been matched
+ // for this locale
+ coverage.setResourceCoverageForLocale(locale,
+ resource, false);
+ }
+ }
+ }
+ }
+ coverage.setPluginMatchingForLocale(locale,
+ pluginIsMatchedToThisLocale);
+
+ }
+
+ if (!pluginIsMatchedToAnyLocale) {
+ directory.delete();
+ }
+
+ if (bundleClasspathStream != null) {
+ bundleClasspathStream.close();
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ e.printStackTrace();
+ }
+
+ return coverage;
+ }
+
+ private int computePropertyCoverageForLocale(Configuration config,
+ ResourceProxy eclipseTargetResource,
+ ResourceProxy translationResource) throws Exception {
+ InputStream in = getResourceAsStream(config, eclipseTargetResource);
+ Properties property = new Properties();
+ property.load(in);
+
+ InputStream transIn = new FileInputStream(
+ translationResource.getFileResource());
+ Properties transProperty = new Properties();
+ transProperty.load(transIn);
+
+ Set<Object> properties = new HashSet<Object>(property.keySet());
+ int initialSize = properties.size();
+ initialSize = initialSize < 1 ? 1 : initialSize;
+ properties.removeAll(transProperty.keySet());
+ return (100 * (initialSize - properties.size())) / initialSize;
+ }
+
+ private InputStream getResourceAsStream(Configuration config,
+ ResourceProxy resource) throws ZipException, IOException,
+ FileNotFoundException {
+
+ if (config.eclipseInstall().isArchive()) {
+ ZipFile eclipseArchive = new ZipFile(config.eclipseInstall()
+ .getLocation());
+
+ String pluginPath = Messages
+ .getString("Paths_eclipse_directory_name")
+ + SLASH
+ + (eclipseInstallPlugin.isFeature() ? "features"
+ : "plugins")
+ + SLASH
+ + eclipseInstallPlugin.getName()
+ + Messages.getString("Characters_underscore")
+ + eclipseInstallPlugin.getVersion()
+ + SLASH
+ + resource.getCanonicalPath(); //$NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$ $NON-NLS-4$
+
+ ZipEntry resourceFile = eclipseArchive.getEntry(pluginPath);
+ return eclipseArchive.getInputStream(resourceFile);
+ }
+
+ return new FileInputStream(resource.getFileResource());
+ }
+
+ /**
+ * private void addBundleClasspathInManifest(Manifest manifest) throws
+ * Exception { Manifest manifest = new Manifest();
+ *
+ * Attributes attributes = manifest.getMainAttributes();
+ *
+ * attributes.putValue(Messages.getString("Manifest_entry_bundle_classpath")
+ * , Messages.getString("Filename_bundle_classpath")); //$NON-NLS-1$
+ * $NON-NLS-2$ }
+ */
+
+ private Manifest composeManifestContent(String localeExtension)
+ throws Exception {
+ Manifest manifest = new Manifest();
+
+ Attributes attributes = manifest.getMainAttributes();
+
+ attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); //$NON-NLS-1$
+ attributes
+ .putValue(
+ Messages.getString("Manifest_key_bundle_name"), eclipseInstallPlugin.getName() + " " + Messages.getString("Suffixes_fragment_name")); //$NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$
+ attributes
+ .putValue(
+ Messages.getString("Manifest_key_bundle_version"), eclipseInstallPlugin.getVersion()); //$NON-NLS-1$
+ attributes
+ .putValue(
+ Messages.getString("Manifest_key_bundle_symbolic_name"),
+ eclipseInstallPlugin.getName()
+ + Messages.getString("Extensions_nl") + localeExtension + Messages.getString("Manifest_value_bundle_symbolic_name_suffix")); //$NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$
+
+ if (eclipseInstallPlugin.getName().contains(
+ (Messages.getString("Prefixes_eclipse_plugin")))) { //$NON-NLS-1$
+ attributes
+ .putValue(
+ Messages.getString("Manifest_key_bundle_vendor"), Messages.getString("Provider_name_eclipse")); //$NON-NLS-1$ $NON-NLS-2$
+ } else if (eclipseInstallPlugin.getName().contains(
+ (Messages.getString("Prefixes_ibm_plugin")))) { //$NON-NLS-1$
+ attributes
+ .putValue(
+ Messages.getString("Manifest_key_bundle_vendor"), Messages.getString("Provider_name_ibm")); //$NON-NLS-1$ $NON-NLS-2$
+ } else {
+ attributes
+ .putValue(
+ Messages.getString("Manifest_key_bundle_vendor"), Messages.getString("Provider_name_unknown")); //$NON-NLS-1$ $NON-NLS-2$
+ }
+
+ attributes
+ .putValue(
+ Messages.getString("Manifest_key_fragment_host"), eclipseInstallPlugin.getName()); //$NON-NLS-1$
+
+ return manifest;
+ }
+
+ private boolean writeResource(PluginProxy eclipseInstallPlugin,
+ ResourceProxy translation, LocaleProxy locale) throws Exception {
+ String translationResourceName = determineTranslatedResourceName(
+ translation, locale);
+ String pluginNameInDirFormat = eclipseInstallPlugin.getName().replace(
+ Messages.getString("Characters_period"), File.separator); //$NON-NLS-1$
+
+ if (translation.getRelativePath().contains(pluginNameInDirFormat)) {
+ return writeResourceToBundleClasspath(translation, locale);
+ } else if (translationResourceName.contains(File.separator)) {
+ String resourcePath = translationResourceName.substring(0,
+ translationResourceName.lastIndexOf(File.separatorChar));
+ File resourcePathDirectory = new File(directory.getPath()
+ + File.separatorChar + resourcePath);
+ resourcePathDirectory.mkdirs();
+ }
+
+ File fragmentResource = new File(directory.getPath()
+ + File.separatorChar + translationResourceName);
+ File translatedResource = new File(translation.getFileResource()
+ .getAbsolutePath());
+
+ FileChannel inputChannel = new FileInputStream(translatedResource)
+ .getChannel();
+ FileChannel outputChannel = new FileOutputStream(fragmentResource)
+ .getChannel();
+ inputChannel.transferTo(0, inputChannel.size(), outputChannel);
+ inputChannel.close();
+ outputChannel.close();
+ return true;
+ }
+
+ private boolean writeResourceToBundleClasspath(ResourceProxy translation,
+ LocaleProxy locale) throws Exception {
+ if (bundleClasspathStream == null) {
+ bundleClasspathStream = new JarOutputStream(new FileOutputStream(
+ directory.getPath() + File.separator + BUNDLE_CLASSPATH));
+ }
+
+ byte[] buf = new byte[1024];
+
+ FileInputStream in = new FileInputStream(new File(translation
+ .getFileResource().getAbsolutePath()));
+
+ // The path of the resource entry in the language pack
+ String temp = determineTranslatedResourceName(translation, locale);
+
// Add ZIP entry to output stream.
- bundleClasspathStream.putNextEntry(new ZipEntry(temp));
+ bundleClasspathStream.putNextEntry(new ZipEntry(temp));
- // Transfer bytes from the translation archive file to the new language pack ZIP file
+ // Transfer bytes from the translation archive file to the new language
+ // pack ZIP file
int len;
while ((len = in.read(buf)) > 0) {
- bundleClasspathStream.write(buf, 0, len);
+ bundleClasspathStream.write(buf, 0, len);
}
// Complete the entry
bundleClasspathStream.closeEntry();
in.close();
return true;
- }
+ }
- public String determineTranslatedResourceName(ResourceProxy resource,
- LocaleProxy locale) {
- String resourceName = resource.getRelativePath();
- String resourceExtension = resourceName.substring(resourceName.lastIndexOf(Messages.getString("Characters_period"))); //$NON-NLS-1$
- return resourceName.substring(0, resourceName.lastIndexOf(Messages.getString("Characters_period"))) //$NON-NLS-1$
- + Messages.getString("Characters_underscore") + locale.getName() + resourceExtension; //$NON-NLS-1$
- }
+ public String determineTranslatedResourceName(ResourceProxy resource,
+ LocaleProxy locale) {
+ String resourceName = resource.getRelativePath();
+ String resourceExtension = resourceName.substring(resourceName
+ .lastIndexOf(Messages.getString("Characters_period"))); //$NON-NLS-1$
+ return resourceName.substring(0, resourceName.lastIndexOf(Messages
+ .getString("Characters_period"))) //$NON-NLS-1$
+ + Messages.getString("Characters_underscore") + locale.getName() + resourceExtension; //$NON-NLS-1$
+ }
- private Map<String, PluginProxy> getPluginOrFeatureForSpecifiedLocales(Configuration config, PluginProxy plugin) {
- if (plugin.isFeature()) {
- return config.translations().getFeatureForSpecifiedLocales(plugin);
- }
- return config.translations().getPluginForSpecifiedLocales(plugin);
- }
+ private Map<String, PluginProxy> getPluginOrFeatureForSpecifiedLocales(
+ Configuration config, PluginProxy plugin) {
+ if (plugin.isFeature()) {
+ return config.translations().getFeatureForSpecifiedLocales(plugin);
+ }
+ return config.translations().getPluginForSpecifiedLocales(plugin);
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/reports/CoverageReport.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/reports/CoverageReport.java
index 08d2ffe..41f1a0d 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/reports/CoverageReport.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/reports/CoverageReport.java
@@ -17,29 +17,32 @@
import org.eclipse.babel.build.core.coverage.PluginCoverageInformation;
import org.eclipse.babel.build.core.coverage.ResourceCoverageInformation;
-
public interface CoverageReport {
- public static class utils{
- public static final int calculateCoverageScore(LocaleProxy locale, ResourceProxy resource, PluginCoverageInformation info){
- ResourceCoverageInformation resourceInfo = info.getResourceCoverage().get(resource.getRelativePath());
-
- if(resourceInfo == null){
- return 0;
- }
-
- Boolean matchingForLocale = resourceInfo.getMatchingForLocale(locale);
- if(matchingForLocale == null){
- return 0;
- }
-
- Integer coverage = resourceInfo.getMatchedPercentageForLocale(locale);
- if(coverage != null){
- return coverage;
- }
-
- return matchingForLocale ? 100 : 0;
- }
- }
-
- public void render(OutputStream stream) throws Exception;
+ public static class utils {
+ public static final int calculateCoverageScore(LocaleProxy locale,
+ ResourceProxy resource, PluginCoverageInformation info) {
+ ResourceCoverageInformation resourceInfo = info
+ .getResourceCoverage().get(resource.getRelativePath());
+
+ if (resourceInfo == null) {
+ return 0;
+ }
+
+ Boolean matchingForLocale = resourceInfo
+ .getMatchingForLocale(locale);
+ if (matchingForLocale == null) {
+ return 0;
+ }
+
+ Integer coverage = resourceInfo
+ .getMatchedPercentageForLocale(locale);
+ if (coverage != null) {
+ return coverage;
+ }
+
+ return matchingForLocale ? 100 : 0;
+ }
+ }
+
+ public void render(OutputStream stream) throws Exception;
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/reports/HtmlCoverageReport.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/reports/HtmlCoverageReport.java
index 26a1f29..943a3b7 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/reports/HtmlCoverageReport.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/reports/HtmlCoverageReport.java
@@ -13,7 +13,6 @@
import static org.eclipse.babel.build.core.xml.Builder.*;
import static org.eclipse.babel.build.core.xml.Html.*;
-
import java.io.OutputStream;
import java.util.Collection;
import java.util.Collections;
@@ -32,276 +31,274 @@
import org.eclipse.babel.build.core.xml.XmlWriter;
import org.eclipse.babel.build.core.xml.Builder.ToNode;
+public class HtmlCoverageReport implements CoverageReport {
+ public class RollUpForLocale implements ToNode<LocaleProxy> {
-public class HtmlCoverageReport implements CoverageReport{
- public class RollUpForLocale implements ToNode<LocaleProxy> {
+ private final PluginCoverageInformation info;
+ private final PluginProxy plugin;
- private final PluginCoverageInformation info;
- private final PluginProxy plugin;
+ public RollUpForLocale(PluginCoverageInformation info) {
+ this.info = info;
+ this.plugin = info.getEclipseArchivePlugin();
+ }
- public RollUpForLocale(PluginCoverageInformation info) {
- this.info = info;
- this.plugin = info.getEclipseArchivePlugin();
- }
+ public Element toNode(LocaleProxy t) {
+ int min = Integer.MAX_VALUE;
- public Element toNode(LocaleProxy t) {
- int min = Integer.MAX_VALUE;
-
- for(ResourceProxy resource : plugin.getResources()){
- boolean matched = resourceMatched(info, resource);
- boolean included = config.includeResource(plugin, resource);
- int score = CoverageReport.utils.calculateCoverageScore(t, resource, info);
-
- if(matched && included && score < min){
- min = score;
- }
- }
-
- return td("" + min).attribute("class", "" + completeness(min));
- }
+ for (ResourceProxy resource : plugin.getResources()) {
+ boolean matched = resourceMatched(info, resource);
+ boolean included = config.includeResource(plugin, resource);
+ int score = CoverageReport.utils.calculateCoverageScore(t,
+ resource, info);
- }
+ if (matched && included && score < min) {
+ min = score;
+ }
+ }
- public class PluginSummaryRow implements ToNode<PluginCoverageInformation>{
- public Element toNode(PluginCoverageInformation info) {
- PluginProxy plugin = info.getEclipseArchivePlugin();
-
- if(!hasMatchedResources(info)){
- return Element.utils.EMPTY_ELEMENT;
- }
-
- return tr(
- td(a("#" + plugin.getName(), plugin.getName())).attribute("class", "first"),
- sequence(locales, new RollUpForLocale(info))
- );
- }
- }
-
- public class UnmatchedResource implements ToNode<ResourceProxy> {
- private PluginProxy plugin;
- private final PluginCoverageInformation info;
+ return td("" + min).attribute("class", "" + completeness(min));
+ }
- public UnmatchedResource(PluginCoverageInformation info){
- this.info = info;
- this.plugin = info.getEclipseArchivePlugin();
- }
+ }
- public Element toNode(ResourceProxy resource) {
- boolean matched = resourceMatched(info, resource);
- boolean included = config.includeResource(plugin, resource);
-
- if(matched || !included){
- return Element.utils.EMPTY_ELEMENT;
- }
-
- return li(resource.getRelativePath());
- }
+ public class PluginSummaryRow implements ToNode<PluginCoverageInformation> {
+ public Element toNode(PluginCoverageInformation info) {
+ PluginProxy plugin = info.getEclipseArchivePlugin();
- }
+ if (!hasMatchedResources(info)) {
+ return Element.utils.EMPTY_ELEMENT;
+ }
+ return tr(td(a("#" + plugin.getName(), plugin.getName()))
+ .attribute("class", "first"),
+ sequence(locales, new RollUpForLocale(info)));
+ }
+ }
- public class UnmatchedResourceList implements
- ToNode<PluginCoverageInformation> {
+ public class UnmatchedResource implements ToNode<ResourceProxy> {
+ private PluginProxy plugin;
+ private final PluginCoverageInformation info;
- public Element toNode(PluginCoverageInformation info) {
- PluginProxy plugin = info.getEclipseArchivePlugin();
-
- if(hasMatchedResources(info)){
- return Element.utils.EMPTY_ELEMENT;
- }
-
- return nodes(
- h2(plugin.getName()),
- ul(sequence(plugin.getResources(), new UnmatchedResource(info)))
- );
- }
+ public UnmatchedResource(PluginCoverageInformation info) {
+ this.info = info;
+ this.plugin = info.getEclipseArchivePlugin();
+ }
- }
+ public Element toNode(ResourceProxy resource) {
+ boolean matched = resourceMatched(info, resource);
+ boolean included = config.includeResource(plugin, resource);
+ if (matched || !included) {
+ return Element.utils.EMPTY_ELEMENT;
+ }
- private final class ResourceCoverageRow implements ToNode<ResourceProxy> {
- private final PluginCoverageInformation info;
- private final PluginProxy plugin;
+ return li(resource.getRelativePath());
+ }
- private ResourceCoverageRow(PluginCoverageInformation info) {
- this.info = info;
- plugin = info.getEclipseArchivePlugin();
- }
+ }
- public Element toNode(final ResourceProxy resource) {
- if(!config.includeResource(plugin, resource)){
- return Element.utils.EMPTY_ELEMENT;
- }
-
- if(!resourceMatched(info, resource)){
- return Element.utils.EMPTY_ELEMENT;
- }
-
- return tr(
- td(resource.getRelativePath()).attribute("class", "first"),
- sequence(locales, new ToNode<LocaleProxy>(){
- public Element toNode(LocaleProxy locale) {
- int score = CoverageReport.utils.calculateCoverageScore(locale, resource, info);
- return td("" + score ).attribute("class", completeness(score));
- }
- })
- );
- }
- }
+ public class UnmatchedResourceList implements
+ ToNode<PluginCoverageInformation> {
- private static String completeness(int score){
- if(score < 25){
- return "missing";
- }
-
- if(score < 80){
- return "incomplete";
- }
-
- if(score < 100){
- return "almost-complete";
- }
-
- return "complete";
- }
-
- private final class MatchedPluginCoverageTable implements ToNode<PluginCoverageInformation> {
- public Element toNode(final PluginCoverageInformation info) {
- if(!hasMatchedResources(info)){
- return Element.utils.EMPTY_ELEMENT;
- }
-
-
- PluginProxy plugin = info.getEclipseArchivePlugin();
- String name = plugin.getName();
- return nodes(
- h2(a("#" + name, name).attribute("name", name).attribute("class", "target")),
- table(
- tr(th("Resource").attribute("class", "first"), sequence(locales, new ToNode<LocaleProxy>(){
- public Element toNode(LocaleProxy t) {
- return th(t.getName());
- }
- })),
- sequence(plugin.getResources(), new ResourceCoverageRow(info))
- )
- );
- }
- }
+ public Element toNode(PluginCoverageInformation info) {
+ PluginProxy plugin = info.getEclipseArchivePlugin();
+ if (hasMatchedResources(info)) {
+ return Element.utils.EMPTY_ELEMENT;
+ }
- private static final String TITLE = "Language Pack Coverage Report";
- private final LanguagePackCoverageReport coverage;
- private final Configuration config;
- private final List<LocaleProxy> locales;
+ return nodes(
+ h2(plugin.getName()),
+ ul(sequence(plugin.getResources(), new UnmatchedResource(
+ info))));
+ }
- public HtmlCoverageReport(Configuration config, LanguagePackCoverageReport coverage){
- this.config = config;
- this.coverage = coverage;
- this.locales = sorted(config.locales(), LocaleProxy.NAME_COMPARATOR);
- }
-
-
- public boolean hasMatchedResources(PluginCoverageInformation info) {
- for(ResourceCoverageInformation coverage : info.getResourceCoverage().values()){
- boolean included = config.includeResource(info.getEclipseArchivePlugin(), coverage.getResource());
- boolean matched = resourceMatched(info, coverage.getResource());
-
- if(included && matched){
- return true;
- }
- }
-
- return false;
- }
+ }
+ private final class ResourceCoverageRow implements ToNode<ResourceProxy> {
+ private final PluginCoverageInformation info;
+ private final PluginProxy plugin;
- private boolean resourceMatched(PluginCoverageInformation info, ResourceProxy resource) {
- ResourceCoverageInformation coverage = info.getResourceCoverage().get(resource.getCanonicalPath());
-
- if(coverage == null){
- return false;
- }
- return any(coverage.getLocaleMatchMap().values());
- }
+ private ResourceCoverageRow(PluginCoverageInformation info) {
+ this.info = info;
+ plugin = info.getEclipseArchivePlugin();
+ }
+ public Element toNode(final ResourceProxy resource) {
+ if (!config.includeResource(plugin, resource)) {
+ return Element.utils.EMPTY_ELEMENT;
+ }
- private boolean any(Collection<Boolean> values) {
- for(Boolean value : values){
- if(value != null && value){
- return true;
- }
- }
-
- return false;
- }
+ if (!resourceMatched(info, resource)) {
+ return Element.utils.EMPTY_ELEMENT;
+ }
- private static final int HEADER_WIDTH = 30;
- private static final int CELL_WIDTH = 4;
-
- public Element build() {
- return html(
- head(
- title(TITLE),
- style(
- "tr, th, td, table { border: 1px solid; }\n" +
- ".missing { background-color: #FFBFBF; }\n" +
- ".incomplete { background-color: #FFE6BF; }\n" +
- ".almost-complete { background-color: #FFFFBF; }\n" +
- ".complete { background-color: #BFFFBF; }\n" +
- "a.target { color: black; }\n" +
- String.format(".first { width: %dem; }\n", HEADER_WIDTH) +
- String.format("th, td { width: %dem; }\n", CELL_WIDTH) +
- String.format("table { table-layout: fixed; width: %dem; }", HEADER_WIDTH + locales.size() * CELL_WIDTH)
- )
- ),
- body(
- h1(TITLE),
- h2("Plugin Coverage Summary Table"),
- table(
- tr(th("Plugin Name").attribute("class", "first"), sequence(locales, new ToNode<LocaleProxy>(){
- public Element toNode(LocaleProxy t) {
- return th(t.getName());
- }
- })),
- sequence(sorted(coverage.getPluginCoverageReports(), PluginCoverageInformation.NAME_COMPARATOR), new PluginSummaryRow())
- ),
-
- sequence(
- sorted(coverage.getPluginCoverageReports(), PluginCoverageInformation.NAME_COMPARATOR),
- new MatchedPluginCoverageTable()
- ),
- unmatchedResources()
- )
- );
- }
-
- private Element unmatchedResources() {
- if(!config.longReport()){
- return Element.utils.EMPTY_ELEMENT;
- }
-
- return nodes(
- h1("Unmatched Resources"),
- sequence(
- sorted(coverage.getPluginCoverageReports(), PluginCoverageInformation.NAME_COMPARATOR),
- new UnmatchedResourceList()
- )
- );
- }
+ return tr(td(resource.getRelativePath())
+ .attribute("class", "first"),
+ sequence(locales, new ToNode<LocaleProxy>() {
+ public Element toNode(LocaleProxy locale) {
+ int score = CoverageReport.utils
+ .calculateCoverageScore(locale, resource,
+ info);
+ return td("" + score).attribute("class",
+ completeness(score));
+ }
+ }));
+ }
+ }
+ private static String completeness(int score) {
+ if (score < 25) {
+ return "missing";
+ }
- private static <T> List<T> sorted(Iterable<T> ts, Comparator<T> cmp) {
- List<T> list = new LinkedList<T>();
- for(T t : ts){
- list.add(t);
- }
-
- Collections.sort(list, cmp);
- return list;
- }
+ if (score < 80) {
+ return "incomplete";
+ }
+ if (score < 100) {
+ return "almost-complete";
+ }
- public void render(OutputStream stream) throws Exception {
- build().render(new XmlWriter(stream));
- }
+ return "complete";
+ }
+
+ private final class MatchedPluginCoverageTable implements
+ ToNode<PluginCoverageInformation> {
+ public Element toNode(final PluginCoverageInformation info) {
+ if (!hasMatchedResources(info)) {
+ return Element.utils.EMPTY_ELEMENT;
+ }
+
+ PluginProxy plugin = info.getEclipseArchivePlugin();
+ String name = plugin.getName();
+ return nodes(
+ h2(a("#" + name, name).attribute("name", name).attribute(
+ "class", "target")),
+ table(tr(th("Resource").attribute("class", "first"),
+ sequence(locales, new ToNode<LocaleProxy>() {
+ public Element toNode(LocaleProxy t) {
+ return th(t.getName());
+ }
+ })),
+ sequence(plugin.getResources(),
+ new ResourceCoverageRow(info))));
+ }
+ }
+
+ private static final String TITLE = "Language Pack Coverage Report";
+ private final LanguagePackCoverageReport coverage;
+ private final Configuration config;
+ private final List<LocaleProxy> locales;
+
+ public HtmlCoverageReport(Configuration config,
+ LanguagePackCoverageReport coverage) {
+ this.config = config;
+ this.coverage = coverage;
+ this.locales = sorted(config.locales(), LocaleProxy.NAME_COMPARATOR);
+ }
+
+ public boolean hasMatchedResources(PluginCoverageInformation info) {
+ for (ResourceCoverageInformation coverage : info.getResourceCoverage()
+ .values()) {
+ boolean included = config.includeResource(
+ info.getEclipseArchivePlugin(), coverage.getResource());
+ boolean matched = resourceMatched(info, coverage.getResource());
+
+ if (included && matched) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private boolean resourceMatched(PluginCoverageInformation info,
+ ResourceProxy resource) {
+ ResourceCoverageInformation coverage = info.getResourceCoverage().get(
+ resource.getCanonicalPath());
+
+ if (coverage == null) {
+ return false;
+ }
+ return any(coverage.getLocaleMatchMap().values());
+ }
+
+ private boolean any(Collection<Boolean> values) {
+ for (Boolean value : values) {
+ if (value != null && value) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private static final int HEADER_WIDTH = 30;
+ private static final int CELL_WIDTH = 4;
+
+ public Element build() {
+ return html(
+ head(title(TITLE),
+ style("tr, th, td, table { border: 1px solid; }\n"
+ + ".missing { background-color: #FFBFBF; }\n"
+ + ".incomplete { background-color: #FFE6BF; }\n"
+ + ".almost-complete { background-color: #FFFFBF; }\n"
+ + ".complete { background-color: #BFFFBF; }\n"
+ + "a.target { color: black; }\n"
+ + String.format(".first { width: %dem; }\n",
+ HEADER_WIDTH)
+ + String.format("th, td { width: %dem; }\n",
+ CELL_WIDTH)
+ + String.format(
+ "table { table-layout: fixed; width: %dem; }",
+ HEADER_WIDTH + locales.size()
+ * CELL_WIDTH))),
+ body(h1(TITLE),
+ h2("Plugin Coverage Summary Table"),
+ table(tr(th("Plugin Name").attribute("class", "first"),
+ sequence(locales, new ToNode<LocaleProxy>() {
+ public Element toNode(LocaleProxy t) {
+ return th(t.getName());
+ }
+ })),
+ sequence(
+ sorted(coverage
+ .getPluginCoverageReports(),
+ PluginCoverageInformation.NAME_COMPARATOR),
+ new PluginSummaryRow())),
+
+ sequence(
+ sorted(coverage.getPluginCoverageReports(),
+ PluginCoverageInformation.NAME_COMPARATOR),
+ new MatchedPluginCoverageTable()),
+ unmatchedResources()));
+ }
+
+ private Element unmatchedResources() {
+ if (!config.longReport()) {
+ return Element.utils.EMPTY_ELEMENT;
+ }
+
+ return nodes(
+ h1("Unmatched Resources"),
+ sequence(
+ sorted(coverage.getPluginCoverageReports(),
+ PluginCoverageInformation.NAME_COMPARATOR),
+ new UnmatchedResourceList()));
+ }
+
+ private static <T> List<T> sorted(Iterable<T> ts, Comparator<T> cmp) {
+ List<T> list = new LinkedList<T>();
+ for (T t : ts) {
+ list.add(t);
+ }
+
+ Collections.sort(list, cmp);
+ return list;
+ }
+
+ public void render(OutputStream stream) throws Exception {
+ build().render(new XmlWriter(stream));
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/reports/TextCoverageReport.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/reports/TextCoverageReport.java
index a85a41d..e785fed 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/reports/TextCoverageReport.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/reports/TextCoverageReport.java
@@ -19,49 +19,55 @@
import org.eclipse.babel.build.core.coverage.PluginCoverageInformation;
import org.eclipse.babel.build.core.coverage.ResourceCoverageInformation;
-
public class TextCoverageReport implements CoverageReport {
- private final LanguagePackCoverageReport coverage;
+ private final LanguagePackCoverageReport coverage;
- public TextCoverageReport(LanguagePackCoverageReport coverage){
- this.coverage = coverage;
- }
+ public TextCoverageReport(LanguagePackCoverageReport coverage) {
+ this.coverage = coverage;
+ }
- public void render(OutputStream stream) throws Exception {
- BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream));
-
- writer.write("Number of total plugins: " + coverage.getPluginCoverageReports().size()); //$NON-NLS-1$
- writer.newLine();
-
- for (LocaleProxy locale: coverage.getMatchesPerLocale().keySet()) {
- writer.write("Number of matched plugins for " + locale.getName() + ": " +
- coverage.getMatchesPerLocale().get(locale)); //$NON-NLS-1$ $NON-NLS-2$
- writer.newLine();
- }
-
- for (PluginCoverageInformation pluginReport: coverage.getPluginCoverageReports()) {
- writer.newLine();
- writer.write(pluginReport.getEclipseArchivePlugin().getName());
- writer.newLine();
-
- for (LocaleProxy locale : pluginReport.getPluginMatchingPerLocale().keySet()) {
- writer.write(locale.getName() + " -> " + pluginReport.getPluginMatchingPerLocale().get(locale));
- writer.newLine();
- }
-
- for (String resourcePath : pluginReport.getResourceCoverage().keySet()) {
- ResourceCoverageInformation resourceCoverageInfo = pluginReport.getResourceCoverage().get(resourcePath);
- writer.write(resourcePath);
- writer.newLine();
-
- for (LocaleProxy locale : resourceCoverageInfo.getRecordedLocales()) {
- writer.write("Locale " + locale.getName() + ": " + resourceCoverageInfo.getMatchingForLocale(locale)); //$NON-NLS-1$ $NON-NLS-2$
- writer.newLine();
- writer.write("Locale property coverage " + locale.getName() + ": " + resourceCoverageInfo.getMatchedPercentageForLocale(locale)); //$NON-NLS-1$ $NON-NLS-2$
- writer.newLine();
- }
- }
- }
- }
+ public void render(OutputStream stream) throws Exception {
+ BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
+ stream));
+
+ writer.write("Number of total plugins: " + coverage.getPluginCoverageReports().size()); //$NON-NLS-1$
+ writer.newLine();
+
+ for (LocaleProxy locale : coverage.getMatchesPerLocale().keySet()) {
+ writer.write("Number of matched plugins for " + locale.getName()
+ + ": " + coverage.getMatchesPerLocale().get(locale)); //$NON-NLS-1$ $NON-NLS-2$
+ writer.newLine();
+ }
+
+ for (PluginCoverageInformation pluginReport : coverage
+ .getPluginCoverageReports()) {
+ writer.newLine();
+ writer.write(pluginReport.getEclipseArchivePlugin().getName());
+ writer.newLine();
+
+ for (LocaleProxy locale : pluginReport.getPluginMatchingPerLocale()
+ .keySet()) {
+ writer.write(locale.getName() + " -> "
+ + pluginReport.getPluginMatchingPerLocale().get(locale));
+ writer.newLine();
+ }
+
+ for (String resourcePath : pluginReport.getResourceCoverage()
+ .keySet()) {
+ ResourceCoverageInformation resourceCoverageInfo = pluginReport
+ .getResourceCoverage().get(resourcePath);
+ writer.write(resourcePath);
+ writer.newLine();
+
+ for (LocaleProxy locale : resourceCoverageInfo
+ .getRecordedLocales()) {
+ writer.write("Locale " + locale.getName() + ": " + resourceCoverageInfo.getMatchingForLocale(locale)); //$NON-NLS-1$ $NON-NLS-2$
+ writer.newLine();
+ writer.write("Locale property coverage " + locale.getName() + ": " + resourceCoverageInfo.getMatchedPercentageForLocale(locale)); //$NON-NLS-1$ $NON-NLS-2$
+ writer.newLine();
+ }
+ }
+ }
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/reports/XmlCoverageReport.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/reports/XmlCoverageReport.java
index 9615296..1471819 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/reports/XmlCoverageReport.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/reports/XmlCoverageReport.java
@@ -37,69 +37,73 @@
import org.eclipse.babel.build.core.xml.XmlWriter;
import org.eclipse.babel.build.core.xml.Builder.ToNode;
+public class XmlCoverageReport implements CoverageReport {
+ public class ResourceToNode implements ToNode<ResourceProxy> {
-public class XmlCoverageReport implements CoverageReport{
- public class ResourceToNode implements ToNode<ResourceProxy> {
+ private final PluginCoverageInformation info;
+ private final PluginProxy plugin;
- private final PluginCoverageInformation info;
- private final PluginProxy plugin;
+ public ResourceToNode(PluginCoverageInformation info) {
+ this.info = info;
+ plugin = info.getEclipseArchivePlugin();
+ }
- public ResourceToNode(PluginCoverageInformation info) {
- this.info = info;
- plugin = info.getEclipseArchivePlugin();
- }
+ public Element toNode(final ResourceProxy resource) {
+ if (!config.includeResource(plugin, resource)) {
+ return resource(resource.getRelativePath(), true);
+ }
- public Element toNode(final ResourceProxy resource) {
- if(!config.includeResource(plugin, resource)){
- return resource(resource.getRelativePath(), true);
- }
-
- return resource(resource.getRelativePath(),
- sequence(config.locales(), new ToNode<LocaleProxy>(){
- public Element toNode(LocaleProxy locale) {
- int score = CoverageReport.utils.calculateCoverageScore(locale, resource, info);
- return locale(locale.getName(), score);
- }
- }));
- }
- }
+ return resource(resource.getRelativePath(),
+ sequence(config.locales(), new ToNode<LocaleProxy>() {
+ public Element toNode(LocaleProxy locale) {
+ int score = CoverageReport.utils
+ .calculateCoverageScore(locale, resource,
+ info);
+ return locale(locale.getName(), score);
+ }
+ }));
+ }
+ }
- public static class LocaleToNode implements ToNode<LocaleProxy> {
- public Element toNode(LocaleProxy locale) {
- return locale(locale.getName());
- }
- }
+ public static class LocaleToNode implements ToNode<LocaleProxy> {
+ public Element toNode(LocaleProxy locale) {
+ return locale(locale.getName());
+ }
+ }
- private final Configuration config;
- private final LanguagePackCoverageReport coverage;
+ private final Configuration config;
+ private final LanguagePackCoverageReport coverage;
- public XmlCoverageReport(Configuration config, LanguagePackCoverageReport coverage){
- this.config = config;
- this.coverage = coverage;
- }
+ public XmlCoverageReport(Configuration config,
+ LanguagePackCoverageReport coverage) {
+ this.config = config;
+ this.coverage = coverage;
+ }
- public Element build() {
- return coverage(config.timestamp() == null ? new Date().toString() : config.timestamp().toString(),
- archive(config.eclipseInstall().getLocation().getAbsolutePath()),
- translations(config.translations().getRootDirectory().getAbsolutePath()),
- output(config.workingDirectory().getAbsolutePath()),
- locales(sequence(config.locales(), new LocaleToNode())),
- plugins(sequence(coverage.getPluginCoverageReports(), new PluginToNode()))
- );
- }
+ public Element build() {
+ return coverage(
+ config.timestamp() == null ? new Date().toString() : config
+ .timestamp().toString(),
+ archive(config.eclipseInstall().getLocation().getAbsolutePath()),
+ translations(config.translations().getRootDirectory()
+ .getAbsolutePath()),
+ output(config.workingDirectory().getAbsolutePath()),
+ locales(sequence(config.locales(), new LocaleToNode())),
+ plugins(sequence(coverage.getPluginCoverageReports(),
+ new PluginToNode())));
+ }
- private class PluginToNode implements ToNode<PluginCoverageInformation> {
-
- public Element toNode(PluginCoverageInformation info) {
- PluginProxy plugin = info.getEclipseArchivePlugin();
- return plugin(plugin.getName(), plugin.getVersion(),
- sequence(plugin.getResources(), new ResourceToNode(info))
- );
- }
-
- }
+ private class PluginToNode implements ToNode<PluginCoverageInformation> {
- public void render(OutputStream stream) throws Exception {
- build().render(new XmlWriter(stream));
- }
+ public Element toNode(PluginCoverageInformation info) {
+ PluginProxy plugin = info.getEclipseArchivePlugin();
+ return plugin(plugin.getName(), plugin.getVersion(),
+ sequence(plugin.getResources(), new ResourceToNode(info)));
+ }
+
+ }
+
+ public void render(OutputStream stream) throws Exception {
+ build().render(new XmlWriter(stream));
+ }
}
\ No newline at end of file
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/translationcatalogue/TranslationCatalogue.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/translationcatalogue/TranslationCatalogue.java
index cc70d58..11c43d0 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/translationcatalogue/TranslationCatalogue.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/translationcatalogue/TranslationCatalogue.java
@@ -24,83 +24,95 @@
import org.eclipse.babel.build.core.exceptions.InvalidLocationException;
import org.eclipse.babel.build.core.exceptions.MissingLocationException;
-
public class TranslationCatalogue {
-
- private File rootDirectory;
- private Set<LocaleProxy> locales = new HashSet<LocaleProxy>();
- private Set<LocaleProxy> allLocales;
-
- private TranslationCatalogueParser catalogueParser;
- public TranslationCatalogue(File root, Collection<LocaleProxy> locales)
- throws MissingLocationException, InvalidLocationException, InvalidFilenameException {
- this.rootDirectory = root.getAbsoluteFile();
-
- if (!this.rootDirectory.exists()) {
- throw new MissingLocationException();
- } else if (!this.rootDirectory.isDirectory()) {
- throw new InvalidFilenameException();
- }
-
- this.locales.addAll(locales);
- this.allLocales = new HashSet<LocaleProxy>();
-
- catalogueParser = new TranslationCatalogueSimpleParser(this.rootDirectory, this.locales);
- this.allLocales = catalogueParser.findRelevantLocalesInCatalogue();
- if (this.locales.isEmpty()) {
- this.locales = this.allLocales;
- }
- }
-
- public TranslationCatalogue(File root, Set<LocaleGroup> localeGroups)
- throws MissingLocationException, InvalidLocationException, InvalidFilenameException {
- this.rootDirectory = root.getAbsoluteFile();
-
- if (!this.rootDirectory.exists()) {
- throw new MissingLocationException();
- } else if (!this.rootDirectory.isDirectory()) {
- throw new InvalidFilenameException();
- }
-
- this.allLocales = new HashSet<LocaleProxy>();
-
- catalogueParser = new TranslationCatalogueBulkParser(this.rootDirectory, localeGroups);
- this.allLocales = catalogueParser.findRelevantLocalesInCatalogue();
- this.locales = this.allLocales;
- }
-
- /**
- * @param eclipseInstallPlugin
- * @return The different versions (one for each locale) of the same plug-in within the catalogue.
- */
- public Map<String, PluginProxy> getPluginForSpecifiedLocales (PluginProxy eclipseInstallPlugin) {
- return catalogueParser.getPluginForSpecifiedLocales(eclipseInstallPlugin);
- }
-
- /**
- * @param eclipseInstallFeature
- * @return The different versions (one for each locale) of the same feature within the catalogue.
- */
- public Map<String, PluginProxy> getFeatureForSpecifiedLocales (PluginProxy eclipseInstallFeature) {
- return catalogueParser.getFeatureForSpecifiedLocales(eclipseInstallFeature);
- }
-
- public ResourceProxy getResourceTranslation(PluginProxy translationCataloguePlugin, ResourceProxy eclipseInstallPluginResource) {
- for (ResourceProxy candidateTranslatedResource: translationCataloguePlugin.getResources()) {
- if (candidateTranslatedResource.getRelativePath().
- equalsIgnoreCase(eclipseInstallPluginResource.getRelativePath())) {
- return candidateTranslatedResource;
- }
- }
- return null;
- }
+ private File rootDirectory;
+ private Set<LocaleProxy> locales = new HashSet<LocaleProxy>();
+ private Set<LocaleProxy> allLocales;
- public Set<LocaleProxy> getAllLocales() {
- return allLocales;
- }
+ private TranslationCatalogueParser catalogueParser;
- public File getRootDirectory() {
- return rootDirectory;
- }
+ public TranslationCatalogue(File root, Collection<LocaleProxy> locales)
+ throws MissingLocationException, InvalidLocationException,
+ InvalidFilenameException {
+ this.rootDirectory = root.getAbsoluteFile();
+
+ if (!this.rootDirectory.exists()) {
+ throw new MissingLocationException();
+ } else if (!this.rootDirectory.isDirectory()) {
+ throw new InvalidFilenameException();
+ }
+
+ this.locales.addAll(locales);
+ this.allLocales = new HashSet<LocaleProxy>();
+
+ catalogueParser = new TranslationCatalogueSimpleParser(
+ this.rootDirectory, this.locales);
+ this.allLocales = catalogueParser.findRelevantLocalesInCatalogue();
+ if (this.locales.isEmpty()) {
+ this.locales = this.allLocales;
+ }
+ }
+
+ public TranslationCatalogue(File root, Set<LocaleGroup> localeGroups)
+ throws MissingLocationException, InvalidLocationException,
+ InvalidFilenameException {
+ this.rootDirectory = root.getAbsoluteFile();
+
+ if (!this.rootDirectory.exists()) {
+ throw new MissingLocationException();
+ } else if (!this.rootDirectory.isDirectory()) {
+ throw new InvalidFilenameException();
+ }
+
+ this.allLocales = new HashSet<LocaleProxy>();
+
+ catalogueParser = new TranslationCatalogueBulkParser(
+ this.rootDirectory, localeGroups);
+ this.allLocales = catalogueParser.findRelevantLocalesInCatalogue();
+ this.locales = this.allLocales;
+ }
+
+ /**
+ * @param eclipseInstallPlugin
+ * @return The different versions (one for each locale) of the same plug-in
+ * within the catalogue.
+ */
+ public Map<String, PluginProxy> getPluginForSpecifiedLocales(
+ PluginProxy eclipseInstallPlugin) {
+ return catalogueParser
+ .getPluginForSpecifiedLocales(eclipseInstallPlugin);
+ }
+
+ /**
+ * @param eclipseInstallFeature
+ * @return The different versions (one for each locale) of the same feature
+ * within the catalogue.
+ */
+ public Map<String, PluginProxy> getFeatureForSpecifiedLocales(
+ PluginProxy eclipseInstallFeature) {
+ return catalogueParser
+ .getFeatureForSpecifiedLocales(eclipseInstallFeature);
+ }
+
+ public ResourceProxy getResourceTranslation(
+ PluginProxy translationCataloguePlugin,
+ ResourceProxy eclipseInstallPluginResource) {
+ for (ResourceProxy candidateTranslatedResource : translationCataloguePlugin
+ .getResources()) {
+ if (candidateTranslatedResource.getRelativePath().equalsIgnoreCase(
+ eclipseInstallPluginResource.getRelativePath())) {
+ return candidateTranslatedResource;
+ }
+ }
+ return null;
+ }
+
+ public Set<LocaleProxy> getAllLocales() {
+ return allLocales;
+ }
+
+ public File getRootDirectory() {
+ return rootDirectory;
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/translationcatalogue/TranslationCatalogueBulkParser.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/translationcatalogue/TranslationCatalogueBulkParser.java
index bd33492..71eaf44 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/translationcatalogue/TranslationCatalogueBulkParser.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/translationcatalogue/TranslationCatalogueBulkParser.java
@@ -25,121 +25,141 @@
import org.eclipse.babel.build.core.ResourceProxy;
import org.eclipse.babel.build.core.exceptions.InvalidLocationException;
+public class TranslationCatalogueBulkParser implements
+ TranslationCatalogueParser {
-public class TranslationCatalogueBulkParser implements TranslationCatalogueParser {
+ private File rootDirectory;
+ private Set<LocaleGroup> specifiedGroups;
- private File rootDirectory;
- private Set<LocaleGroup> specifiedGroups;
-
- public TranslationCatalogueBulkParser(File rootDirectory, Set<LocaleGroup> specifiedGroups) {
- this.rootDirectory = rootDirectory;
- this.specifiedGroups = specifiedGroups;
- }
+ public TranslationCatalogueBulkParser(File rootDirectory,
+ Set<LocaleGroup> specifiedGroups) {
+ this.rootDirectory = rootDirectory;
+ this.specifiedGroups = specifiedGroups;
+ }
- /**
- *
- * @param eclipseInstallPlugin
- * @return The different versions (one for each locale) of the same plug-in within the catalogue.
- */
- public Map<String, PluginProxy> getPluginForSpecifiedLocales (PluginProxy eclipseInstallPlugin) {
- Map<String, PluginProxy> plugins = new HashMap<String, PluginProxy>();
-
- for (File subDir: rootDirectory.listFiles()) {
- if (LocaleGroup.isValidGroupName(subDir.getName()) && isIncludedGroup(subDir.getName())) {
-
- for (File localeDir: subDir.listFiles()) {
-
- String group = subDir.getName();
-
- File pluginsRoot = new File(rootDirectory.getAbsolutePath() +
- File.separatorChar + group + File.separatorChar + localeDir.getName() +
- File.separatorChar + PLUGINS_PATH);
-
- File pluginFile = new File(pluginsRoot.getAbsolutePath() + File.separator + eclipseInstallPlugin.getName());
-
- if(pluginFile.exists()) {
- List<ResourceProxy> pluginResources = extractResources(pluginFile, pluginFile.getName());
- plugins.put(localeDir.getName(), new PluginProxy(pluginFile, pluginResources, false, false));
- }
- }
- }
- }
-
- return plugins;
- }
-
- /**
- *
- * @param eclipseInstallFeature
- * @return The different versions (one for each locale) of the same feature within the catalogue.
- */
- public Map<String, PluginProxy> getFeatureForSpecifiedLocales (PluginProxy eclipseInstallFeature) {
- Map<String, PluginProxy> features = new HashMap<String, PluginProxy>();
-
- for (File subDir: rootDirectory.listFiles()) {
- if (LocaleGroup.isValidGroupName(subDir.getName()) && isIncludedGroup(subDir.getName())) {
-
- for (File localeDir: subDir.listFiles()) {
-
- String group = subDir.getName();
-
- File featuresRoot = new File(rootDirectory.getAbsolutePath() +
- File.separatorChar + group + File.separatorChar + localeDir.getName() +
- File.separatorChar + FEATURES_PATH);
-
- File featureFile = new File(featuresRoot.getAbsolutePath() + File.separator + eclipseInstallFeature.getName());
-
- if(featureFile.exists()) {
- List<ResourceProxy> featureResources = extractResources(featureFile, featureFile.getName());
- features.put(localeDir.getName(), new PluginProxy(featureFile, featureResources, false, false));
- }
- }
- }
- }
-
- return features;
- }
-
- private List<ResourceProxy> extractResources(File file, String pluginName) {
- List<ResourceProxy> resources = new LinkedList<ResourceProxy>();
- for (File subFile: file.listFiles()) {
- if (subFile.isDirectory()) {
- resources.addAll(extractResources(subFile, pluginName));
- }
- else {
- String absolutePath = subFile.getAbsolutePath();
- String relativePath = absolutePath.substring(absolutePath.indexOf(pluginName));
- relativePath = relativePath.substring(pluginName.length() + 1);
- resources.add(new ResourceProxy(subFile, relativePath));
- }
- }
- return resources;
- }
-
- private boolean isIncludedGroup(String name) {
- return this.specifiedGroups.contains(LocaleGroup.GROUP_ALL) || this.specifiedGroups.contains(LocaleGroup.get(name));
- }
-
- /**
- * Extract the list of all the relevant locales featured in the Translation Catalogue.
- * The assumption is that all folders within relevant group folders are locales.
- */
- public Set<LocaleProxy> findRelevantLocalesInCatalogue() throws InvalidLocationException {
- Set<LocaleProxy> allLocales = new HashSet<LocaleProxy>();
-
- for (File groupDir: rootDirectory.listFiles()) {
- if (LocaleGroup.isValidGroupName(groupDir.getName()) && isIncludedGroup(groupDir.getName())) {
- for (File localeDir: groupDir.listFiles()) {
- allLocales.add(new LocaleProxy(localeDir.getName()));
- }
- }
- }
-
- if (allLocales.isEmpty()) {
- throw new InvalidLocationException(
- Messages.getString("Error_invalid_translation_catalogue_bulk")); //$NON-NLS-1$
- }
-
- return allLocales;
- }
+ /**
+ *
+ * @param eclipseInstallPlugin
+ * @return The different versions (one for each locale) of the same plug-in
+ * within the catalogue.
+ */
+ public Map<String, PluginProxy> getPluginForSpecifiedLocales(
+ PluginProxy eclipseInstallPlugin) {
+ Map<String, PluginProxy> plugins = new HashMap<String, PluginProxy>();
+
+ for (File subDir : rootDirectory.listFiles()) {
+ if (LocaleGroup.isValidGroupName(subDir.getName())
+ && isIncludedGroup(subDir.getName())) {
+
+ for (File localeDir : subDir.listFiles()) {
+
+ String group = subDir.getName();
+
+ File pluginsRoot = new File(rootDirectory.getAbsolutePath()
+ + File.separatorChar + group + File.separatorChar
+ + localeDir.getName() + File.separatorChar
+ + PLUGINS_PATH);
+
+ File pluginFile = new File(pluginsRoot.getAbsolutePath()
+ + File.separator + eclipseInstallPlugin.getName());
+
+ if (pluginFile.exists()) {
+ List<ResourceProxy> pluginResources = extractResources(
+ pluginFile, pluginFile.getName());
+ plugins.put(localeDir.getName(), new PluginProxy(
+ pluginFile, pluginResources, false, false));
+ }
+ }
+ }
+ }
+
+ return plugins;
+ }
+
+ /**
+ *
+ * @param eclipseInstallFeature
+ * @return The different versions (one for each locale) of the same feature
+ * within the catalogue.
+ */
+ public Map<String, PluginProxy> getFeatureForSpecifiedLocales(
+ PluginProxy eclipseInstallFeature) {
+ Map<String, PluginProxy> features = new HashMap<String, PluginProxy>();
+
+ for (File subDir : rootDirectory.listFiles()) {
+ if (LocaleGroup.isValidGroupName(subDir.getName())
+ && isIncludedGroup(subDir.getName())) {
+
+ for (File localeDir : subDir.listFiles()) {
+
+ String group = subDir.getName();
+
+ File featuresRoot = new File(
+ rootDirectory.getAbsolutePath()
+ + File.separatorChar + group
+ + File.separatorChar + localeDir.getName()
+ + File.separatorChar + FEATURES_PATH);
+
+ File featureFile = new File(featuresRoot.getAbsolutePath()
+ + File.separator + eclipseInstallFeature.getName());
+
+ if (featureFile.exists()) {
+ List<ResourceProxy> featureResources = extractResources(
+ featureFile, featureFile.getName());
+ features.put(localeDir.getName(), new PluginProxy(
+ featureFile, featureResources, false, false));
+ }
+ }
+ }
+ }
+
+ return features;
+ }
+
+ private List<ResourceProxy> extractResources(File file, String pluginName) {
+ List<ResourceProxy> resources = new LinkedList<ResourceProxy>();
+ for (File subFile : file.listFiles()) {
+ if (subFile.isDirectory()) {
+ resources.addAll(extractResources(subFile, pluginName));
+ } else {
+ String absolutePath = subFile.getAbsolutePath();
+ String relativePath = absolutePath.substring(absolutePath
+ .indexOf(pluginName));
+ relativePath = relativePath.substring(pluginName.length() + 1);
+ resources.add(new ResourceProxy(subFile, relativePath));
+ }
+ }
+ return resources;
+ }
+
+ private boolean isIncludedGroup(String name) {
+ return this.specifiedGroups.contains(LocaleGroup.GROUP_ALL)
+ || this.specifiedGroups.contains(LocaleGroup.get(name));
+ }
+
+ /**
+ * Extract the list of all the relevant locales featured in the Translation
+ * Catalogue. The assumption is that all folders within relevant group
+ * folders are locales.
+ */
+ public Set<LocaleProxy> findRelevantLocalesInCatalogue()
+ throws InvalidLocationException {
+ Set<LocaleProxy> allLocales = new HashSet<LocaleProxy>();
+
+ for (File groupDir : rootDirectory.listFiles()) {
+ if (LocaleGroup.isValidGroupName(groupDir.getName())
+ && isIncludedGroup(groupDir.getName())) {
+ for (File localeDir : groupDir.listFiles()) {
+ allLocales.add(new LocaleProxy(localeDir.getName()));
+ }
+ }
+ }
+
+ if (allLocales.isEmpty()) {
+ throw new InvalidLocationException(
+ Messages.getString("Error_invalid_translation_catalogue_bulk")); //$NON-NLS-1$
+ }
+
+ return allLocales;
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/translationcatalogue/TranslationCatalogueParser.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/translationcatalogue/TranslationCatalogueParser.java
index e73bfe9..75f3176 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/translationcatalogue/TranslationCatalogueParser.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/translationcatalogue/TranslationCatalogueParser.java
@@ -18,25 +18,32 @@
import org.eclipse.babel.build.core.PluginProxy;
import org.eclipse.babel.build.core.exceptions.InvalidLocationException;
-
public interface TranslationCatalogueParser {
- public final static String PLUGINS_PATH = Messages.getString("Paths_plugins_directory"); //$NON-NLS-1$
- public final static String FEATURES_PATH = Messages.getString("Paths_features_directory"); //$NON-NLS-1$
-
- /**
- * @param eclipseInstallPlugin
- * @return The different versions (one for each locale) of the same plug-in within the catalogue.
- */
- public Map<String, PluginProxy> getPluginForSpecifiedLocales (PluginProxy eclipseInstallPlugin);
-
- /**
- * @param eclipseInstallFeature
- * @return The different versions (one for each locale) of the same feature within the catalogue.
- */
- public Map<String, PluginProxy> getFeatureForSpecifiedLocales (PluginProxy eclipseInstallFeature);
-
- /**
- * Extract the list of all the relevant locales featured in the Translation Catalogue.
- */
- public Set<LocaleProxy> findRelevantLocalesInCatalogue() throws InvalidLocationException;
+ public final static String PLUGINS_PATH = Messages
+ .getString("Paths_plugins_directory"); //$NON-NLS-1$
+ public final static String FEATURES_PATH = Messages
+ .getString("Paths_features_directory"); //$NON-NLS-1$
+
+ /**
+ * @param eclipseInstallPlugin
+ * @return The different versions (one for each locale) of the same plug-in
+ * within the catalogue.
+ */
+ public Map<String, PluginProxy> getPluginForSpecifiedLocales(
+ PluginProxy eclipseInstallPlugin);
+
+ /**
+ * @param eclipseInstallFeature
+ * @return The different versions (one for each locale) of the same feature
+ * within the catalogue.
+ */
+ public Map<String, PluginProxy> getFeatureForSpecifiedLocales(
+ PluginProxy eclipseInstallFeature);
+
+ /**
+ * Extract the list of all the relevant locales featured in the Translation
+ * Catalogue.
+ */
+ public Set<LocaleProxy> findRelevantLocalesInCatalogue()
+ throws InvalidLocationException;
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/translationcatalogue/TranslationCatalogueSimpleParser.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/translationcatalogue/TranslationCatalogueSimpleParser.java
index 2d1914b..1c2850e 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/translationcatalogue/TranslationCatalogueSimpleParser.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/translationcatalogue/TranslationCatalogueSimpleParser.java
@@ -24,158 +24,185 @@
import org.eclipse.babel.build.core.ResourceProxy;
import org.eclipse.babel.build.core.exceptions.InvalidLocationException;
-
public class TranslationCatalogueSimpleParser implements
- TranslationCatalogueParser {
+ TranslationCatalogueParser {
- private File rootDirectory;
- private Set<LocaleProxy> locales;
-
- public TranslationCatalogueSimpleParser(File rootDirectory, Set<LocaleProxy> locales) {
- this.locales = locales;
- this.rootDirectory = rootDirectory;
- }
+ private File rootDirectory;
+ private Set<LocaleProxy> locales;
- /**
- *
- * @param eclipseInstallPlugin
- * @return The different versions (one for each locale) of the same plug-in within the catalogue.
- */
- public Map<String, PluginProxy> getPluginForSpecifiedLocales (PluginProxy eclipseInstallPlugin) {
- Map<String, PluginProxy> plugins = new HashMap<String, PluginProxy>();
-
- for (LocaleProxy locale : this.locales) {
- PluginProxy plugin = getPluginForLocale(locale, eclipseInstallPlugin);
- if (plugin != null) {
- plugins.put(locale.getName(), plugin);
- }
- }
- return plugins;
- }
-
- /**
- *
- * @param eclipseInstallPlugin
- * @return The different versions (one for each locale) of the same feature within the catalogue.
- */
- public Map<String, PluginProxy> getFeatureForSpecifiedLocales (PluginProxy eclipseInstallFeature) {
- Map<String, PluginProxy> features = new HashMap<String, PluginProxy>();
-
- for (LocaleProxy locale : this.locales) {
- PluginProxy feature = getFeatureForLocale(locale, eclipseInstallFeature);
- if ( feature != null ) {
- features.put( locale.getName(), feature );
- }
- }
-
- return features;
- }
-
- /**
- * Assumes that the locale folder is directly under the translation catalogue's root folder.
- *
- * @param locale
- * @param eclipseInstallPlugin
- * @return The eclipseInstallPlugin's corresponding plug-in in the catalogue for the specified locale.
- */
- private PluginProxy getPluginForLocale(LocaleProxy locale, PluginProxy eclipseInstallPlugin) {
-
- for (File localeDir: rootDirectory.listFiles()) {
- if ( localeDir.getName().equalsIgnoreCase(locale.getName()) ) {
-
- File pluginsRoot = new File(rootDirectory.getAbsolutePath() +
- File.separatorChar + localeDir.getName() +
- File.separatorChar + PLUGINS_PATH);
-
- File pluginFile = new File(pluginsRoot.getAbsolutePath() + File.separator + eclipseInstallPlugin.getName());
-
- if(pluginFile.exists()) {
- List<ResourceProxy> pluginResources = extractResources(pluginFile, pluginFile.getName());
- return new PluginProxy(pluginFile, pluginResources, false, false);
- }
- }
- }
-
- return null;
- }
-
- /**
- * Assumes that the locale folder is directly under the translation catalogue's root folder.
- *
- * @param locale
- * @param eclipseInstallFeature
- * @return The eclipseInstallFeature's corresponding plug-in in the catalogue for the specified locale.
- */
- private PluginProxy getFeatureForLocale(LocaleProxy locale, PluginProxy eclipseInstallFeature) {
-
- for (File localeDir: rootDirectory.listFiles()) {
- if ( localeDir.getName().equalsIgnoreCase(locale.getName()) ) {
-
- File featuresRoot = new File(rootDirectory.getAbsolutePath() +
- File.separatorChar + localeDir.getName() +
- File.separatorChar + FEATURES_PATH);
-
- File featureFile = new File(featuresRoot.getAbsolutePath() + File.separator + eclipseInstallFeature.getName());
-
- if(featureFile.exists()) {
- List<ResourceProxy> featureResources = extractResources(featureFile, featureFile.getName());
- return new PluginProxy(featureFile, featureResources, false, false);
- }
- }
- }
-
- return null;
- }
+ public TranslationCatalogueSimpleParser(File rootDirectory,
+ Set<LocaleProxy> locales) {
+ this.locales = locales;
+ this.rootDirectory = rootDirectory;
+ }
- public ResourceProxy getResourceTranslation(PluginProxy translationCataloguePlugin, ResourceProxy eclipseInstallPluginResource) {
- for (ResourceProxy candidateTranslatedResource: translationCataloguePlugin.getResources()) {
- if (candidateTranslatedResource.getRelativePath().
- equalsIgnoreCase(eclipseInstallPluginResource.getRelativePath())) {
- return candidateTranslatedResource;
- }
- }
- return null;
- }
-
- private List<ResourceProxy> extractResources(File file, String pluginName) {
- List<ResourceProxy> resources = new LinkedList<ResourceProxy>();
- for (File subFile: file.listFiles()) {
- if (subFile.isDirectory()) {
- resources.addAll(extractResources(subFile, pluginName));
- }
- else {
- String absolutePath = subFile.getAbsolutePath();
- String relativePath = absolutePath.substring(absolutePath.indexOf(pluginName));
- relativePath = relativePath.substring(pluginName.length() + 1);
- resources.add(new ResourceProxy(subFile, relativePath));
- }
- }
- return resources;
- }
-
- /**
- * Extract the list of all the relevant locales featured in the Translation Catalogue.
- * The assumption is that all folders within the catalogue's root folder are locales.
- */
- public Set<LocaleProxy> findRelevantLocalesInCatalogue() throws InvalidLocationException {
- Set<LocaleProxy> allLocales = new HashSet<LocaleProxy>();
-
- for (File localeDir: rootDirectory.listFiles()) {
- LocaleProxy candidateLocale = new LocaleProxy(localeDir.getName());
- /* If it's in the list of specified locales, or if the latter is empty (meaning all
- locales are to be included), then the candidate is a relevant locale. */
- if (locales.contains(candidateLocale) || locales.isEmpty()) {
- allLocales.add(candidateLocale);
- }
- }
-
- if (allLocales.isEmpty()) {
- throw new InvalidLocationException(Messages.getString("Error_invalid_translation_catalogue")); //$NON-NLS-1$
- } else if (locales.isEmpty()) {
- locales = allLocales;
- }
-
- return allLocales;
- }
+ /**
+ *
+ * @param eclipseInstallPlugin
+ * @return The different versions (one for each locale) of the same plug-in
+ * within the catalogue.
+ */
+ public Map<String, PluginProxy> getPluginForSpecifiedLocales(
+ PluginProxy eclipseInstallPlugin) {
+ Map<String, PluginProxy> plugins = new HashMap<String, PluginProxy>();
+
+ for (LocaleProxy locale : this.locales) {
+ PluginProxy plugin = getPluginForLocale(locale,
+ eclipseInstallPlugin);
+ if (plugin != null) {
+ plugins.put(locale.getName(), plugin);
+ }
+ }
+ return plugins;
+ }
+
+ /**
+ *
+ * @param eclipseInstallPlugin
+ * @return The different versions (one for each locale) of the same feature
+ * within the catalogue.
+ */
+ public Map<String, PluginProxy> getFeatureForSpecifiedLocales(
+ PluginProxy eclipseInstallFeature) {
+ Map<String, PluginProxy> features = new HashMap<String, PluginProxy>();
+
+ for (LocaleProxy locale : this.locales) {
+ PluginProxy feature = getFeatureForLocale(locale,
+ eclipseInstallFeature);
+ if (feature != null) {
+ features.put(locale.getName(), feature);
+ }
+ }
+
+ return features;
+ }
+
+ /**
+ * Assumes that the locale folder is directly under the translation
+ * catalogue's root folder.
+ *
+ * @param locale
+ * @param eclipseInstallPlugin
+ * @return The eclipseInstallPlugin's corresponding plug-in in the catalogue
+ * for the specified locale.
+ */
+ private PluginProxy getPluginForLocale(LocaleProxy locale,
+ PluginProxy eclipseInstallPlugin) {
+
+ for (File localeDir : rootDirectory.listFiles()) {
+ if (localeDir.getName().equalsIgnoreCase(locale.getName())) {
+
+ File pluginsRoot = new File(rootDirectory.getAbsolutePath()
+ + File.separatorChar + localeDir.getName()
+ + File.separatorChar + PLUGINS_PATH);
+
+ File pluginFile = new File(pluginsRoot.getAbsolutePath()
+ + File.separator + eclipseInstallPlugin.getName());
+
+ if (pluginFile.exists()) {
+ List<ResourceProxy> pluginResources = extractResources(
+ pluginFile, pluginFile.getName());
+ return new PluginProxy(pluginFile, pluginResources, false,
+ false);
+ }
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Assumes that the locale folder is directly under the translation
+ * catalogue's root folder.
+ *
+ * @param locale
+ * @param eclipseInstallFeature
+ * @return The eclipseInstallFeature's corresponding plug-in in the
+ * catalogue for the specified locale.
+ */
+ private PluginProxy getFeatureForLocale(LocaleProxy locale,
+ PluginProxy eclipseInstallFeature) {
+
+ for (File localeDir : rootDirectory.listFiles()) {
+ if (localeDir.getName().equalsIgnoreCase(locale.getName())) {
+
+ File featuresRoot = new File(rootDirectory.getAbsolutePath()
+ + File.separatorChar + localeDir.getName()
+ + File.separatorChar + FEATURES_PATH);
+
+ File featureFile = new File(featuresRoot.getAbsolutePath()
+ + File.separator + eclipseInstallFeature.getName());
+
+ if (featureFile.exists()) {
+ List<ResourceProxy> featureResources = extractResources(
+ featureFile, featureFile.getName());
+ return new PluginProxy(featureFile, featureResources,
+ false, false);
+ }
+ }
+ }
+
+ return null;
+ }
+
+ public ResourceProxy getResourceTranslation(
+ PluginProxy translationCataloguePlugin,
+ ResourceProxy eclipseInstallPluginResource) {
+ for (ResourceProxy candidateTranslatedResource : translationCataloguePlugin
+ .getResources()) {
+ if (candidateTranslatedResource.getRelativePath().equalsIgnoreCase(
+ eclipseInstallPluginResource.getRelativePath())) {
+ return candidateTranslatedResource;
+ }
+ }
+ return null;
+ }
+
+ private List<ResourceProxy> extractResources(File file, String pluginName) {
+ List<ResourceProxy> resources = new LinkedList<ResourceProxy>();
+ for (File subFile : file.listFiles()) {
+ if (subFile.isDirectory()) {
+ resources.addAll(extractResources(subFile, pluginName));
+ } else {
+ String absolutePath = subFile.getAbsolutePath();
+ String relativePath = absolutePath.substring(absolutePath
+ .indexOf(pluginName));
+ relativePath = relativePath.substring(pluginName.length() + 1);
+ resources.add(new ResourceProxy(subFile, relativePath));
+ }
+ }
+ return resources;
+ }
+
+ /**
+ * Extract the list of all the relevant locales featured in the Translation
+ * Catalogue. The assumption is that all folders within the catalogue's root
+ * folder are locales.
+ */
+ public Set<LocaleProxy> findRelevantLocalesInCatalogue()
+ throws InvalidLocationException {
+ Set<LocaleProxy> allLocales = new HashSet<LocaleProxy>();
+
+ for (File localeDir : rootDirectory.listFiles()) {
+ LocaleProxy candidateLocale = new LocaleProxy(localeDir.getName());
+ /*
+ * If it's in the list of specified locales, or if the latter is
+ * empty (meaning all locales are to be included), then the
+ * candidate is a relevant locale.
+ */
+ if (locales.contains(candidateLocale) || locales.isEmpty()) {
+ allLocales.add(candidateLocale);
+ }
+ }
+
+ if (allLocales.isEmpty()) {
+ throw new InvalidLocationException(
+ Messages.getString("Error_invalid_translation_catalogue")); //$NON-NLS-1$
+ } else if (locales.isEmpty()) {
+ locales = allLocales;
+ }
+
+ return allLocales;
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Attribute.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Attribute.java
index fc2c894..094a202 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Attribute.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Attribute.java
@@ -11,38 +11,40 @@
package org.eclipse.babel.build.core.xml;
/**
- * An attribute pair on an Element in a Builder document tree.
+ * An attribute pair on an Element in a Builder document tree.
*/
public class Attribute {
- private final String name;
- private final String value;
+ private final String name;
+ private final String value;
- /**
- * Create a new attribute.
- *
- * @param name The name of the attribute.
- * @param value The value of the attribute.
- */
- public Attribute(String name, String value){
- this.name = name;
- this.value = value;
- }
+ /**
+ * Create a new attribute.
+ *
+ * @param name
+ * The name of the attribute.
+ * @param value
+ * The value of the attribute.
+ */
+ public Attribute(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
- /**
- * Retrieve the attribute's name.
- *
- * @return The attribute's name.
- */
- public String getName() {
- return name;
- }
+ /**
+ * Retrieve the attribute's name.
+ *
+ * @return The attribute's name.
+ */
+ public String getName() {
+ return name;
+ }
- /**
- * Retrieve the attribute's value.
- *
- * @return The attribute's value.
- */
- public String getValue() {
- return value;
- }
+ /**
+ * Retrieve the attribute's value.
+ *
+ * @return The attribute's value.
+ */
+ public String getValue() {
+ return value;
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Builder.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Builder.java
index a2f5306..a03082d 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Builder.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Builder.java
@@ -20,99 +20,109 @@
* For example:
*
* <pre>
- * Document doc = root("contacts",
- * element("description", text("People that I know")),
- * element("people",
- * element("person").attribute("name", "Alice"),
- * element("person").attribute("name", "Bob")
- * )
- * );
+ * Document doc = root(
+ * "contacts",
+ * element("description", text("People that I know")),
+ * element("people", element("person").attribute("name", "Alice"),
+ * element("person").attribute("name", "Bob")));
*
* doc.render(new XmlWriter(System.out));
* </pre>
*/
-public class Builder{
- private Builder(){}
-
-
- public interface ToNode<T>{
- Element toNode(T t);
- }
-
- public static <T> Element sequence(final Iterable<T> ts, final ToNode<T> toNode){
- return new Element.NodeIterator(){
- Iterator<T> iter = ts.iterator();
-
- @Override
- public Element next() {
- try{
- T t = iter.next();
- return toNode.toNode(t);
- } catch (NoSuchElementException ex){
- /* Reached the end of the iterable */
- return null;
- }
- }
- };
- }
-
- public static Element nodes(Element... children){
- return new Element.NodeSequence(children);
- }
-
-
- /**
- * Creates a new element.
- *
- * @param ns The namespace of the element.
- * @param tag The local name of the element.
- * @param elements The child elements of this element.
- * @return The newly created element.
- */
- public static Element element(String ns, String tag, Element... elements){
- return new TagElement(ns, tag, elements);
- }
-
- /**
- * Creates a new element in the default namespace.
- *
- * @param tag The local name of the element.
- * @param elements The child elements of this element.
- * @return The newly created element.
- */
- public static Element element(String tag, Element... elements){
- return element("", tag, elements);
- }
-
- /**
- * Creates a new text node.
- * @param text The text to be contained within the text node.
- * @return The newly created text node.
- */
- public static Element text(String text){
- return new TextElement(text);
- }
-
- /**
- * Creates a new document with a root element.
- *
- * @param ns The namespace of the root element.
- * @param tag The local name of the root element.
- * @param elements The children of the root element.
- * @return The newly created document.
- */
- public static Document root(String ns, String tag, Element...elements){
- return new Document(new TagElement(ns, tag, elements));
- }
-
- /**
- * Creates a new document with a root element in the default namespace.
- *
- * @param tag The local name of the root element.
- * @param elements The children of the root element.
- * @return The newly create document.
- */
- public static Document root(String tag, Element... elements){
- return root("", tag, elements);
- }
+public class Builder {
+ private Builder() {
+ }
+
+ public interface ToNode<T> {
+ Element toNode(T t);
+ }
+
+ public static <T> Element sequence(final Iterable<T> ts,
+ final ToNode<T> toNode) {
+ return new Element.NodeIterator() {
+ Iterator<T> iter = ts.iterator();
+
+ @Override
+ public Element next() {
+ try {
+ T t = iter.next();
+ return toNode.toNode(t);
+ } catch (NoSuchElementException ex) {
+ /* Reached the end of the iterable */
+ return null;
+ }
+ }
+ };
+ }
+
+ public static Element nodes(Element... children) {
+ return new Element.NodeSequence(children);
+ }
+
+ /**
+ * Creates a new element.
+ *
+ * @param ns
+ * The namespace of the element.
+ * @param tag
+ * The local name of the element.
+ * @param elements
+ * The child elements of this element.
+ * @return The newly created element.
+ */
+ public static Element element(String ns, String tag, Element... elements) {
+ return new TagElement(ns, tag, elements);
+ }
+
+ /**
+ * Creates a new element in the default namespace.
+ *
+ * @param tag
+ * The local name of the element.
+ * @param elements
+ * The child elements of this element.
+ * @return The newly created element.
+ */
+ public static Element element(String tag, Element... elements) {
+ return element("", tag, elements);
+ }
+
+ /**
+ * Creates a new text node.
+ *
+ * @param text
+ * The text to be contained within the text node.
+ * @return The newly created text node.
+ */
+ public static Element text(String text) {
+ return new TextElement(text);
+ }
+
+ /**
+ * Creates a new document with a root element.
+ *
+ * @param ns
+ * The namespace of the root element.
+ * @param tag
+ * The local name of the root element.
+ * @param elements
+ * The children of the root element.
+ * @return The newly created document.
+ */
+ public static Document root(String ns, String tag, Element... elements) {
+ return new Document(new TagElement(ns, tag, elements));
+ }
+
+ /**
+ * Creates a new document with a root element in the default namespace.
+ *
+ * @param tag
+ * The local name of the root element.
+ * @param elements
+ * The children of the root element.
+ * @return The newly create document.
+ */
+ public static Document root(String tag, Element... elements) {
+ return root("", tag, elements);
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Coverage.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Coverage.java
index e7b8753..9c67166 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Coverage.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Coverage.java
@@ -13,8 +13,8 @@
import static org.eclipse.babel.build.core.xml.Builder.*;
/**
- * Implements grammar specific builder elements to aid in the construction of coverage reports.
- * For example:
+ * Implements grammar specific builder elements to aid in the construction of
+ * coverage reports. For example:
*
* <pre>
* Document report = root("coverage",
@@ -29,85 +29,103 @@
* </pre>
*/
public class Coverage {
-
- public static Element coverage(String timestamp, Element... children){
- return root("coverage", children).attribute("timestamp", timestamp);
- }
-
- public static Element archive(String location){
- return element("archive").attribute("location", location);
- }
-
- public static Element translations(String location){
- return element("translations").attribute("location", location);
- }
-
- public static Element output(String location){
- return element("output").attribute("location", location);
- }
-
- /**
- * Creates a coverage report resource element.
- *
- * @param location The location of the resource relative to the root of the eclipse archive.
- * @param locales The locales into which the resource was localized.
- * @return The resource element.
- */
- public static Element resource(String location, Element... locales){
- return resource(location, false, locales);
- }
-
- /**
- * Creates a coverage report resource element.
- *
- * @param location The location of the resource element relative to the root of the eclipse archive.
- * @param excluded Whether or not the resource was excluded from the coverage report.
- * @param locales The locales into which the resource was localized.
- * @return The resource element.
- */
- public static Element resource(String location, boolean excluded, Element... locales){
- return element("resource", locales).attribute("location", location
- ).attribute("excluded", (excluded ? "true" : "false"));
- }
-
- /**
- * Creates a coverage report locale element, representing a target locale.
- *
- * @param name The name of the locale.
- * @param coverage The percentage of the resources that were translated into this locale.
- * @return The locale element.
- */
- public static Element locale(String name, int coverage){
- return locale(name).attribute("coverage", "" + coverage);
- }
-
- /**
- * Creates a coverage report locale element.
- *
- * @param name The name of the locale.
- * @return The locale element.
- */
- public static Element locale(String name){
- return element("locale").attribute("name", name);
- }
-
- public static Element locales(Element... children){
- return element("locales", children);
- }
-
- /**
- * Creates a coverage report plugin element.
- *
- * @param name The name of the plugin (eg. "org.eclipse.core")
- * @param version The version of the plugin that was translated (eg. 3.5.0)
- * @param resources The resources in the plugin that were translated.
- * @return The pluin element.
- */
- public static Element plugin(String name, String version, Element... resources){
- return element("plugin", resources).attribute("name", name).attribute("version", version);
- }
-
- public static Element plugins(Element... plugins){
- return element("plugins", plugins);
- }
+
+ public static Element coverage(String timestamp, Element... children) {
+ return root("coverage", children).attribute("timestamp", timestamp);
+ }
+
+ public static Element archive(String location) {
+ return element("archive").attribute("location", location);
+ }
+
+ public static Element translations(String location) {
+ return element("translations").attribute("location", location);
+ }
+
+ public static Element output(String location) {
+ return element("output").attribute("location", location);
+ }
+
+ /**
+ * Creates a coverage report resource element.
+ *
+ * @param location
+ * The location of the resource relative to the root of the
+ * eclipse archive.
+ * @param locales
+ * The locales into which the resource was localized.
+ * @return The resource element.
+ */
+ public static Element resource(String location, Element... locales) {
+ return resource(location, false, locales);
+ }
+
+ /**
+ * Creates a coverage report resource element.
+ *
+ * @param location
+ * The location of the resource element relative to the root of
+ * the eclipse archive.
+ * @param excluded
+ * Whether or not the resource was excluded from the coverage
+ * report.
+ * @param locales
+ * The locales into which the resource was localized.
+ * @return The resource element.
+ */
+ public static Element resource(String location, boolean excluded,
+ Element... locales) {
+ return element("resource", locales).attribute("location", location)
+ .attribute("excluded", (excluded ? "true" : "false"));
+ }
+
+ /**
+ * Creates a coverage report locale element, representing a target locale.
+ *
+ * @param name
+ * The name of the locale.
+ * @param coverage
+ * The percentage of the resources that were translated into this
+ * locale.
+ * @return The locale element.
+ */
+ public static Element locale(String name, int coverage) {
+ return locale(name).attribute("coverage", "" + coverage);
+ }
+
+ /**
+ * Creates a coverage report locale element.
+ *
+ * @param name
+ * The name of the locale.
+ * @return The locale element.
+ */
+ public static Element locale(String name) {
+ return element("locale").attribute("name", name);
+ }
+
+ public static Element locales(Element... children) {
+ return element("locales", children);
+ }
+
+ /**
+ * Creates a coverage report plugin element.
+ *
+ * @param name
+ * The name of the plugin (eg. "org.eclipse.core")
+ * @param version
+ * The version of the plugin that was translated (eg. 3.5.0)
+ * @param resources
+ * The resources in the plugin that were translated.
+ * @return The pluin element.
+ */
+ public static Element plugin(String name, String version,
+ Element... resources) {
+ return element("plugin", resources).attribute("name", name).attribute(
+ "version", version);
+ }
+
+ public static Element plugins(Element... plugins) {
+ return element("plugins", plugins);
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Document.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Document.java
index 58e9604..8edba69 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Document.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Document.java
@@ -14,24 +14,23 @@
import org.xml.sax.SAXException;
/**
- * Implements a Builder document element.
+ * Implements a Builder document element.
*/
public class Document implements Element {
- private final Element root;
-
+ private final Element root;
- public Document(Element root) {
- this.root = root;
- }
+ public Document(Element root) {
+ this.root = root;
+ }
- public void render(ContentHandler handler) throws SAXException {
- handler.startDocument();
- root.render(handler);
- handler.endDocument();
- }
+ public void render(ContentHandler handler) throws SAXException {
+ handler.startDocument();
+ root.render(handler);
+ handler.endDocument();
+ }
- public Element attribute(String name, String value) {
- root.attribute(name, value);
- return this;
- }
+ public Element attribute(String name, String value) {
+ root.attribute(name, value);
+ return this;
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Element.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Element.java
index 97f7036..d7349b6 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Element.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Element.java
@@ -17,82 +17,92 @@
* Represents an element node in an XML document.
*/
public interface Element {
- /**
- * Implements an iterator over a sequence of nodes.
- */
- public class NodeIterator implements Element {
- public Element attribute(String name, String value) {
- throw new UnsupportedOperationException("NodeIterators do not have attributes");
- }
+ /**
+ * Implements an iterator over a sequence of nodes.
+ */
+ public class NodeIterator implements Element {
+ public Element attribute(String name, String value) {
+ throw new UnsupportedOperationException(
+ "NodeIterators do not have attributes");
+ }
- public void render(ContentHandler handler) throws SAXException {
- Element element;
- while((element = next()) != null){
- element.render(handler);
- }
- }
-
- public Element next(){
- return null;
- }
+ public void render(ContentHandler handler) throws SAXException {
+ Element element;
+ while ((element = next()) != null) {
+ element.render(handler);
+ }
+ }
- }
+ public Element next() {
+ return null;
+ }
- public static class utils{
-
- /**
- * The empty element. Useful when building templates.
- */
- public static final Element EMPTY_ELEMENT = new Element(){
- public Element attribute(String name, String value) {
- return this;
- }
+ }
- public void render(ContentHandler handler) throws SAXException {}
- };
- }
-
- /**
- * Implements a sequence of Elements.
- */
- public static class NodeSequence implements Element{
-
- private final Element[] children;
+ public static class utils {
- public NodeSequence(Element... children){
- this.children = children;
- }
-
- /**
- * This method throws an UnsupportedOperationException as NodeSequences do not have attributes.
- */
- public Element attribute(String name, String value) {
- throw new UnsupportedOperationException("NodeSequences do not have attributes.");
- }
+ /**
+ * The empty element. Useful when building templates.
+ */
+ public static final Element EMPTY_ELEMENT = new Element() {
+ public Element attribute(String name, String value) {
+ return this;
+ }
- public void render(ContentHandler handler) throws SAXException {
- for(Element child : children){
- child.render(handler);
- }
- }
-
- }
+ public void render(ContentHandler handler) throws SAXException {
+ }
+ };
+ }
- /**
- * Recursively render this element and it's children to the provided ContentHandler.
- *
- * @param handler The handler to send the SAX events describing this element and it's children.
- * @throws SAXException
- */
- public void render(ContentHandler handler) throws SAXException;
-
- /**
- * Add an attribute to this element.
- * May throw an UnsupportedOperationException if the underlying implementation does not have attributes.
- *
- * @param name The name of the attribute to create.
- * @param value The value of the created attribute.
- * @return This element. Allows chained calls to attribute.
- */
- public Element attribute(String name, String value);
+ /**
+ * Implements a sequence of Elements.
+ */
+ public static class NodeSequence implements Element {
+
+ private final Element[] children;
+
+ public NodeSequence(Element... children) {
+ this.children = children;
+ }
+
+ /**
+ * This method throws an UnsupportedOperationException as NodeSequences
+ * do not have attributes.
+ */
+ public Element attribute(String name, String value) {
+ throw new UnsupportedOperationException(
+ "NodeSequences do not have attributes.");
+ }
+
+ public void render(ContentHandler handler) throws SAXException {
+ for (Element child : children) {
+ child.render(handler);
+ }
+ }
+
+ }
+
+ /**
+ * Recursively render this element and it's children to the provided
+ * ContentHandler.
+ *
+ * @param handler
+ * The handler to send the SAX events describing this element and
+ * it's children.
+ * @throws SAXException
+ */
+ public void render(ContentHandler handler) throws SAXException;
+
+ /**
+ * Add an attribute to this element. May throw an
+ * UnsupportedOperationException if the underlying implementation does not
+ * have attributes.
+ *
+ * @param name
+ * The name of the attribute to create.
+ * @param value
+ * The value of the created attribute.
+ * @return This element. Allows chained calls to attribute.
+ */
+ public Element attribute(String name, String value);
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Html.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Html.java
index b55d708..a9c56af 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Html.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Html.java
@@ -13,187 +13,203 @@
import static org.eclipse.babel.build.core.xml.Builder.*;
/**
- * Implements grammar specific Builder elements to facilitate the generation of HTML documents.
+ * Implements grammar specific Builder elements to facilitate the generation of
+ * HTML documents.
*/
public class Html {
- public static final String NS = "http://http://www.w3.org/1999/xhtml";
-
- /**
- * Creates a new HTML document.
- *
- * @param children The children of the root element.
- * @return The newly created HTML document.
- */
- public static Document html(Element... children){
- return (Document)root(NS, "html", children).attribute("xmlns", NS);
- }
-
- /**
- * Creates an HTML head element.
- *
- * @param children The children of the document's head.
- * @return The newly create head element.
- */
- public static Element head(Element... children){
- return element(NS, "head", children);
- }
-
- /**
- * Create an HTML title element.
- *
- * @param title The title of the document.
- * @return The newly created title element.
- */
- public static Element title(String title){
- return element(NS, "title", text(title));
- }
-
- /**
- * Creates an HTML link element for linking to an external CSS stylesheet.
- *
- * @param url The URL of the stylesheet.
- * @return The newly created link element.
- */
- public static Element stylesheet(String url){
- return element(NS, "link")
- .attribute("type", "text/css")
- .attribute("href", url)
- .attribute("rel", "stylesheet");
-
- }
-
- public static Element style(String style){
- return element(NS, "style", text(style)).attribute("type", "text/css");
- }
-
- /**
- * Create an HTML body element.
- *
- * @param elements The children of the document's body.
- * @return The newly created body element.
- */
- public static Element body(Element...elements){
- return element(NS, "body", elements);
- }
-
- /**
- * Creates an HTML h1 element.
- *
- * @param title The title to be contained within the h1.
- * @return The newly created h1 element.
- */
- public static Element h1(String title){
- return h1(text(title));
- }
-
- public static Element h1(Element... children){
- return element(NS, "h1", children);
- }
-
- /**
- * Creates an HTML h2 element.
- *
- * @param title The title to be contained within the h2.
- * @return The newly created h2 element.
- */
- public static Element h2(String title){
- return element(NS, "h2", text(title));
- }
-
- public static Element h2(Element... children){
- return element(NS, "h2", children);
- }
-
- /**
- * Creates an HTML table element.
- *
- * @param children The children of the table element.
- * @return The table.
- */
- public static Element table(Element... children){
- return element(NS, "table", children);
- }
-
- /**
- * Creates an HTML table row (tr) element.
- *
- * @param children The children of the tr.
- * @return The tr.
- */
- public static Element tr(Element... children){
- return element(NS, "tr", children);
- }
-
- /**
- * Creates an HTML table data cell (td) element.
- *
- * @param children The children of the td.
- * @return The td.
- */
- public static Element td(Element... children){
- return element(NS, "td", children);
- }
-
- /**
- * Creates an HTML table data cell (td) element.
- *
- * @param text The text to be contained within the td.
- * @return The td.
- */
- public static Element td(String text){
- return td(text(text));
- }
-
- /**
- * Creates an HTML table header cell (th) element.
- *
- * @param title The text to be contained within the th.
- * @return The th.
- */
- public static Element th(String title){
- return element(NS, "th", text(title));
- }
-
-
- /**
- * Creates an HTML anchor element for linking to another hypertext document.
- *
- * @param href The url to link to.
- * @param children The children of the a.
- * @return The a.
- */
- public static Element a(String href, Element... children){
- return element(NS, "a", children).attribute("href", href);
- }
-
- /**
- * Creates an HTML anchor element for linking to another hypertext document.
- *
- * @param href The url to link to.
- * @param description The descriptive text to use with the link.
- * @return The a.
- */
- public static Element a(String href, String description){
- return a(href, text(description));
- }
+ public static final String NS = "http://http://www.w3.org/1999/xhtml";
- /**
- * Creates an HTML unordered list (ul) element.
- *
- * @param children The children of the ul.
- * @return The ul.
- */
- public static Element ul(Element... children){
- return element(NS, "ul", children);
- }
-
- /**
- * Creates an HTML list item (li) element.
- *
- * @param text The text contained within the li.
- * @return The li.
- */
- public static Element li(String text){
- return element(NS, "li", text(text));
- }
+ /**
+ * Creates a new HTML document.
+ *
+ * @param children
+ * The children of the root element.
+ * @return The newly created HTML document.
+ */
+ public static Document html(Element... children) {
+ return (Document) root(NS, "html", children).attribute("xmlns", NS);
+ }
+
+ /**
+ * Creates an HTML head element.
+ *
+ * @param children
+ * The children of the document's head.
+ * @return The newly create head element.
+ */
+ public static Element head(Element... children) {
+ return element(NS, "head", children);
+ }
+
+ /**
+ * Create an HTML title element.
+ *
+ * @param title
+ * The title of the document.
+ * @return The newly created title element.
+ */
+ public static Element title(String title) {
+ return element(NS, "title", text(title));
+ }
+
+ /**
+ * Creates an HTML link element for linking to an external CSS stylesheet.
+ *
+ * @param url
+ * The URL of the stylesheet.
+ * @return The newly created link element.
+ */
+ public static Element stylesheet(String url) {
+ return element(NS, "link").attribute("type", "text/css")
+ .attribute("href", url).attribute("rel", "stylesheet");
+
+ }
+
+ public static Element style(String style) {
+ return element(NS, "style", text(style)).attribute("type", "text/css");
+ }
+
+ /**
+ * Create an HTML body element.
+ *
+ * @param elements
+ * The children of the document's body.
+ * @return The newly created body element.
+ */
+ public static Element body(Element... elements) {
+ return element(NS, "body", elements);
+ }
+
+ /**
+ * Creates an HTML h1 element.
+ *
+ * @param title
+ * The title to be contained within the h1.
+ * @return The newly created h1 element.
+ */
+ public static Element h1(String title) {
+ return h1(text(title));
+ }
+
+ public static Element h1(Element... children) {
+ return element(NS, "h1", children);
+ }
+
+ /**
+ * Creates an HTML h2 element.
+ *
+ * @param title
+ * The title to be contained within the h2.
+ * @return The newly created h2 element.
+ */
+ public static Element h2(String title) {
+ return element(NS, "h2", text(title));
+ }
+
+ public static Element h2(Element... children) {
+ return element(NS, "h2", children);
+ }
+
+ /**
+ * Creates an HTML table element.
+ *
+ * @param children
+ * The children of the table element.
+ * @return The table.
+ */
+ public static Element table(Element... children) {
+ return element(NS, "table", children);
+ }
+
+ /**
+ * Creates an HTML table row (tr) element.
+ *
+ * @param children
+ * The children of the tr.
+ * @return The tr.
+ */
+ public static Element tr(Element... children) {
+ return element(NS, "tr", children);
+ }
+
+ /**
+ * Creates an HTML table data cell (td) element.
+ *
+ * @param children
+ * The children of the td.
+ * @return The td.
+ */
+ public static Element td(Element... children) {
+ return element(NS, "td", children);
+ }
+
+ /**
+ * Creates an HTML table data cell (td) element.
+ *
+ * @param text
+ * The text to be contained within the td.
+ * @return The td.
+ */
+ public static Element td(String text) {
+ return td(text(text));
+ }
+
+ /**
+ * Creates an HTML table header cell (th) element.
+ *
+ * @param title
+ * The text to be contained within the th.
+ * @return The th.
+ */
+ public static Element th(String title) {
+ return element(NS, "th", text(title));
+ }
+
+ /**
+ * Creates an HTML anchor element for linking to another hypertext document.
+ *
+ * @param href
+ * The url to link to.
+ * @param children
+ * The children of the a.
+ * @return The a.
+ */
+ public static Element a(String href, Element... children) {
+ return element(NS, "a", children).attribute("href", href);
+ }
+
+ /**
+ * Creates an HTML anchor element for linking to another hypertext document.
+ *
+ * @param href
+ * The url to link to.
+ * @param description
+ * The descriptive text to use with the link.
+ * @return The a.
+ */
+ public static Element a(String href, String description) {
+ return a(href, text(description));
+ }
+
+ /**
+ * Creates an HTML unordered list (ul) element.
+ *
+ * @param children
+ * The children of the ul.
+ * @return The ul.
+ */
+ public static Element ul(Element... children) {
+ return element(NS, "ul", children);
+ }
+
+ /**
+ * Creates an HTML list item (li) element.
+ *
+ * @param text
+ * The text contained within the li.
+ * @return The li.
+ */
+ public static Element li(String text) {
+ return element(NS, "li", text(text));
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/SavedConfiguration.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/SavedConfiguration.java
index 4a58a49..6cd5e44 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/SavedConfiguration.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/SavedConfiguration.java
@@ -25,85 +25,84 @@
import org.eclipse.babel.build.core.eclipsetarget.EclipseTarget;
import org.eclipse.babel.build.core.translationcatalogue.TranslationCatalogue;
-
public class SavedConfiguration implements Configuration {
- public EclipseTarget eclipseInstall() {
- // TODO Auto-generated method stub
- return null;
- }
+ public EclipseTarget eclipseInstall() {
+ // TODO Auto-generated method stub
+ return null;
+ }
- public Range compatibilityRange() {
- // TODO Auto-generated method stub
- return null;
- }
+ public Range compatibilityRange() {
+ // TODO Auto-generated method stub
+ return null;
+ }
- public List<Filter> filters() {
- // TODO Auto-generated method stub
- return null;
- }
+ public List<Filter> filters() {
+ // TODO Auto-generated method stub
+ return null;
+ }
- public boolean includePseudoTranslations() {
- // TODO Auto-generated method stub
- return false;
- }
+ public boolean includePseudoTranslations() {
+ // TODO Auto-generated method stub
+ return false;
+ }
- public boolean includeResource(PluginProxy plugin, ResourceProxy resouce) {
- // TODO Auto-generated method stub
- return false;
- }
+ public boolean includeResource(PluginProxy plugin, ResourceProxy resouce) {
+ // TODO Auto-generated method stub
+ return false;
+ }
- public File reportLocation() {
- // TODO Auto-generated method stub
- return null;
- }
+ public File reportLocation() {
+ // TODO Auto-generated method stub
+ return null;
+ }
- public Date timestamp() {
- // TODO Auto-generated method stub
- return null;
- }
+ public Date timestamp() {
+ // TODO Auto-generated method stub
+ return null;
+ }
- public TranslationCatalogue translations() {
- // TODO Auto-generated method stub
- return null;
- }
+ public TranslationCatalogue translations() {
+ // TODO Auto-generated method stub
+ return null;
+ }
- public File workingDirectory() {
- // TODO Auto-generated method stub
- return null;
- }
+ public File workingDirectory() {
+ // TODO Auto-generated method stub
+ return null;
+ }
- public Set<LocaleProxy> locales() {
- // TODO Auto-generated method stub
- return null;
- }
+ public Set<LocaleProxy> locales() {
+ // TODO Auto-generated method stub
+ return null;
+ }
- public Set<LocaleGroup> localeGroups() {
- // TODO Auto-generated method stub
- return null;
- }
+ public Set<LocaleGroup> localeGroups() {
+ // TODO Auto-generated method stub
+ return null;
+ }
- public Set<String> excludeList() {
- // TODO Auto-generated method stub
- return null;
- }
+ public Set<String> excludeList() {
+ // TODO Auto-generated method stub
+ return null;
+ }
- public void notifyProgress(String fragmentName) {
- // TODO Auto-generated method stub
- }
+ public void notifyProgress(String fragmentName) {
+ // TODO Auto-generated method stub
+ }
- public boolean includeXmlReport() {
- // TODO Auto-generated method stub
- return false;
- }
+ public boolean includeXmlReport() {
+ // TODO Auto-generated method stub
+ return false;
+ }
- public boolean longReport() {
- // TODO Auto-generated method stub
- return false;
- }
+ public boolean longReport() {
+ // TODO Auto-generated method stub
+ return false;
+ }
- public String localeExtension() {
- // TODO Auto-generated method stub
- return null;
- }
+ public String localeExtension() {
+ // TODO Auto-generated method stub
+ return null;
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Schemas.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Schemas.java
index 1a0099e..cf1b825 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Schemas.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/Schemas.java
@@ -17,31 +17,33 @@
import org.xml.sax.SAXException;
/**
- * Loads an parses the XMLSchemas used to define the format of the coverage reports and saved configurations.
+ * Loads an parses the XMLSchemas used to define the format of the coverage
+ * reports and saved configurations.
*/
public class Schemas {
-
- /**
- * The schema which defines the format of the XML coverage reports.
- */
- public static final Schema COVERAGE = loadSchema("/azure/build/core/xml/coverage.xsd");
-
- /**
- * The schema which defines the format of saved build configurations.
- */
- public static final Schema CONFIG = loadSchema("/azure/build/core/xml/config.xsd");
- private static Schema loadSchema(String schema) {
- try {
- return SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI
- ).newSchema(Schema.class.getResource(schema));
- } catch (SAXException e) {
- throw new AssertionError("Cannot load schema: (" + schema + ")");
- } finally {
- if(schema == null){
- throw new AssertionError("Cannot load schema: (" + schema + ")");
- }
- }
- }
-
+ /**
+ * The schema which defines the format of the XML coverage reports.
+ */
+ public static final Schema COVERAGE = loadSchema("/azure/build/core/xml/coverage.xsd");
+
+ /**
+ * The schema which defines the format of saved build configurations.
+ */
+ public static final Schema CONFIG = loadSchema("/azure/build/core/xml/config.xsd");
+
+ private static Schema loadSchema(String schema) {
+ try {
+ return SchemaFactory
+ .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(
+ Schema.class.getResource(schema));
+ } catch (SAXException e) {
+ throw new AssertionError("Cannot load schema: (" + schema + ")");
+ } finally {
+ if (schema == null) {
+ throw new AssertionError("Cannot load schema: (" + schema + ")");
+ }
+ }
+ }
+
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/TagElement.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/TagElement.java
index d08d086..c9af873 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/TagElement.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/TagElement.java
@@ -21,30 +21,30 @@
* Implements a builder Element node.
*/
public class TagElement implements Element {
- private final String tag;
- private final AttributesImpl attrs = new AttributesImpl();
- private final List<Element> children = new LinkedList<Element>();
- private final String namespace;
-
- public TagElement(String namespace, String tag, Element... children){
- this.namespace = namespace;
- this.tag = tag;
-
- for(Element element : children){
- this.children.add(element);
- }
- }
-
- public void render(ContentHandler handler) throws SAXException {
- handler.startElement(namespace, tag, null, attrs);
- for(Element child : children){
- child.render(handler);
- }
- handler.endElement(namespace, tag, null);
- }
+ private final String tag;
+ private final AttributesImpl attrs = new AttributesImpl();
+ private final List<Element> children = new LinkedList<Element>();
+ private final String namespace;
- public Element attribute(String name, String value) {
- attrs.addAttribute(null, null, name, "string", value);
- return this;
- }
+ public TagElement(String namespace, String tag, Element... children) {
+ this.namespace = namespace;
+ this.tag = tag;
+
+ for (Element element : children) {
+ this.children.add(element);
+ }
+ }
+
+ public void render(ContentHandler handler) throws SAXException {
+ handler.startElement(namespace, tag, null, attrs);
+ for (Element child : children) {
+ child.render(handler);
+ }
+ handler.endElement(namespace, tag, null);
+ }
+
+ public Element attribute(String name, String value) {
+ attrs.addAttribute(null, null, name, "string", value);
+ return this;
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/TextElement.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/TextElement.java
index 4b0fb9d..202aef6 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/TextElement.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/TextElement.java
@@ -16,19 +16,19 @@
/**
* Implements a Builder text node.
*/
-public class TextElement implements Element{
- private final String text;
-
- public TextElement(String text){
- this.text = text;
- }
-
- public void render(ContentHandler handler) throws SAXException {
- char[] ch = text.toCharArray();
- handler.characters(ch, 0, ch.length);
- }
+public class TextElement implements Element {
+ private final String text;
- public Element attribute(String name, String value) {
- throw new UnsupportedOperationException();
- }
+ public TextElement(String text) {
+ this.text = text;
+ }
+
+ public void render(ContentHandler handler) throws SAXException {
+ char[] ch = text.toCharArray();
+ handler.characters(ch, 0, ch.length);
+ }
+
+ public Element attribute(String name, String value) {
+ throw new UnsupportedOperationException();
+ }
}
diff --git a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/XmlWriter.java b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/XmlWriter.java
index 829eb6b..112c6e9 100644
--- a/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/XmlWriter.java
+++ b/org.eclipse.babel.build.core/src/org/eclipse/babel/build/core/xml/XmlWriter.java
@@ -24,95 +24,101 @@
import org.xml.sax.SAXException;
/**
- * A content handler which serialises SAX events to a stream.
- * Useful for serialising XML documents.
+ * A content handler which serialises SAX events to a stream. Useful for
+ * serialising XML documents.
*
- * For a higher level XML serialisation library {@link org.eclipse.babel.build.core.xml.Builder}
+ * For a higher level XML serialisation library
+ * {@link org.eclipse.babel.build.core.xml.Builder}
*/
public class XmlWriter implements ContentHandler {
-
- private final PrintWriter out;
-
- public XmlWriter(PrintWriter out){
- this.out = out;
- }
-
- public XmlWriter(Writer out){
- this(new PrintWriter(out));
- }
-
-
- public XmlWriter(OutputStream out) {
- this(new OutputStreamWriter(out));
- }
- public void characters(char[] ch, int start, int length) throws SAXException {
- out.write(ch, start, length);
- }
+ private final PrintWriter out;
- public void endDocument() throws SAXException {
- out.flush();
- }
+ public XmlWriter(PrintWriter out) {
+ this.out = out;
+ }
- public void endElement(String uri, String localName, String name) throws SAXException {
- out.format("</%s>\n", localName);
- }
+ public XmlWriter(Writer out) {
+ this(new PrintWriter(out));
+ }
- public void endPrefixMapping(String prefix) throws SAXException {
- throw new UnsupportedOperationException();
- }
+ public XmlWriter(OutputStream out) {
+ this(new OutputStreamWriter(out));
+ }
- public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
- throw new UnsupportedOperationException();
- }
+ public void characters(char[] ch, int start, int length)
+ throws SAXException {
+ out.write(ch, start, length);
+ }
- public void processingInstruction(String target, String data) throws SAXException {
- throw new UnsupportedOperationException();
- }
+ public void endDocument() throws SAXException {
+ out.flush();
+ }
- public void setDocumentLocator(Locator locator) {
- throw new UnsupportedOperationException();
- }
+ public void endElement(String uri, String localName, String name)
+ throws SAXException {
+ out.format("</%s>\n", localName);
+ }
- public void skippedEntity(String name) throws SAXException {
- throw new UnsupportedOperationException();
- }
+ public void endPrefixMapping(String prefix) throws SAXException {
+ throw new UnsupportedOperationException();
+ }
- public void startDocument() throws SAXException {
- out.format("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
- }
+ public void ignorableWhitespace(char[] ch, int start, int length)
+ throws SAXException {
+ throw new UnsupportedOperationException();
+ }
- public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException {
- List<String> attrs = new LinkedList<String>();
- int len = atts.getLength();
-
- if(len > 0){
- attrs.add("");
- }
- for(int i = 0; i < len; i++){
- attrs.add(String.format("%s=\"%s\"", atts.getQName(i), atts.getValue(i)));
- }
-
- out.format("<%s%s>", localName, join(" ", attrs));
- }
+ public void processingInstruction(String target, String data)
+ throws SAXException {
+ throw new UnsupportedOperationException();
+ }
- private <T> String join(String seperator, Iterable<T> parts){
- StringBuilder builder = new StringBuilder("");
- for(Iterator<T> it = parts.iterator(); it.hasNext();){
- T part = it.next();
-
- builder.append(part.toString());
- if(it.hasNext()){
- builder.append(seperator);
- }
- }
-
- return builder.toString();
- }
+ public void setDocumentLocator(Locator locator) {
+ throw new UnsupportedOperationException();
+ }
- public void startPrefixMapping(String prefix, String uri)
- throws SAXException {
- throw new UnsupportedOperationException();
- }
+ public void skippedEntity(String name) throws SAXException {
+ throw new UnsupportedOperationException();
+ }
+
+ public void startDocument() throws SAXException {
+ out.format("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+ }
+
+ public void startElement(String uri, String localName, String name,
+ Attributes atts) throws SAXException {
+ List<String> attrs = new LinkedList<String>();
+ int len = atts.getLength();
+
+ if (len > 0) {
+ attrs.add("");
+ }
+ for (int i = 0; i < len; i++) {
+ attrs.add(String.format("%s=\"%s\"", atts.getQName(i),
+ atts.getValue(i)));
+ }
+
+ out.format("<%s%s>", localName, join(" ", attrs));
+ }
+
+ private <T> String join(String seperator, Iterable<T> parts) {
+ StringBuilder builder = new StringBuilder("");
+ for (Iterator<T> it = parts.iterator(); it.hasNext();) {
+ T part = it.next();
+
+ builder.append(part.toString());
+ if (it.hasNext()) {
+ builder.append(seperator);
+ }
+ }
+
+ return builder.toString();
+ }
+
+ public void startPrefixMapping(String prefix, String uri)
+ throws SAXException {
+ throw new UnsupportedOperationException();
+ }
}
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/Activator.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/Activator.java
index a8f83b5..b37cd3d 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/Activator.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/Activator.java
@@ -19,53 +19,60 @@
*/
public class Activator extends AbstractUIPlugin {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.babel.build.ui"; //$NON-NLS-1$
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.babel.build.ui"; //$NON-NLS-1$
- // The shared instance
- private static Activator plugin;
-
- /**
- * The constructor
- */
- public Activator() {
- }
+ // The shared instance
+ private static Activator plugin;
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
+ /**
+ * The constructor
+ */
+ public Activator() {
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
+ * )
+ */
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static Activator getDefault() {
- return plugin;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
+ * )
+ */
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
- /**
- * Returns an image descriptor for the image file at the given
- * plug-in relative path
- *
- * @param path the path
- * @return the image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String path) {
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
+
+ /**
+ * Returns an image descriptor for the image file at the given plug-in
+ * relative path
+ *
+ * @param path
+ * the path
+ * @return the image descriptor
+ */
+ public static ImageDescriptor getImageDescriptor(String path) {
+ return imageDescriptorFromPlugin(PLUGIN_ID, path);
+ }
}
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/handlers/SampleHandler.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/handlers/SampleHandler.java
index e1ffdfe..09fae06 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/handlers/SampleHandler.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/handlers/SampleHandler.java
@@ -16,10 +16,10 @@
public class SampleHandler extends AbstractHandler {
- public SampleHandler() {
- }
+ public SampleHandler() {
+ }
- public Object execute(ExecutionEvent event) throws ExecutionException {
- return null;
- }
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ return null;
+ }
}
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildInitializationOperation.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildInitializationOperation.java
index 0fc2651..1685282 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildInitializationOperation.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildInitializationOperation.java
@@ -28,139 +28,151 @@
import org.eclipse.pde.core.plugin.IPluginModelBase;
import org.eclipse.pde.core.plugin.PluginRegistry;
-public class BuildInitializationOperation implements IRunnableWithProgress{
- private BuildToolModelTable fModelPluginsTable;
- private BuildToolModelTable fModelLocalesTable;
- private BuildToolModelTable fModelIgnoreTable;
- private BuildToolModelTable fModelResourceExclusionTable;
-
- private ISelection fPluginSelection;
- private List<String> fSelectedLocales = null;
- private ArrayList<IProject> fSelectedPlugins;
- private boolean fCanceled;
-
- public BuildInitializationOperation(ISelection pluginSelection, String[] localeSelection) {
- fPluginSelection = pluginSelection;
- if (localeSelection != null) {
- fSelectedLocales = Arrays.asList(localeSelection);
- }
- }
-
- public void run(IProgressMonitor monitor) throws InvocationTargetException,
- InterruptedException {
- this.fillLocalesTable();
- this.fillPluginsTable();
- this.fillIgnoreTable();
- this.fillResourceExclusionTable();
- }
-
- private void fillPluginsTable() {
- if (fPluginSelection instanceof IStructuredSelection) {
- IPath MANIFEST_PATH = new Path("META-INF/MANIFEST.MF"); //$NON-NLS-1$
- IPath PLUGIN_PATH = new Path("plugin.xml"); //$NON-NLS-1$
- IPath FRAGMENT_PATH = new Path("fragment.xml"); //$NON-NLS-1$
+public class BuildInitializationOperation implements IRunnableWithProgress {
+ private BuildToolModelTable fModelPluginsTable;
+ private BuildToolModelTable fModelLocalesTable;
+ private BuildToolModelTable fModelIgnoreTable;
+ private BuildToolModelTable fModelResourceExclusionTable;
- Object[] plugins = ((IStructuredSelection) fPluginSelection).toArray();
-
- fSelectedPlugins = new ArrayList<IProject>(plugins.length);
- for (int i = 0; i < plugins.length; i++) {
- //Handle plug-ins java projects (These are also plug-ins
- if(plugins[i] instanceof IJavaProject) {
- plugins[i] = ((IJavaProject)(((IStructuredSelection) fPluginSelection).toArray()[i])).getProject();
- }
- //If a file was selected, get its parent project
- if (plugins[i] instanceof IFile)
- plugins[i] = ((IFile) plugins[i]).getProject();
+ private ISelection fPluginSelection;
+ private List<String> fSelectedLocales = null;
+ private ArrayList<IProject> fSelectedPlugins;
+ private boolean fCanceled;
- //Add the project to the preselected model list
- if (plugins[i] instanceof IProject
- && (((IProject)plugins[i]).exists(MANIFEST_PATH)
- || ((IProject)plugins[i]).exists(PLUGIN_PATH)
- || ((IProject)plugins[i]).exists(FRAGMENT_PATH))) {
- fSelectedPlugins.add((IProject)plugins[i]);
- }
- }
- }
- //Get all models (workspace and external) excluding fragment models
- IPluginModelBase[] pluginModels = PluginRegistry.getAllModels(false);
+ public BuildInitializationOperation(ISelection pluginSelection,
+ String[] localeSelection) {
+ fPluginSelection = pluginSelection;
+ if (localeSelection != null) {
+ fSelectedLocales = Arrays.asList(localeSelection);
+ }
+ }
- //Populate list to an InternationalizeModelTable
- fModelPluginsTable = new BuildToolModelTable();
- for (int i = 0; i < pluginModels.length; i++) {
- fModelPluginsTable.addToModelTable(pluginModels[i], pluginModels[i].getUnderlyingResource() != null ? isPluginSelected(pluginModels[i].getUnderlyingResource().getProject()) : false);
- }
- }
-
- private void fillLocalesTable() {
- fModelLocalesTable = new BuildToolModelTable();
- Locale[] availableLocales = Locale.getAvailableLocales();
- for (int i = 0; i < availableLocales.length; i++) {
- fModelLocalesTable.addToModelTable(availableLocales[i], availableLocales != null ? isLocaleSelected(availableLocales[i].toString()) : false);
- }
- }
-
- private void fillIgnoreTable() {
- fModelIgnoreTable = new BuildToolModelTable();
- }
-
- private void fillResourceExclusionTable() {
- fModelResourceExclusionTable = new BuildToolModelTable();
- }
-
- /**
- *
- * @return whether or not the operation was canceled
- */
- public boolean wasCanceled() {
- return fCanceled;
- }
+ public void run(IProgressMonitor monitor) throws InvocationTargetException,
+ InterruptedException {
+ this.fillLocalesTable();
+ this.fillPluginsTable();
+ this.fillIgnoreTable();
+ this.fillResourceExclusionTable();
+ }
- /**
- *
- * @param project
- * @return whether or not the project was preselected
- */
- public boolean isPluginSelected(IProject project) {
- return fSelectedPlugins.contains(project);
- }
+ private void fillPluginsTable() {
+ if (fPluginSelection instanceof IStructuredSelection) {
+ IPath MANIFEST_PATH = new Path("META-INF/MANIFEST.MF"); //$NON-NLS-1$
+ IPath PLUGIN_PATH = new Path("plugin.xml"); //$NON-NLS-1$
+ IPath FRAGMENT_PATH = new Path("fragment.xml"); //$NON-NLS-1$
- public boolean isLocaleSelected(String locale) {
- if (fSelectedLocales == null) {
- return false;
- }
-
- return fSelectedLocales.contains(locale);
- }
-
- /**
- *
- * @return the BuildToolModelTable containing the plug-ins
- */
- public BuildToolModelTable getPluginsTable() {
- return fModelPluginsTable;
- }
-
- /**
- *
- * @return the BuildToolModelTable containing the locales
- */
- public BuildToolModelTable getLocalesTable() {
- return fModelLocalesTable;
- }
-
- /**
- *
- * @return the BuildToolModelTable containing the ignore list
- */
- public BuildToolModelTable getIgnoreTable() {
- return fModelIgnoreTable;
- }
+ Object[] plugins = ((IStructuredSelection) fPluginSelection)
+ .toArray();
- /**
- *
- * @return the BuildToolModelTable containing the resource exclusion list
- */
- public BuildToolModelTable getResourceExclusionTable() {
- return fModelResourceExclusionTable;
- }
+ fSelectedPlugins = new ArrayList<IProject>(plugins.length);
+ for (int i = 0; i < plugins.length; i++) {
+ // Handle plug-ins java projects (These are also plug-ins
+ if (plugins[i] instanceof IJavaProject) {
+ plugins[i] = ((IJavaProject) (((IStructuredSelection) fPluginSelection)
+ .toArray()[i])).getProject();
+ }
+ // If a file was selected, get its parent project
+ if (plugins[i] instanceof IFile)
+ plugins[i] = ((IFile) plugins[i]).getProject();
+
+ // Add the project to the preselected model list
+ if (plugins[i] instanceof IProject
+ && (((IProject) plugins[i]).exists(MANIFEST_PATH)
+ || ((IProject) plugins[i]).exists(PLUGIN_PATH) || ((IProject) plugins[i])
+ .exists(FRAGMENT_PATH))) {
+ fSelectedPlugins.add((IProject) plugins[i]);
+ }
+ }
+ }
+ // Get all models (workspace and external) excluding fragment models
+ IPluginModelBase[] pluginModels = PluginRegistry.getAllModels(false);
+
+ // Populate list to an InternationalizeModelTable
+ fModelPluginsTable = new BuildToolModelTable();
+ for (int i = 0; i < pluginModels.length; i++) {
+ fModelPluginsTable
+ .addToModelTable(
+ pluginModels[i],
+ pluginModels[i].getUnderlyingResource() != null ? isPluginSelected(pluginModels[i]
+ .getUnderlyingResource().getProject())
+ : false);
+ }
+ }
+
+ private void fillLocalesTable() {
+ fModelLocalesTable = new BuildToolModelTable();
+ Locale[] availableLocales = Locale.getAvailableLocales();
+ for (int i = 0; i < availableLocales.length; i++) {
+ fModelLocalesTable
+ .addToModelTable(
+ availableLocales[i],
+ availableLocales != null ? isLocaleSelected(availableLocales[i]
+ .toString()) : false);
+ }
+ }
+
+ private void fillIgnoreTable() {
+ fModelIgnoreTable = new BuildToolModelTable();
+ }
+
+ private void fillResourceExclusionTable() {
+ fModelResourceExclusionTable = new BuildToolModelTable();
+ }
+
+ /**
+ *
+ * @return whether or not the operation was canceled
+ */
+ public boolean wasCanceled() {
+ return fCanceled;
+ }
+
+ /**
+ *
+ * @param project
+ * @return whether or not the project was preselected
+ */
+ public boolean isPluginSelected(IProject project) {
+ return fSelectedPlugins.contains(project);
+ }
+
+ public boolean isLocaleSelected(String locale) {
+ if (fSelectedLocales == null) {
+ return false;
+ }
+
+ return fSelectedLocales.contains(locale);
+ }
+
+ /**
+ *
+ * @return the BuildToolModelTable containing the plug-ins
+ */
+ public BuildToolModelTable getPluginsTable() {
+ return fModelPluginsTable;
+ }
+
+ /**
+ *
+ * @return the BuildToolModelTable containing the locales
+ */
+ public BuildToolModelTable getLocalesTable() {
+ return fModelLocalesTable;
+ }
+
+ /**
+ *
+ * @return the BuildToolModelTable containing the ignore list
+ */
+ public BuildToolModelTable getIgnoreTable() {
+ return fModelIgnoreTable;
+ }
+
+ /**
+ *
+ * @return the BuildToolModelTable containing the resource exclusion list
+ */
+ public BuildToolModelTable getResourceExclusionTable() {
+ return fModelResourceExclusionTable;
+ }
}
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolImages.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolImages.java
index f3e1e53..5f2cddb 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolImages.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolImages.java
@@ -17,19 +17,21 @@
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.resource.ImageDescriptor;
-
public class BuildToolImages {
- public final static String ICONS_PATH = "icons/"; //$NON-NLS-1$
-
- public static final ImageDescriptor PLUGIN = create(ICONS_PATH, "plugin.gif"); //$NON-NLS-1$
- public static final ImageDescriptor LOCALE = create(ICONS_PATH, "locale.gif"); //$NON-NLS-1$
+ public final static String ICONS_PATH = "icons/"; //$NON-NLS-1$
- private static ImageDescriptor create(String prefix, String name) {
- return ImageDescriptor.createFromURL(makeImageURL(prefix, name));
- }
-
- private static URL makeImageURL(String prefix, String name) {
- String path = "$nl$/" + prefix + name; //$NON-NLS-1$
- return FileLocator.find(Activator.getDefault().getBundle(), new Path(path), null);
- }
+ public static final ImageDescriptor PLUGIN = create(ICONS_PATH,
+ "plugin.gif"); //$NON-NLS-1$
+ public static final ImageDescriptor LOCALE = create(ICONS_PATH,
+ "locale.gif"); //$NON-NLS-1$
+
+ private static ImageDescriptor create(String prefix, String name) {
+ return ImageDescriptor.createFromURL(makeImageURL(prefix, name));
+ }
+
+ private static URL makeImageURL(String prefix, String name) {
+ String path = "$nl$/" + prefix + name; //$NON-NLS-1$
+ return FileLocator.find(Activator.getDefault().getBundle(), new Path(
+ path), null);
+ }
}
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolModelTable.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolModelTable.java
index 11f0c49..5023536 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolModelTable.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolModelTable.java
@@ -14,88 +14,93 @@
import java.util.List;
public class BuildToolModelTable {
- private List<Object> fAvailableModels;
- private List<Object> fPreSelectedModels;
+ private List<Object> fAvailableModels;
+ private List<Object> fPreSelectedModels;
- public BuildToolModelTable() {
- fAvailableModels = new ArrayList<Object>();
- fPreSelectedModels = new ArrayList<Object>();
- }
+ public BuildToolModelTable() {
+ fAvailableModels = new ArrayList<Object>();
+ fPreSelectedModels = new ArrayList<Object>();
+ }
- /**
- * Adds the model to the model table. Takes into consideration the specified
- * selection.
- * @param model
- * @param selected
- */
- public void addToModelTable(Object model, boolean selected) {
- if (selected)
- fPreSelectedModels.add(model);
- else
- fAvailableModels.add(model);
- }
+ /**
+ * Adds the model to the model table. Takes into consideration the specified
+ * selection.
+ *
+ * @param model
+ * @param selected
+ */
+ public void addToModelTable(Object model, boolean selected) {
+ if (selected)
+ fPreSelectedModels.add(model);
+ else
+ fAvailableModels.add(model);
+ }
- /**
- * Adds the model to the model table.
- * @param model
- */
- public void addModel(Object model) {
- fAvailableModels.add(model);
- }
+ /**
+ * Adds the model to the model table.
+ *
+ * @param model
+ */
+ public void addModel(Object model) {
+ fAvailableModels.add(model);
+ }
- /**
- * Removes the specified model from the model table.
- * @param model
- */
- public void removeModel(Object model) {
- fAvailableModels.remove(model);
- }
-
- public void addToPreselected(Object model) {
- fPreSelectedModels.add(model);
- }
-
- public void removeFromPreselected(Object model) {
- fPreSelectedModels.remove(model);
- }
+ /**
+ * Removes the specified model from the model table.
+ *
+ * @param model
+ */
+ public void removeModel(Object model) {
+ fAvailableModels.remove(model);
+ }
- /**
- *
- * @return the number of models in the table
- */
- public int getModelCount() {
- return fPreSelectedModels.size() + fAvailableModels.size();
- }
+ public void addToPreselected(Object model) {
+ fPreSelectedModels.add(model);
+ }
- /**
- * Returns the list of models stored in the model table
- * @return the array of models
- */
- public Object[] getModels() {
- return fAvailableModels.toArray();
- }
+ public void removeFromPreselected(Object model) {
+ fPreSelectedModels.remove(model);
+ }
- /**
- * Returns the list of preselected models stored in the model table
- * @return the array of preselected models
- */
- public Object[] getPreSelected() {
- return fPreSelectedModels.toArray();
- }
+ /**
+ *
+ * @return the number of models in the table
+ */
+ public int getModelCount() {
+ return fPreSelectedModels.size() + fAvailableModels.size();
+ }
- /**
- *
- * @return whether or not the model table contains preselected models
- */
- public boolean hasPreSelected() {
- return fPreSelectedModels.size() > 0;
- }
+ /**
+ * Returns the list of models stored in the model table
+ *
+ * @return the array of models
+ */
+ public Object[] getModels() {
+ return fAvailableModels.toArray();
+ }
- /**
- *
- * @return whether or not the list of models is empty
- */
- public boolean isEmpty() {
- return fAvailableModels.size() == 0;
- }
+ /**
+ * Returns the list of preselected models stored in the model table
+ *
+ * @return the array of preselected models
+ */
+ public Object[] getPreSelected() {
+ return fPreSelectedModels.toArray();
+ }
+
+ /**
+ *
+ * @return whether or not the model table contains preselected models
+ */
+ public boolean hasPreSelected() {
+ return fPreSelectedModels.size() > 0;
+ }
+
+ /**
+ *
+ * @return whether or not the list of models is empty
+ */
+ public boolean isEmpty() {
+ return fAvailableModels.size() == 0;
+ }
}
\ No newline at end of file
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizard.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizard.java
index 244e7c6..e4d3bb5 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizard.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizard.java
@@ -26,184 +26,177 @@
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
+public class BuildToolWizard extends Wizard implements IExportWizard {
-public class BuildToolWizard extends Wizard
- implements IExportWizard {
+ private final static String SELECTED_LOCALES = "BuildToolWizardLocalePage#Locales";
- private final static String SELECTED_LOCALES = "BuildToolWizardLocalePage#Locales";
-
- private BuildToolWizardPluginPage fPage1;
- private BuildToolWizardLocalePage fPage2;
- private BuildToolWizardConfigurationPage fPage3;
-
- public BuildToolWizard() {
- IDialogSettings master = Activator.getDefault().getDialogSettings();
- setDialogSettings(getSection(master));
- setWindowTitle(Messages.getString("Wizard_Title"));
- }
-
- private IDialogSettings getSection(IDialogSettings master){
- IDialogSettings settings = master.getSection("BuildToolWizard");
- if(settings == null){
- return master.addNewSection("BuildToolWizard");
- }
- return settings;
- }
-
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- BuildInitializationOperation runnable = new BuildInitializationOperation(selection, getDialogSettings().getArray(SELECTED_LOCALES));
- try {
- PlatformUI.getWorkbench().getProgressService().busyCursorWhile(runnable);
- }
- catch (InvocationTargetException e) {e.printStackTrace();}
- catch (InterruptedException e) {e.printStackTrace();}
- finally {
- if (runnable.wasCanceled()) {
- return;
- }
- fPage1 = new BuildToolWizardPluginPage("BuildToolWizardPluginPage.Page1", runnable.getPluginsTable()); //$NON-NLS-1$
- fPage2 = new BuildToolWizardLocalePage("BuildToolWizardLocalePage.Page2", runnable.getLocalesTable()); //$NON-NLS-1$
- fPage3 = new BuildToolWizardConfigurationPage("BuildToolWizardConfigurationPage.Page3", runnable.getIgnoreTable(), runnable.getResourceExclusionTable()); //$NON-NLS-1$
- }
- }
-
- public void addPages() {
- addPage(fPage1);
- addPage(fPage2);
- addPage(fPage3);
- }
-
- private String getGroupName(String nameWithDescription) {
- if(nameWithDescription.startsWith("Group1")) {
- return "Group1";
- }
- else if(nameWithDescription.startsWith("Group2a")) {
- return "Group2a";
- }
- else if(nameWithDescription.startsWith("Group2")) {
- return "Group2";
- }
- else if(nameWithDescription.startsWith("GroupBidi")) {
- return "GroupBidi";
- }
- else {
- return "All";
- }
-
- }
-
- public boolean performFinish() {
- fPage1.storeSettings();
- fPage2.storeSettings();
- fPage3.storeSettings();
-
+ private BuildToolWizardPluginPage fPage1;
+ private BuildToolWizardLocalePage fPage2;
+ private BuildToolWizardConfigurationPage fPage3;
+
+ public BuildToolWizard() {
+ IDialogSettings master = Activator.getDefault().getDialogSettings();
+ setDialogSettings(getSection(master));
+ setWindowTitle(Messages.getString("Wizard_Title"));
+ }
+
+ private IDialogSettings getSection(IDialogSettings master) {
+ IDialogSettings settings = master.getSection("BuildToolWizard");
+ if (settings == null) {
+ return master.addNewSection("BuildToolWizard");
+ }
+ return settings;
+ }
+
+ public void init(IWorkbench workbench, IStructuredSelection selection) {
+ BuildInitializationOperation runnable = new BuildInitializationOperation(
+ selection, getDialogSettings().getArray(SELECTED_LOCALES));
+ try {
+ PlatformUI.getWorkbench().getProgressService()
+ .busyCursorWhile(runnable);
+ } catch (InvocationTargetException e) {
+ e.printStackTrace();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ } finally {
+ if (runnable.wasCanceled()) {
+ return;
+ }
+ fPage1 = new BuildToolWizardPluginPage(
+ "BuildToolWizardPluginPage.Page1", runnable.getPluginsTable()); //$NON-NLS-1$
+ fPage2 = new BuildToolWizardLocalePage(
+ "BuildToolWizardLocalePage.Page2", runnable.getLocalesTable()); //$NON-NLS-1$
+ fPage3 = new BuildToolWizardConfigurationPage(
+ "BuildToolWizardConfigurationPage.Page3", runnable.getIgnoreTable(), runnable.getResourceExclusionTable()); //$NON-NLS-1$
+ }
+ }
+
+ public void addPages() {
+ addPage(fPage1);
+ addPage(fPage2);
+ addPage(fPage3);
+ }
+
+ private String getGroupName(String nameWithDescription) {
+ if (nameWithDescription.startsWith("Group1")) {
+ return "Group1";
+ } else if (nameWithDescription.startsWith("Group2a")) {
+ return "Group2a";
+ } else if (nameWithDescription.startsWith("Group2")) {
+ return "Group2";
+ } else if (nameWithDescription.startsWith("GroupBidi")) {
+ return "GroupBidi";
+ } else {
+ return "All";
+ }
+
+ }
+
+ public boolean performFinish() {
+ fPage1.storeSettings();
+ fPage2.storeSettings();
+ fPage3.storeSettings();
+
Object[] selectedPlugins;
String eclipseArchivePath;
-
+
String[] selectedLocales;
-
+
String workingDirectoryLocation;
String translationCataloguelocation;
Object[] ignoreList;
Object[] reportFilterPatterns;
boolean includeXmlReport;
boolean longReport;
-
- if(fPage1.isGeneratingFromPlugins()) {
+
+ if (fPage1.isGeneratingFromPlugins()) {
selectedPlugins = fPage1.getSelectedPlugins();
eclipseArchivePath = "";
- }
- else {
+ } else {
eclipseArchivePath = fPage1.getEclipseArchiveLocation();
selectedPlugins = null;
}
-
- if(fPage2.isGeneratingFromLocales()) {
- if(fPage2.isGeneratingForAllLocales()) {
- selectedLocales = new String[0];
- }
- else {
- Object[] locales = fPage2.getSelectedLocales();
- selectedLocales = new String[locales.length];
- for(int i=0; i<locales.length; i++) {
- selectedLocales[i] = locales[i].toString();
- }
- }
+
+ if (fPage2.isGeneratingFromLocales()) {
+ if (fPage2.isGeneratingForAllLocales()) {
+ selectedLocales = new String[0];
+ } else {
+ Object[] locales = fPage2.getSelectedLocales();
+ selectedLocales = new String[locales.length];
+ for (int i = 0; i < locales.length; i++) {
+ selectedLocales[i] = locales[i].toString();
+ }
+ }
+ } else {
+ selectedLocales = new String[] { getGroupName(fPage2
+ .getSelectedGroup()) };
}
- else {
- selectedLocales = new String[]{getGroupName(fPage2.getSelectedGroup())};
- }
-
+
workingDirectoryLocation = fPage3.getWorkingDirectoryLocation();
translationCataloguelocation = fPage3.getTranslationCatalogueLocation();
ignoreList = fPage3.getIgnoreList();
reportFilterPatterns = fPage3.getReportFilterPatterns();
includeXmlReport = fPage3.getXmlReportSelection();
longReport = fPage3.getLongReportSelection();
-
+
final LanguagePackGenerationHandler handler;
-
- if(selectedPlugins == null) {
- handler = new LanguagePackGenerationHandler(eclipseArchivePath,
- selectedLocales,
- workingDirectoryLocation,
- translationCataloguelocation,
- ignoreList,
- reportFilterPatterns,
- includeXmlReport,
- longReport);
+
+ if (selectedPlugins == null) {
+ handler = new LanguagePackGenerationHandler(eclipseArchivePath,
+ selectedLocales, workingDirectoryLocation,
+ translationCataloguelocation, ignoreList,
+ reportFilterPatterns, includeXmlReport, longReport);
+ } else {
+ handler = new LanguagePackGenerationHandler(selectedPlugins,
+ selectedLocales, workingDirectoryLocation,
+ translationCataloguelocation, ignoreList,
+ reportFilterPatterns, includeXmlReport, longReport);
}
- else {
- handler = new LanguagePackGenerationHandler(selectedPlugins,
- selectedLocales,
- workingDirectoryLocation,
- translationCataloguelocation,
- ignoreList,
- reportFilterPatterns,
- includeXmlReport,
- longReport);
- }
-
+
Job languagePackGenerationJob = new Job("Generating Language Pack") {
@Override
protected IStatus run(IProgressMonitor monitor) {
String errorMessage = handler.generateLanguagePack(monitor);
if (errorMessage.equals("")) {
- return new Status(Status.OK, "Generating Language Pack", "Language pack successfully generated");
+ return new Status(Status.OK, "Generating Language Pack",
+ "Language pack successfully generated");
}
- return new Status(Status.ERROR, "Generating Language Pack", errorMessage);
+ return new Status(Status.ERROR, "Generating Language Pack",
+ errorMessage);
}
};
languagePackGenerationJob.setPriority(Job.BUILD);
languagePackGenerationJob.schedule();
-
- PlatformUI.getWorkbench().getProgressService().showInDialog(new Shell(), languagePackGenerationJob);
+
+ PlatformUI.getWorkbench().getProgressService()
+ .showInDialog(new Shell(), languagePackGenerationJob);
return true;
}
- @Override
- public boolean canFinish() {
- return fPage1.canFlipToNextPage() && fPage2.canFlipToNextPage() && fPage3.isPageComplete();
- }
-
- @Override
- public IWizardPage getPreviousPage(IWizardPage currentPage) {
- if (currentPage.equals(fPage3)) {
- return fPage2;
- } else if (currentPage.equals(fPage2)) {
- return fPage1;
- }
- return null;
- }
-
- @Override
- public IWizardPage getNextPage(IWizardPage currentPage) {
- if (currentPage.equals(fPage1)) {
- return fPage2;
- } else if (currentPage.equals(fPage2)) {
- return fPage3;
- }
- return null;
- }
+ @Override
+ public boolean canFinish() {
+ return fPage1.canFlipToNextPage() && fPage2.canFlipToNextPage()
+ && fPage3.isPageComplete();
+ }
+
+ @Override
+ public IWizardPage getPreviousPage(IWizardPage currentPage) {
+ if (currentPage.equals(fPage3)) {
+ return fPage2;
+ } else if (currentPage.equals(fPage2)) {
+ return fPage1;
+ }
+ return null;
+ }
+
+ @Override
+ public IWizardPage getNextPage(IWizardPage currentPage) {
+ if (currentPage.equals(fPage1)) {
+ return fPage2;
+ } else if (currentPage.equals(fPage2)) {
+ return fPage3;
+ }
+ return null;
+ }
}
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizardConfigurationPage.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizardConfigurationPage.java
index edf940a..5af5b85 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizardConfigurationPage.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizardConfigurationPage.java
@@ -47,628 +47,727 @@
public class BuildToolWizardConfigurationPage extends BuildToolWizardPage {
- private static final String[] STRING = new String[]{};
- private static final String XML_REPORT = "BuildToolWizardConfigurationPage#fXMLReportGeneration";
- private static final String LONG_REPORT = "BuildToolWizardConfigurationPage#fLongReportGeneration";
- private static final String TRANSLATION_CATALOG_LOCATION = "BuildToolWizardConfigurationPage#fTranslationCatalogueLocationText";
- private static final String WORKING_DIRECTORY = "BuildToolWizardConfigurationPage#fWorkingDirectoryLocationText";
- private static final String IGNORE_LIST = "BuildToolWizardConfigurationPage#IgnoreList";
- private static final String IGNORE_LIST_CHECKED = "BuildToolWizardConfigurationPage#IgnoreListChecked";
- private static final String EXCLUDE_LIST = "BuildToolWizardConfigurationPage#ExcludeList";
- private static final String EXCLUDE_LIST_CHECKED = "BuildToolWizardConfigurationPage#ExcludeListChecked";
-
-
- private static final int VIEWER_WIDTH = 450;
- private static final int VIEWER_HEIGHT = 110;
- private static final int LIST_LABEL_INDENT = 6;
- private static final int BUTTON_WIDTH = 110;
- private static final int LIST_SEPARATOR = 20;
- private static final int TEXT_WIDTH = 325;
- private static final int LABEL_WIDTH = 190;
-
- private BuildToolModelTable fModelIgnoreTable;
- private BuildToolModelTable fModelResourceExclusionTable;
-
- private Button fTranslationCatalogueBrowseButton;
- private Button fWorkingDirectoryBrowseButton;
-
- private Label fWorkingDirectoryLocationLabel;
- private Label fTranslationCatalogueLocationLabel;
-
- private Text fWorkingDirectoryLocationText;
- private Text fTranslationCatalogueLocationText;
+ private static final String[] STRING = new String[] {};
+ private static final String XML_REPORT = "BuildToolWizardConfigurationPage#fXMLReportGeneration";
+ private static final String LONG_REPORT = "BuildToolWizardConfigurationPage#fLongReportGeneration";
+ private static final String TRANSLATION_CATALOG_LOCATION = "BuildToolWizardConfigurationPage#fTranslationCatalogueLocationText";
+ private static final String WORKING_DIRECTORY = "BuildToolWizardConfigurationPage#fWorkingDirectoryLocationText";
+ private static final String IGNORE_LIST = "BuildToolWizardConfigurationPage#IgnoreList";
+ private static final String IGNORE_LIST_CHECKED = "BuildToolWizardConfigurationPage#IgnoreListChecked";
+ private static final String EXCLUDE_LIST = "BuildToolWizardConfigurationPage#ExcludeList";
+ private static final String EXCLUDE_LIST_CHECKED = "BuildToolWizardConfigurationPage#ExcludeListChecked";
- private CheckboxTableViewer fLanguagePackResourceIgnoreViewer;
- private Label fLanguagePackListLabel;
- private Button fAddLanguagePackFilterButton;
- private Button fRemoveLanguagePackFilterButton;
- private String fChosenLanguagePackFilter;
-
- private CheckboxTableViewer fCoverageReportResourceFilterViewer;
- private Label fCoverageReportListLabel;
- private Button fAddCoverageReportFilterButton;
- private Button fRemoveCoverageReportFilterButton;
- private String fChosenCoverageReportFilter;
-
- private LanguagePackFilterDialog fLanguagePackFilterDialog;
- private CoverageReportFilterDialog fCoverageReportFilterDialog;
- private Button fLongReportGeneration;
- private Button fXMLReportGeneration;
-
- private static ToT<Object,String> TO_STRING = new ToT<Object, String>() {
- public String convert(Object from) {
- return from.toString();
- }
- };
+ private static final int VIEWER_WIDTH = 450;
+ private static final int VIEWER_HEIGHT = 110;
+ private static final int LIST_LABEL_INDENT = 6;
+ private static final int BUTTON_WIDTH = 110;
+ private static final int LIST_SEPARATOR = 20;
+ private static final int TEXT_WIDTH = 325;
+ private static final int LABEL_WIDTH = 190;
- private class TextModifyListener implements ModifyListener {
- public void modifyText(ModifyEvent e) {
- textSelectionChanged();
- }
- }
-
- protected class IgnoreListContentProvider implements IStructuredContentProvider {
- public Object[] getElements(Object parent) {
- return fModelIgnoreTable.getModels();
- }
+ private BuildToolModelTable fModelIgnoreTable;
+ private BuildToolModelTable fModelResourceExclusionTable;
- public void dispose() {
- }
+ private Button fTranslationCatalogueBrowseButton;
+ private Button fWorkingDirectoryBrowseButton;
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
- }
-
- protected class ExcludeListContentProvider implements IStructuredContentProvider {
- public Object[] getElements(Object parent) {
- return fModelResourceExclusionTable.getModels();
- }
+ private Label fWorkingDirectoryLocationLabel;
+ private Label fTranslationCatalogueLocationLabel;
- public void dispose() {
- }
+ private Text fWorkingDirectoryLocationText;
+ private Text fTranslationCatalogueLocationText;
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
- }
-
- protected BuildToolWizardConfigurationPage(String pageName, BuildToolModelTable modelIgnoreTable, BuildToolModelTable modelExcludeTable) {
- super(pageName);
- this.fModelIgnoreTable = modelIgnoreTable;
- this.fModelResourceExclusionTable = modelExcludeTable;
-
- this.setTitle(Messages.getString("BuildToolWizardConfigurationPage_PageTitle")); //$NON-NLS-1$
- this.setDescription(Messages.getString("BuildToolWizardConfigurationPage_PageDescription")); //$NON-NLS-1$
- }
-
- public void createControl(Composite parent) {
- // Create a scrollable container to hold components
- // This is useful when users are using a lower resolution.
- ScrolledComposite comp = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.H_SCROLL);
- Composite container = new Composite(comp, SWT.NONE);
- container.setLayout(new GridLayout(1, false));
- container.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- createConfigurationArea(container);
-
- createLanguagePackFilteredListArea(container);
-
- createCoverageReportFilteredListArea(container);
-
- setControl(container);
- Dialog.applyDialogFont(container);
- setPageComplete(!"".equals(fWorkingDirectoryLocationText.getText()) && !"".equals(fTranslationCatalogueLocationText.getText()));
-
- // Scrollable container properties
- comp.setContent(container);
- comp.setMinHeight(500);
- comp.setExpandHorizontal(true);
- comp.setExpandVertical(true);
- }
+ private CheckboxTableViewer fLanguagePackResourceIgnoreViewer;
+ private Label fLanguagePackListLabel;
+ private Button fAddLanguagePackFilterButton;
+ private Button fRemoveLanguagePackFilterButton;
+ private String fChosenLanguagePackFilter;
- private void createConfigurationArea(Composite parent) {
- // Create a checkbox allowing for lightweight report generation
- Composite longReportContainer = new Composite(parent, SWT.NONE);
- longReportContainer.setLayout(new GridLayout(1, false));
- longReportContainer.setLayoutData(new GridData(GridData.FILL_BOTH));
- createLongReportCheckbox(longReportContainer);
-
- // Create a checkbox allowing for xml report generation
- Composite xmlReportContainer = new Composite(parent, SWT.NONE);
- xmlReportContainer.setLayout(new GridLayout(1, false));
- xmlReportContainer.setLayoutData(new GridData(GridData.FILL_BOTH));
- createXMLReportCheckbox(xmlReportContainer);
-
- // Create a place for specifying working directory
- Composite workingDirectoryContainer = new Composite(parent, SWT.NONE);
- workingDirectoryContainer.setLayout(new GridLayout(3, false));
- workingDirectoryContainer.setLayoutData(new GridData(GridData.FILL_BOTH));
- createWorkingDirectoryBrowse(workingDirectoryContainer);
-
- // Create a place for specifying translation archive
- Composite translationArchiveContainer = new Composite(parent, SWT.NONE);
- translationArchiveContainer.setLayout(new GridLayout(3, false));
- translationArchiveContainer.setLayoutData(new GridData(GridData.FILL_BOTH));
- createTranslationArchiveLocationBrowse(translationArchiveContainer);
- }
+ private CheckboxTableViewer fCoverageReportResourceFilterViewer;
+ private Label fCoverageReportListLabel;
+ private Button fAddCoverageReportFilterButton;
+ private Button fRemoveCoverageReportFilterButton;
+ private String fChosenCoverageReportFilter;
- private void createLongReportCheckbox(Composite parent) {
- fLongReportGeneration = new Button(parent, SWT.CHECK);
- fLongReportGeneration.setText(Messages.getString("BuildToolWizardConfigurationPage_GenerateLongReportLabel"));
- fLongReportGeneration.setSelection(getDialogSettings().getBoolean(LONG_REPORT));
- }
-
- private void createXMLReportCheckbox(Composite parent) {
- fXMLReportGeneration = new Button(parent, SWT.CHECK);
- fXMLReportGeneration.setText(Messages.getString("BuildToolWizardConfigurationPage_GenerateXMLReportLabel"));
- fXMLReportGeneration.setSelection(getDialogSettings().getBoolean(XML_REPORT));
- }
-
- public boolean getLongReportSelection() {
- return fLongReportGeneration.getSelection();
- }
-
- public boolean getXmlReportSelection() {
- return fXMLReportGeneration.getSelection();
- }
-
- private void createTranslationArchiveLocationBrowse(Composite parent) {
- fTranslationCatalogueLocationLabel = new Label(parent, SWT.NULL);
- fTranslationCatalogueLocationLabel.setText(Messages.getString("BuildToolWizardConfigurationPage_TranslationCatalogueLabel")); //$NON-NLS-1$
- GridData gdLabel = new GridData();
- gdLabel.widthHint = LABEL_WIDTH;
- fTranslationCatalogueLocationLabel.setLayoutData(gdLabel);
-
- fTranslationCatalogueLocationText = new Text(parent, SWT.BORDER | SWT.SINGLE);
- String location = not_null(getDialogSettings().get(TRANSLATION_CATALOG_LOCATION), "");
- fTranslationCatalogueLocationText.setText(location);
- fTranslationCatalogueLocationText.addModifyListener(new TextModifyListener());
- GridData gdText = new GridData(GridData.FILL_HORIZONTAL);
- gdText.widthHint = TEXT_WIDTH;
- fTranslationCatalogueLocationText.setLayoutData(gdText);
-
- fTranslationCatalogueBrowseButton = new Button(parent, SWT.PUSH);
- fTranslationCatalogueBrowseButton.setText(Messages.getString("BuildToolWizardConfigurationPage_TranslationCatalogueBrowseButton")); //$NON-NLS-1$
+ private LanguagePackFilterDialog fLanguagePackFilterDialog;
+ private CoverageReportFilterDialog fCoverageReportFilterDialog;
+ private Button fLongReportGeneration;
+ private Button fXMLReportGeneration;
- Listener listener = new Listener() {
- public void handleEvent(Event event) {
- DirectoryDialog dialog = new DirectoryDialog(getContainer().getShell());
- dialog.setText(Messages.getString("BuildToolWizardConfigurationPage_TranslationCatalogueDialogTitle")); //$NON-NLS-1$
- dialog.setMessage(Messages.getString("BuildToolWizardConfigurationPage_TranslationCatalogueDialogMessage")); //$NON-NLS-1$
- String selectedFileName = dialog.open();
- if (selectedFileName != null) {
- fTranslationCatalogueLocationText.setText(selectedFileName);
- }
- }
- };
+ private static ToT<Object, String> TO_STRING = new ToT<Object, String>() {
+ public String convert(Object from) {
+ return from.toString();
+ }
+ };
- fTranslationCatalogueBrowseButton.addListener(SWT.Selection, listener);
- }
-
- private void createWorkingDirectoryBrowse(Composite parent) {
- fWorkingDirectoryLocationLabel = new Label(parent, SWT.NULL);
- fWorkingDirectoryLocationLabel.setText(Messages.getString("BuildToolWizardConfigurationPage_WorkingDirectoryLabel")); //$NON-NLS-1$
- GridData gdLabel = new GridData();
- gdLabel.widthHint = LABEL_WIDTH;
- fWorkingDirectoryLocationLabel.setLayoutData(gdLabel);
-
- fWorkingDirectoryLocationText = new Text(parent, SWT.BORDER | SWT.SINGLE);
- String location = not_null(getDialogSettings().get(WORKING_DIRECTORY), "");
- fWorkingDirectoryLocationText.setText(location);
- fWorkingDirectoryLocationText.addModifyListener(new TextModifyListener());
- GridData gdText = new GridData(GridData.FILL_HORIZONTAL);
- gdText.widthHint = TEXT_WIDTH;
- fWorkingDirectoryLocationText.setLayoutData(gdText);
-
- fWorkingDirectoryBrowseButton = new Button(parent, SWT.PUSH);
- fWorkingDirectoryBrowseButton.setText(Messages.getString("BuildToolWizardConfigurationPage_WorkingDirectoryBrowseButton")); //$NON-NLS-1$
+ private class TextModifyListener implements ModifyListener {
+ public void modifyText(ModifyEvent e) {
+ textSelectionChanged();
+ }
+ }
- Listener listener = new Listener() {
- public void handleEvent(Event event) {
- DirectoryDialog dialog = new DirectoryDialog(getContainer().getShell());
- dialog.setText(Messages.getString("BuildToolWizardConfigurationPage_WorkingDirectoryDialogTitle")); //$NON-NLS-1$
- dialog.setMessage(Messages.getString("BuildToolWizardConfigurationPage_WorkingDirectoryDialogMessage")); //$NON-NLS-1$
- String selectedFileName = dialog.open();
- if (selectedFileName != null) {
- fWorkingDirectoryLocationText.setText(selectedFileName);
- }
- }
- };
+ protected class IgnoreListContentProvider implements
+ IStructuredContentProvider {
+ public Object[] getElements(Object parent) {
+ return fModelIgnoreTable.getModels();
+ }
- fWorkingDirectoryBrowseButton.addListener(SWT.Selection, listener);
- }
-
- private void createLanguagePackFilteredListArea(Composite parent) {
+ public void dispose() {
+ }
+
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
+ }
+
+ protected class ExcludeListContentProvider implements
+ IStructuredContentProvider {
+ public Object[] getElements(Object parent) {
+ return fModelResourceExclusionTable.getModels();
+ }
+
+ public void dispose() {
+ }
+
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
+ }
+
+ protected BuildToolWizardConfigurationPage(String pageName,
+ BuildToolModelTable modelIgnoreTable,
+ BuildToolModelTable modelExcludeTable) {
+ super(pageName);
+ this.fModelIgnoreTable = modelIgnoreTable;
+ this.fModelResourceExclusionTable = modelExcludeTable;
+
+ this.setTitle(Messages
+ .getString("BuildToolWizardConfigurationPage_PageTitle")); //$NON-NLS-1$
+ this.setDescription(Messages
+ .getString("BuildToolWizardConfigurationPage_PageDescription")); //$NON-NLS-1$
+ }
+
+ public void createControl(Composite parent) {
+ // Create a scrollable container to hold components
+ // This is useful when users are using a lower resolution.
+ ScrolledComposite comp = new ScrolledComposite(parent, SWT.V_SCROLL
+ | SWT.H_SCROLL);
+ Composite container = new Composite(comp, SWT.NONE);
+ container.setLayout(new GridLayout(1, false));
+ container.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ createConfigurationArea(container);
+
+ createLanguagePackFilteredListArea(container);
+
+ createCoverageReportFilteredListArea(container);
+
+ setControl(container);
+ Dialog.applyDialogFont(container);
+ setPageComplete(!"".equals(fWorkingDirectoryLocationText.getText())
+ && !"".equals(fTranslationCatalogueLocationText.getText()));
+
+ // Scrollable container properties
+ comp.setContent(container);
+ comp.setMinHeight(500);
+ comp.setExpandHorizontal(true);
+ comp.setExpandVertical(true);
+ }
+
+ private void createConfigurationArea(Composite parent) {
+ // Create a checkbox allowing for lightweight report generation
+ Composite longReportContainer = new Composite(parent, SWT.NONE);
+ longReportContainer.setLayout(new GridLayout(1, false));
+ longReportContainer.setLayoutData(new GridData(GridData.FILL_BOTH));
+ createLongReportCheckbox(longReportContainer);
+
+ // Create a checkbox allowing for xml report generation
+ Composite xmlReportContainer = new Composite(parent, SWT.NONE);
+ xmlReportContainer.setLayout(new GridLayout(1, false));
+ xmlReportContainer.setLayoutData(new GridData(GridData.FILL_BOTH));
+ createXMLReportCheckbox(xmlReportContainer);
+
+ // Create a place for specifying working directory
+ Composite workingDirectoryContainer = new Composite(parent, SWT.NONE);
+ workingDirectoryContainer.setLayout(new GridLayout(3, false));
+ workingDirectoryContainer
+ .setLayoutData(new GridData(GridData.FILL_BOTH));
+ createWorkingDirectoryBrowse(workingDirectoryContainer);
+
+ // Create a place for specifying translation archive
+ Composite translationArchiveContainer = new Composite(parent, SWT.NONE);
+ translationArchiveContainer.setLayout(new GridLayout(3, false));
+ translationArchiveContainer.setLayoutData(new GridData(
+ GridData.FILL_BOTH));
+ createTranslationArchiveLocationBrowse(translationArchiveContainer);
+ }
+
+ private void createLongReportCheckbox(Composite parent) {
+ fLongReportGeneration = new Button(parent, SWT.CHECK);
+ fLongReportGeneration
+ .setText(Messages
+ .getString("BuildToolWizardConfigurationPage_GenerateLongReportLabel"));
+ fLongReportGeneration.setSelection(getDialogSettings().getBoolean(
+ LONG_REPORT));
+ }
+
+ private void createXMLReportCheckbox(Composite parent) {
+ fXMLReportGeneration = new Button(parent, SWT.CHECK);
+ fXMLReportGeneration
+ .setText(Messages
+ .getString("BuildToolWizardConfigurationPage_GenerateXMLReportLabel"));
+ fXMLReportGeneration.setSelection(getDialogSettings().getBoolean(
+ XML_REPORT));
+ }
+
+ public boolean getLongReportSelection() {
+ return fLongReportGeneration.getSelection();
+ }
+
+ public boolean getXmlReportSelection() {
+ return fXMLReportGeneration.getSelection();
+ }
+
+ private void createTranslationArchiveLocationBrowse(Composite parent) {
+ fTranslationCatalogueLocationLabel = new Label(parent, SWT.NULL);
+ fTranslationCatalogueLocationLabel
+ .setText(Messages
+ .getString("BuildToolWizardConfigurationPage_TranslationCatalogueLabel")); //$NON-NLS-1$
+ GridData gdLabel = new GridData();
+ gdLabel.widthHint = LABEL_WIDTH;
+ fTranslationCatalogueLocationLabel.setLayoutData(gdLabel);
+
+ fTranslationCatalogueLocationText = new Text(parent, SWT.BORDER
+ | SWT.SINGLE);
+ String location = not_null(
+ getDialogSettings().get(TRANSLATION_CATALOG_LOCATION), "");
+ fTranslationCatalogueLocationText.setText(location);
+ fTranslationCatalogueLocationText
+ .addModifyListener(new TextModifyListener());
+ GridData gdText = new GridData(GridData.FILL_HORIZONTAL);
+ gdText.widthHint = TEXT_WIDTH;
+ fTranslationCatalogueLocationText.setLayoutData(gdText);
+
+ fTranslationCatalogueBrowseButton = new Button(parent, SWT.PUSH);
+ fTranslationCatalogueBrowseButton
+ .setText(Messages
+ .getString("BuildToolWizardConfigurationPage_TranslationCatalogueBrowseButton")); //$NON-NLS-1$
+
+ Listener listener = new Listener() {
+ public void handleEvent(Event event) {
+ DirectoryDialog dialog = new DirectoryDialog(getContainer()
+ .getShell());
+ dialog.setText(Messages
+ .getString("BuildToolWizardConfigurationPage_TranslationCatalogueDialogTitle")); //$NON-NLS-1$
+ dialog.setMessage(Messages
+ .getString("BuildToolWizardConfigurationPage_TranslationCatalogueDialogMessage")); //$NON-NLS-1$
+ String selectedFileName = dialog.open();
+ if (selectedFileName != null) {
+ fTranslationCatalogueLocationText.setText(selectedFileName);
+ }
+ }
+ };
+
+ fTranslationCatalogueBrowseButton.addListener(SWT.Selection, listener);
+ }
+
+ private void createWorkingDirectoryBrowse(Composite parent) {
+ fWorkingDirectoryLocationLabel = new Label(parent, SWT.NULL);
+ fWorkingDirectoryLocationLabel
+ .setText(Messages
+ .getString("BuildToolWizardConfigurationPage_WorkingDirectoryLabel")); //$NON-NLS-1$
+ GridData gdLabel = new GridData();
+ gdLabel.widthHint = LABEL_WIDTH;
+ fWorkingDirectoryLocationLabel.setLayoutData(gdLabel);
+
+ fWorkingDirectoryLocationText = new Text(parent, SWT.BORDER
+ | SWT.SINGLE);
+ String location = not_null(getDialogSettings().get(WORKING_DIRECTORY),
+ "");
+ fWorkingDirectoryLocationText.setText(location);
+ fWorkingDirectoryLocationText
+ .addModifyListener(new TextModifyListener());
+ GridData gdText = new GridData(GridData.FILL_HORIZONTAL);
+ gdText.widthHint = TEXT_WIDTH;
+ fWorkingDirectoryLocationText.setLayoutData(gdText);
+
+ fWorkingDirectoryBrowseButton = new Button(parent, SWT.PUSH);
+ fWorkingDirectoryBrowseButton
+ .setText(Messages
+ .getString("BuildToolWizardConfigurationPage_WorkingDirectoryBrowseButton")); //$NON-NLS-1$
+
+ Listener listener = new Listener() {
+ public void handleEvent(Event event) {
+ DirectoryDialog dialog = new DirectoryDialog(getContainer()
+ .getShell());
+ dialog.setText(Messages
+ .getString("BuildToolWizardConfigurationPage_WorkingDirectoryDialogTitle")); //$NON-NLS-1$
+ dialog.setMessage(Messages
+ .getString("BuildToolWizardConfigurationPage_WorkingDirectoryDialogMessage")); //$NON-NLS-1$
+ String selectedFileName = dialog.open();
+ if (selectedFileName != null) {
+ fWorkingDirectoryLocationText.setText(selectedFileName);
+ }
+ }
+ };
+
+ fWorkingDirectoryBrowseButton.addListener(SWT.Selection, listener);
+ }
+
+ private void createLanguagePackFilteredListArea(Composite parent) {
fLanguagePackListLabel = new Label(parent, SWT.NONE);
- fLanguagePackListLabel.setText(Messages.getString("BuildToolWizardConfigurationPage_IgnoreListLabel")); //$NON-NLS-1$
+ fLanguagePackListLabel.setText(Messages
+ .getString("BuildToolWizardConfigurationPage_IgnoreListLabel")); //$NON-NLS-1$
GridData gdLabel = new GridData(GridData.FILL_HORIZONTAL);
- gdLabel.widthHint = LABEL_WIDTH;
- gdLabel.horizontalIndent = LIST_LABEL_INDENT;
- gdLabel.verticalIndent = LIST_SEPARATOR;
- fLanguagePackListLabel.setLayoutData(gdLabel);
-
- Composite listComposite = new Composite(parent, SWT.NONE);
- listComposite.setLayout(new GridLayout(2, false));
- listComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- Table table = new Table(listComposite, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
+ gdLabel.widthHint = LABEL_WIDTH;
+ gdLabel.horizontalIndent = LIST_LABEL_INDENT;
+ gdLabel.verticalIndent = LIST_SEPARATOR;
+ fLanguagePackListLabel.setLayoutData(gdLabel);
+
+ Composite listComposite = new Composite(parent, SWT.NONE);
+ listComposite.setLayout(new GridLayout(2, false));
+ listComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ Table table = new Table(listComposite, SWT.CHECK | SWT.BORDER
+ | SWT.V_SCROLL | SWT.H_SCROLL);
table.setLayout(new TableLayout());
GridData data = new GridData(GridData.FILL_BOTH);
data.heightHint = VIEWER_HEIGHT;
data.widthHint = VIEWER_WIDTH;
table.setLayoutData(data);
-
+
fLanguagePackResourceIgnoreViewer = new CheckboxTableViewer(table);
fLanguagePackResourceIgnoreViewer.setLabelProvider(new LabelProvider());
- fLanguagePackResourceIgnoreViewer.setContentProvider(new IgnoreListContentProvider());
- fLanguagePackResourceIgnoreViewer.setInput(fModelIgnoreTable.getModels());
+ fLanguagePackResourceIgnoreViewer
+ .setContentProvider(new IgnoreListContentProvider());
+ fLanguagePackResourceIgnoreViewer.setInput(fModelIgnoreTable
+ .getModels());
fLanguagePackResourceIgnoreViewer.setComparator(new ViewerComparator());
- fLanguagePackResourceIgnoreViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- // Enable button only if there's a selection
- if (event.getSelection().isEmpty()) {
- fRemoveLanguagePackFilterButton.setEnabled(false);
- } else {
- fRemoveLanguagePackFilterButton.setEnabled(true);
- }
- }
- });
-
+ fLanguagePackResourceIgnoreViewer
+ .addSelectionChangedListener(new ISelectionChangedListener() {
+ public void selectionChanged(SelectionChangedEvent event) {
+ // Enable button only if there's a selection
+ if (event.getSelection().isEmpty()) {
+ fRemoveLanguagePackFilterButton.setEnabled(false);
+ } else {
+ fRemoveLanguagePackFilterButton.setEnabled(true);
+ }
+ }
+ });
+
// By default, all pre-defined patterns are checked
fLanguagePackResourceIgnoreViewer.setAllChecked(true);
-
+
createLanguagePackFilteredListControlButtonsArea(listComposite);
- }
-
- private void createLanguagePackFilteredListControlButtonsArea(Composite parent) {
- Composite buttonComposite = new Composite(parent, SWT.NONE);
+ }
+
+ private void createLanguagePackFilteredListControlButtonsArea(
+ Composite parent) {
+ Composite buttonComposite = new Composite(parent, SWT.NONE);
buttonComposite.setLayout(new GridLayout(1, false));
GridData gData = new GridData();
buttonComposite.setLayoutData(gData);
-
- GridData gdText = new GridData();
- gdText.widthHint = BUTTON_WIDTH;
-
- // Add Pattern Button
+
+ GridData gdText = new GridData();
+ gdText.widthHint = BUTTON_WIDTH;
+
+ // Add Pattern Button
fAddLanguagePackFilterButton = new Button(buttonComposite, SWT.PUSH);
- fAddLanguagePackFilterButton.setText(Messages.getString("BuildToolWizardConfigurationPage_AddLanguagePackFilterButton"));
+ fAddLanguagePackFilterButton
+ .setText(Messages
+ .getString("BuildToolWizardConfigurationPage_AddLanguagePackFilterButton"));
fAddLanguagePackFilterButton.setLayoutData(gdText);
- fAddLanguagePackFilterButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- openLanguagePackFilterDialog();
- }
- });
-
+ fAddLanguagePackFilterButton
+ .addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ openLanguagePackFilterDialog();
+ }
+ });
+
// Remove Pattern Button
fRemoveLanguagePackFilterButton = new Button(buttonComposite, SWT.PUSH);
- fRemoveLanguagePackFilterButton.setText(Messages.getString("BuildToolWizardConfigurationPage_RemoveLanguagePackFilterButton"));
+ fRemoveLanguagePackFilterButton
+ .setText(Messages
+ .getString("BuildToolWizardConfigurationPage_RemoveLanguagePackFilterButton"));
fRemoveLanguagePackFilterButton.setLayoutData(gdText);
- fRemoveLanguagePackFilterButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- removeSelectedLanguagePackFilter();
- }
- });
+ fRemoveLanguagePackFilterButton
+ .addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ removeSelectedLanguagePackFilter();
+ }
+ });
fRemoveLanguagePackFilterButton.setEnabled(false);
-
- Button selectAll = new Button(buttonComposite, SWT.PUSH);
- selectAll.setText(Messages.getString("BuildToolWizardConfigurationPage_SelectAllLanguagePackFiltersButton"));
- selectAll.setLayoutData(gdText);
- selectAll.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- fLanguagePackResourceIgnoreViewer.setAllChecked(true);
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
-
- Button deselectAll = new Button(buttonComposite, SWT.PUSH);
- deselectAll.setText(Messages.getString("BuildToolWizardConfigurationPage_DeselectAllLanguagePackFiltersButton"));
- deselectAll.setLayoutData(gdText);
- deselectAll.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- fLanguagePackResourceIgnoreViewer.setAllChecked(false);
- }
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
-
- IDialogSettings settings = getDialogSettings();
- for(String filter : not_null(settings.getArray(IGNORE_LIST), new String[]{})){
- addLanguagePackFilter(filter, false);
- }
-
- for(String checked : not_null(settings.getArray(IGNORE_LIST_CHECKED), new String[]{})){
- addLanguagePackFilter(checked, true);
- }
- }
-
- private void createCoverageReportFilteredListArea(Composite parent) {
- fCoverageReportListLabel = new Label(parent, SWT.NONE);
- fCoverageReportListLabel.setText(Messages.getString("BuildToolWizardConfigurationPage_FilterListLabel")); //$NON-NLS-1$
+ Button selectAll = new Button(buttonComposite, SWT.PUSH);
+ selectAll
+ .setText(Messages
+ .getString("BuildToolWizardConfigurationPage_SelectAllLanguagePackFiltersButton"));
+ selectAll.setLayoutData(gdText);
+ selectAll.addSelectionListener(new SelectionListener() {
+ public void widgetSelected(SelectionEvent e) {
+ fLanguagePackResourceIgnoreViewer.setAllChecked(true);
+ }
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ });
+
+ Button deselectAll = new Button(buttonComposite, SWT.PUSH);
+ deselectAll
+ .setText(Messages
+ .getString("BuildToolWizardConfigurationPage_DeselectAllLanguagePackFiltersButton"));
+ deselectAll.setLayoutData(gdText);
+ deselectAll.addSelectionListener(new SelectionListener() {
+ public void widgetSelected(SelectionEvent e) {
+ fLanguagePackResourceIgnoreViewer.setAllChecked(false);
+ }
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ });
+
+ IDialogSettings settings = getDialogSettings();
+ for (String filter : not_null(settings.getArray(IGNORE_LIST),
+ new String[] {})) {
+ addLanguagePackFilter(filter, false);
+ }
+
+ for (String checked : not_null(settings.getArray(IGNORE_LIST_CHECKED),
+ new String[] {})) {
+ addLanguagePackFilter(checked, true);
+ }
+ }
+
+ private void createCoverageReportFilteredListArea(Composite parent) {
+ fCoverageReportListLabel = new Label(parent, SWT.NONE);
+ fCoverageReportListLabel.setText(Messages
+ .getString("BuildToolWizardConfigurationPage_FilterListLabel")); //$NON-NLS-1$
GridData gdLabel = new GridData(GridData.FILL_HORIZONTAL);
- gdLabel.widthHint = LABEL_WIDTH;
- gdLabel.horizontalIndent = LIST_LABEL_INDENT;
- gdLabel.verticalIndent = LIST_SEPARATOR;
- fCoverageReportListLabel.setLayoutData(gdLabel);
-
- Composite listComposite = new Composite(parent, SWT.NONE);
- listComposite.setLayout(new GridLayout(2, false));
- listComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- Table table = new Table(listComposite, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
+ gdLabel.widthHint = LABEL_WIDTH;
+ gdLabel.horizontalIndent = LIST_LABEL_INDENT;
+ gdLabel.verticalIndent = LIST_SEPARATOR;
+ fCoverageReportListLabel.setLayoutData(gdLabel);
+
+ Composite listComposite = new Composite(parent, SWT.NONE);
+ listComposite.setLayout(new GridLayout(2, false));
+ listComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ Table table = new Table(listComposite, SWT.CHECK | SWT.BORDER
+ | SWT.V_SCROLL | SWT.H_SCROLL);
table.setLayout(new TableLayout());
GridData data = new GridData(GridData.FILL_BOTH);
data.heightHint = VIEWER_HEIGHT;
data.widthHint = VIEWER_WIDTH;
table.setLayoutData(data);
-
+
fCoverageReportResourceFilterViewer = new CheckboxTableViewer(table);
- fCoverageReportResourceFilterViewer.setLabelProvider(new LabelProvider());
- fCoverageReportResourceFilterViewer.setContentProvider(new ExcludeListContentProvider());
- fCoverageReportResourceFilterViewer.setInput(fModelResourceExclusionTable.getModels());
- fCoverageReportResourceFilterViewer.setComparator(new ViewerComparator());
- fCoverageReportResourceFilterViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- // Enable button only if there's a selection
- if (event.getSelection().isEmpty()) {
- fRemoveCoverageReportFilterButton.setEnabled(false);
- } else {
- fRemoveCoverageReportFilterButton.setEnabled(true);
- }
- }
- });
-
+ fCoverageReportResourceFilterViewer
+ .setLabelProvider(new LabelProvider());
+ fCoverageReportResourceFilterViewer
+ .setContentProvider(new ExcludeListContentProvider());
+ fCoverageReportResourceFilterViewer
+ .setInput(fModelResourceExclusionTable.getModels());
+ fCoverageReportResourceFilterViewer
+ .setComparator(new ViewerComparator());
+ fCoverageReportResourceFilterViewer
+ .addSelectionChangedListener(new ISelectionChangedListener() {
+ public void selectionChanged(SelectionChangedEvent event) {
+ // Enable button only if there's a selection
+ if (event.getSelection().isEmpty()) {
+ fRemoveCoverageReportFilterButton.setEnabled(false);
+ } else {
+ fRemoveCoverageReportFilterButton.setEnabled(true);
+ }
+ }
+ });
+
// By default, all pre-defined filters are checked
fCoverageReportResourceFilterViewer.setAllChecked(true);
-
- // Create an area with buttons for adding/removing resource patterns, and for selecting/deselecting all
+
+ // Create an area with buttons for adding/removing resource patterns,
+ // and for selecting/deselecting all
createExcludeListControlButtonArea(listComposite);
-
- IDialogSettings settings = getDialogSettings();
- for(String filter : not_null(settings.getArray(EXCLUDE_LIST), new String[]{})){
- addCoverageReportFilter(filter, false);
- }
-
- for(String checked : not_null(settings.getArray(EXCLUDE_LIST_CHECKED), new String[]{})){
- addCoverageReportFilter(checked, true);
- }
- }
-
- private void createExcludeListControlButtonArea(Composite parent) {
- Composite buttonComposite = new Composite(parent, SWT.NONE);
+
+ IDialogSettings settings = getDialogSettings();
+ for (String filter : not_null(settings.getArray(EXCLUDE_LIST),
+ new String[] {})) {
+ addCoverageReportFilter(filter, false);
+ }
+
+ for (String checked : not_null(settings.getArray(EXCLUDE_LIST_CHECKED),
+ new String[] {})) {
+ addCoverageReportFilter(checked, true);
+ }
+ }
+
+ private void createExcludeListControlButtonArea(Composite parent) {
+ Composite buttonComposite = new Composite(parent, SWT.NONE);
buttonComposite.setLayout(new GridLayout(1, false));
GridData gData = new GridData();
buttonComposite.setLayoutData(gData);
-
- GridData gdText = new GridData();
- gdText.widthHint = BUTTON_WIDTH;
-
- // Add Pattern Button
- fAddCoverageReportFilterButton = new Button(buttonComposite, SWT.PUSH);
- fAddCoverageReportFilterButton.setText(Messages.getString("BuildToolWizardConfigurationPage_AddCoverageReportFilterButton"));
- fAddCoverageReportFilterButton.setLayoutData(gdText);
- fAddCoverageReportFilterButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- openCoverageReportFilterDialog();
- }
- });
-
- // Remove Pattern Button
- fRemoveCoverageReportFilterButton = new Button(buttonComposite, SWT.PUSH);
- fRemoveCoverageReportFilterButton.setText(Messages.getString("BuildToolWizardConfigurationPage_RemoveCoverageReportFilterButton"));
- fRemoveCoverageReportFilterButton.setLayoutData(gdText);
- fRemoveCoverageReportFilterButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- removeSelectedCoverageReportFilter();
- }
- });
- fRemoveCoverageReportFilterButton.setEnabled(false);
-
- Button selectAll = new Button(buttonComposite, SWT.PUSH);
- selectAll.setText(Messages.getString("BuildToolWizardConfigurationPage_SelectAllCoverageReportFiltersButton"));
- selectAll.setLayoutData(gdText);
- selectAll.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- fCoverageReportResourceFilterViewer.setAllChecked(true);
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
-
- Button deselectAll = new Button(buttonComposite, SWT.PUSH);
- deselectAll.setText(Messages.getString("BuildToolWizardConfigurationPage_DeselectAllCoverageReportFiltersButton"));
- deselectAll.setLayoutData(gdText);
- deselectAll.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- fCoverageReportResourceFilterViewer.setAllChecked(false);
- }
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
- }
-
- public void setCoverageReportFilter(String filter) {
- this.fChosenCoverageReportFilter = filter;
- }
-
- public void setLanguagePackFilter(String filter) {
- this.fChosenLanguagePackFilter = filter;
- }
-
- private void openLanguagePackFilterDialog() {
- Shell shell = new Shell(this.getShell(), SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM);
-
- fLanguagePackFilterDialog = new LanguagePackFilterDialog(shell, this);
- fLanguagePackFilterDialog.getParent().open();
- fLanguagePackFilterDialog.getParent().addDisposeListener(new DisposeListener() {
- public void widgetDisposed(DisposeEvent e) {
- // If a pattern was provided through the dialog, handle.
- if ((fChosenLanguagePackFilter != null) && (fChosenLanguagePackFilter.trim().compareTo("") != 0)) {
- addLanguagePackFilter(fChosenLanguagePackFilter);
- }
- fChosenLanguagePackFilter = null;
- }
- });
- }
-
- private void addCoverageReportFilter(String o){
- addCoverageReportFilter(o, true);
- }
-
- private void addCoverageReportFilter(String o, boolean checked) {
- boolean doesItemExist = false;
-
- // Check if extension is already in the ignore list
- for (TableItem item: fCoverageReportResourceFilterViewer.getTable().getItems()) {
- if (item.getText().compareToIgnoreCase(o) == 0) {
- doesItemExist = true;
- }
- }
-
- // Only add an item if its name does not conflict with an item
- // that is already in the list.
- if (!doesItemExist) {
- fModelResourceExclusionTable.addModel(o);
- fCoverageReportResourceFilterViewer.add(o);
- fCoverageReportResourceFilterViewer.refresh();
- }
- // Ensure new item is checked
- fCoverageReportResourceFilterViewer.setChecked(o, checked);
- }
-
- private void addLanguagePackFilter(String o){
- addLanguagePackFilter(o, true);
- }
-
- private void addLanguagePackFilter(String o, boolean checked) {
- boolean doesItemExist = false;
-
- // Check if extension is already in the ignore list
- for (TableItem item: fLanguagePackResourceIgnoreViewer.getTable().getItems()) {
- if (item.getText().compareToIgnoreCase(o) == 0) {
- doesItemExist = true;
- }
- }
-
- // Only add an item if its name does not conflict with an item
- // that is already in the list.
- if (!doesItemExist) {
- fModelIgnoreTable.addModel(o);
- fLanguagePackResourceIgnoreViewer.add(o);
- fLanguagePackResourceIgnoreViewer.refresh();
- }
- fLanguagePackResourceIgnoreViewer.setChecked(o, checked);
- }
-
- private void removeSelectedLanguagePackFilter() {
- int selectionIndex = fLanguagePackResourceIgnoreViewer.getTable().getSelectionIndex();
- if (selectionIndex != -1) {
- Object o = fLanguagePackResourceIgnoreViewer.getElementAt(selectionIndex);
-
- fModelIgnoreTable.removeModel(o);
- fLanguagePackResourceIgnoreViewer.remove(o);
-
- fLanguagePackResourceIgnoreViewer.refresh();
- }
- }
-
- private void removeSelectedCoverageReportFilter() {
- int selectionIndex = fCoverageReportResourceFilterViewer.getTable().getSelectionIndex();
- if (selectionIndex != -1) {
- Object o = fCoverageReportResourceFilterViewer.getElementAt(selectionIndex);
-
- fModelResourceExclusionTable.removeModel(o);
- fCoverageReportResourceFilterViewer.remove(o);
-
- fCoverageReportResourceFilterViewer.refresh();
- }
- }
-
- private void openCoverageReportFilterDialog() {
- Shell shell = new Shell(this.getShell(), SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM);
-
- // Start up custom AddPatternDialog which requests a custom pattern
- fCoverageReportFilterDialog = new CoverageReportFilterDialog(shell, this);
- fCoverageReportFilterDialog.getParent().open();
- fCoverageReportFilterDialog.getParent().addDisposeListener(new DisposeListener() {
- public void widgetDisposed(DisposeEvent e) {
- // If a pattern was provided through the custom dialog, handle.
- if ((fChosenCoverageReportFilter != null) && (fChosenCoverageReportFilter.trim().compareTo("") != 0)) {
- addCoverageReportFilter(fChosenCoverageReportFilter);
- }
- fChosenCoverageReportFilter = null;
- }
- });
- }
-
- private void textSelectionChanged() {
- setPageComplete((fWorkingDirectoryLocationText.getText().length() > 0)
- && (fTranslationCatalogueLocationText.getText().length() > 0));
- }
-
- public String getWorkingDirectoryLocation() {
- return fWorkingDirectoryLocationText.getText();
- }
-
- public String getTranslationCatalogueLocation() {
- return fTranslationCatalogueLocationText.getText();
- }
-
- public Object[] getIgnoreList() {
- return fLanguagePackResourceIgnoreViewer.getCheckedElements();
- }
-
- public Object[] getReportFilterPatterns() {
- return fCoverageReportResourceFilterViewer.getCheckedElements();
- }
-
- public boolean isCurrentPage() {
- return super.isCurrentPage();
- }
-
- public boolean canFlipToNextPage() {
- return false;
- }
-
- private String[] getAllElements(CheckboxTableViewer viewer){
- List<String> elements = new LinkedList<String>();
- Object o;
- int i = 0;
- while((o = viewer.getElementAt(i++)) != null){
- elements.add(o.toString());
- }
-
- return elements.toArray(STRING);
- }
-
- private static interface ToT<F,T>{
- public T convert(F from);
- }
-
- private <F,T> T[] convert(T[] array, ToT<F,T> toT, F... fs){
- List<T> ts = new LinkedList<T>();
-
- for(F f : fs){
- ts.add(toT.convert(f));
- }
-
- return ts.toArray(array);
- }
-
- @Override
- public void storeSettings() {
- IDialogSettings settings = getDialogSettings();
- settings.put(XML_REPORT, fXMLReportGeneration.getSelection());
- settings.put(LONG_REPORT, fLongReportGeneration.getSelection());
- settings.put(TRANSLATION_CATALOG_LOCATION, fTranslationCatalogueLocationText.getText());
- settings.put(WORKING_DIRECTORY, fWorkingDirectoryLocationText.getText());
- settings.put(IGNORE_LIST, getAllElements(fLanguagePackResourceIgnoreViewer));
- settings.put(IGNORE_LIST_CHECKED, convert(STRING, TO_STRING, fLanguagePackResourceIgnoreViewer.getCheckedElements()));
-
- settings.put(EXCLUDE_LIST, getAllElements(fCoverageReportResourceFilterViewer));
- settings.put(EXCLUDE_LIST_CHECKED, convert(STRING, TO_STRING, fCoverageReportResourceFilterViewer.getCheckedElements()));
- }
+ GridData gdText = new GridData();
+ gdText.widthHint = BUTTON_WIDTH;
+
+ // Add Pattern Button
+ fAddCoverageReportFilterButton = new Button(buttonComposite, SWT.PUSH);
+ fAddCoverageReportFilterButton
+ .setText(Messages
+ .getString("BuildToolWizardConfigurationPage_AddCoverageReportFilterButton"));
+ fAddCoverageReportFilterButton.setLayoutData(gdText);
+ fAddCoverageReportFilterButton
+ .addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ openCoverageReportFilterDialog();
+ }
+ });
+
+ // Remove Pattern Button
+ fRemoveCoverageReportFilterButton = new Button(buttonComposite,
+ SWT.PUSH);
+ fRemoveCoverageReportFilterButton
+ .setText(Messages
+ .getString("BuildToolWizardConfigurationPage_RemoveCoverageReportFilterButton"));
+ fRemoveCoverageReportFilterButton.setLayoutData(gdText);
+ fRemoveCoverageReportFilterButton
+ .addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ removeSelectedCoverageReportFilter();
+ }
+ });
+ fRemoveCoverageReportFilterButton.setEnabled(false);
+
+ Button selectAll = new Button(buttonComposite, SWT.PUSH);
+ selectAll
+ .setText(Messages
+ .getString("BuildToolWizardConfigurationPage_SelectAllCoverageReportFiltersButton"));
+ selectAll.setLayoutData(gdText);
+ selectAll.addSelectionListener(new SelectionListener() {
+ public void widgetSelected(SelectionEvent e) {
+ fCoverageReportResourceFilterViewer.setAllChecked(true);
+ }
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ });
+
+ Button deselectAll = new Button(buttonComposite, SWT.PUSH);
+ deselectAll
+ .setText(Messages
+ .getString("BuildToolWizardConfigurationPage_DeselectAllCoverageReportFiltersButton"));
+ deselectAll.setLayoutData(gdText);
+ deselectAll.addSelectionListener(new SelectionListener() {
+ public void widgetSelected(SelectionEvent e) {
+ fCoverageReportResourceFilterViewer.setAllChecked(false);
+ }
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ });
+ }
+
+ public void setCoverageReportFilter(String filter) {
+ this.fChosenCoverageReportFilter = filter;
+ }
+
+ public void setLanguagePackFilter(String filter) {
+ this.fChosenLanguagePackFilter = filter;
+ }
+
+ private void openLanguagePackFilterDialog() {
+ Shell shell = new Shell(this.getShell(), SWT.APPLICATION_MODAL
+ | SWT.DIALOG_TRIM);
+
+ fLanguagePackFilterDialog = new LanguagePackFilterDialog(shell, this);
+ fLanguagePackFilterDialog.getParent().open();
+ fLanguagePackFilterDialog.getParent().addDisposeListener(
+ new DisposeListener() {
+ public void widgetDisposed(DisposeEvent e) {
+ // If a pattern was provided through the dialog, handle.
+ if ((fChosenLanguagePackFilter != null)
+ && (fChosenLanguagePackFilter.trim().compareTo(
+ "") != 0)) {
+ addLanguagePackFilter(fChosenLanguagePackFilter);
+ }
+ fChosenLanguagePackFilter = null;
+ }
+ });
+ }
+
+ private void addCoverageReportFilter(String o) {
+ addCoverageReportFilter(o, true);
+ }
+
+ private void addCoverageReportFilter(String o, boolean checked) {
+ boolean doesItemExist = false;
+
+ // Check if extension is already in the ignore list
+ for (TableItem item : fCoverageReportResourceFilterViewer.getTable()
+ .getItems()) {
+ if (item.getText().compareToIgnoreCase(o) == 0) {
+ doesItemExist = true;
+ }
+ }
+
+ // Only add an item if its name does not conflict with an item
+ // that is already in the list.
+ if (!doesItemExist) {
+ fModelResourceExclusionTable.addModel(o);
+ fCoverageReportResourceFilterViewer.add(o);
+ fCoverageReportResourceFilterViewer.refresh();
+ }
+ // Ensure new item is checked
+ fCoverageReportResourceFilterViewer.setChecked(o, checked);
+ }
+
+ private void addLanguagePackFilter(String o) {
+ addLanguagePackFilter(o, true);
+ }
+
+ private void addLanguagePackFilter(String o, boolean checked) {
+ boolean doesItemExist = false;
+
+ // Check if extension is already in the ignore list
+ for (TableItem item : fLanguagePackResourceIgnoreViewer.getTable()
+ .getItems()) {
+ if (item.getText().compareToIgnoreCase(o) == 0) {
+ doesItemExist = true;
+ }
+ }
+
+ // Only add an item if its name does not conflict with an item
+ // that is already in the list.
+ if (!doesItemExist) {
+ fModelIgnoreTable.addModel(o);
+ fLanguagePackResourceIgnoreViewer.add(o);
+ fLanguagePackResourceIgnoreViewer.refresh();
+ }
+ fLanguagePackResourceIgnoreViewer.setChecked(o, checked);
+ }
+
+ private void removeSelectedLanguagePackFilter() {
+ int selectionIndex = fLanguagePackResourceIgnoreViewer.getTable()
+ .getSelectionIndex();
+ if (selectionIndex != -1) {
+ Object o = fLanguagePackResourceIgnoreViewer
+ .getElementAt(selectionIndex);
+
+ fModelIgnoreTable.removeModel(o);
+ fLanguagePackResourceIgnoreViewer.remove(o);
+
+ fLanguagePackResourceIgnoreViewer.refresh();
+ }
+ }
+
+ private void removeSelectedCoverageReportFilter() {
+ int selectionIndex = fCoverageReportResourceFilterViewer.getTable()
+ .getSelectionIndex();
+ if (selectionIndex != -1) {
+ Object o = fCoverageReportResourceFilterViewer
+ .getElementAt(selectionIndex);
+
+ fModelResourceExclusionTable.removeModel(o);
+ fCoverageReportResourceFilterViewer.remove(o);
+
+ fCoverageReportResourceFilterViewer.refresh();
+ }
+ }
+
+ private void openCoverageReportFilterDialog() {
+ Shell shell = new Shell(this.getShell(), SWT.APPLICATION_MODAL
+ | SWT.DIALOG_TRIM);
+
+ // Start up custom AddPatternDialog which requests a custom pattern
+ fCoverageReportFilterDialog = new CoverageReportFilterDialog(shell,
+ this);
+ fCoverageReportFilterDialog.getParent().open();
+ fCoverageReportFilterDialog.getParent().addDisposeListener(
+ new DisposeListener() {
+ public void widgetDisposed(DisposeEvent e) {
+ // If a pattern was provided through the custom dialog,
+ // handle.
+ if ((fChosenCoverageReportFilter != null)
+ && (fChosenCoverageReportFilter.trim()
+ .compareTo("") != 0)) {
+ addCoverageReportFilter(fChosenCoverageReportFilter);
+ }
+ fChosenCoverageReportFilter = null;
+ }
+ });
+ }
+
+ private void textSelectionChanged() {
+ setPageComplete((fWorkingDirectoryLocationText.getText().length() > 0)
+ && (fTranslationCatalogueLocationText.getText().length() > 0));
+ }
+
+ public String getWorkingDirectoryLocation() {
+ return fWorkingDirectoryLocationText.getText();
+ }
+
+ public String getTranslationCatalogueLocation() {
+ return fTranslationCatalogueLocationText.getText();
+ }
+
+ public Object[] getIgnoreList() {
+ return fLanguagePackResourceIgnoreViewer.getCheckedElements();
+ }
+
+ public Object[] getReportFilterPatterns() {
+ return fCoverageReportResourceFilterViewer.getCheckedElements();
+ }
+
+ public boolean isCurrentPage() {
+ return super.isCurrentPage();
+ }
+
+ public boolean canFlipToNextPage() {
+ return false;
+ }
+
+ private String[] getAllElements(CheckboxTableViewer viewer) {
+ List<String> elements = new LinkedList<String>();
+ Object o;
+ int i = 0;
+ while ((o = viewer.getElementAt(i++)) != null) {
+ elements.add(o.toString());
+ }
+
+ return elements.toArray(STRING);
+ }
+
+ private static interface ToT<F, T> {
+ public T convert(F from);
+ }
+
+ private <F, T> T[] convert(T[] array, ToT<F, T> toT, F... fs) {
+ List<T> ts = new LinkedList<T>();
+
+ for (F f : fs) {
+ ts.add(toT.convert(f));
+ }
+
+ return ts.toArray(array);
+ }
+
+ @Override
+ public void storeSettings() {
+ IDialogSettings settings = getDialogSettings();
+ settings.put(XML_REPORT, fXMLReportGeneration.getSelection());
+ settings.put(LONG_REPORT, fLongReportGeneration.getSelection());
+ settings.put(TRANSLATION_CATALOG_LOCATION,
+ fTranslationCatalogueLocationText.getText());
+ settings.put(WORKING_DIRECTORY, fWorkingDirectoryLocationText.getText());
+ settings.put(IGNORE_LIST,
+ getAllElements(fLanguagePackResourceIgnoreViewer));
+ settings.put(
+ IGNORE_LIST_CHECKED,
+ convert(STRING, TO_STRING,
+ fLanguagePackResourceIgnoreViewer.getCheckedElements()));
+
+ settings.put(EXCLUDE_LIST,
+ getAllElements(fCoverageReportResourceFilterViewer));
+ settings.put(
+ EXCLUDE_LIST_CHECKED,
+ convert(STRING, TO_STRING, fCoverageReportResourceFilterViewer
+ .getCheckedElements()));
+ }
}
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizardLocalePage.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizardLocalePage.java
index caa9105..84d0183 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizardLocalePage.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizardLocalePage.java
@@ -26,227 +26,240 @@
public class BuildToolWizardLocalePage extends BuildToolWizardPage {
- private final static String FILTER_PATTERN = "BuildToolWizardLocalePage#fLocaleFilter";
- private final static String SELECTED_LOCALES = "BuildToolWizardLocalePage#Locales";
- private final static String ALL_LOCALES = "BuildToolWizardLocalePage#fAllLocalesCheckbox";
- private final static String BY_GROUP = "BuildToolWizardLocalePage#fLocaleGroupCheckbox";
- private final static String SELECTED_GROUP = "BuildToolWizardLocalePage#fLocaleGroupCombo";
-
- private BuildToolModelTable fModelLocalesTable;
-
- private Button fAllLocalesCheckbox;
- private Button fLocaleGroupCheckbox;
- private Label fLocaleGroupLabel;
- private Combo fLocaleGroupCombo;
-
- private FilteredListComponent fLocaleFilter;
-
- private class GroupCheckboxSelectionListener implements SelectionListener {
- public void widgetSelected(SelectionEvent e){
- groupCheckboxSelectionChanged();
- }
+ private final static String FILTER_PATTERN = "BuildToolWizardLocalePage#fLocaleFilter";
+ private final static String SELECTED_LOCALES = "BuildToolWizardLocalePage#Locales";
+ private final static String ALL_LOCALES = "BuildToolWizardLocalePage#fAllLocalesCheckbox";
+ private final static String BY_GROUP = "BuildToolWizardLocalePage#fLocaleGroupCheckbox";
+ private final static String SELECTED_GROUP = "BuildToolWizardLocalePage#fLocaleGroupCombo";
- public void widgetDefaultSelected(SelectionEvent e){
- }
- }
-
- private class AllLocalesCheckboxSelectionListener implements SelectionListener {
- public void widgetSelected(SelectionEvent e){
- allLocalesCheckboxSelectionChanged();
- }
+ private BuildToolModelTable fModelLocalesTable;
- public void widgetDefaultSelected(SelectionEvent e){
- }
- }
-
- protected BuildToolWizardLocalePage(String pageName, BuildToolModelTable modelLocalesTable) {
- super(pageName);
- this.fModelLocalesTable = modelLocalesTable;
-
- this.setTitle(Messages.getString("BuildToolWizardLocalePage_PageTitle")); //$NON-NLS-1$
- this.setDescription(Messages.getString("BuildToolWizardLocalePage_PageDescription")); //$NON-NLS-1$
- }
+ private Button fAllLocalesCheckbox;
+ private Button fLocaleGroupCheckbox;
+ private Label fLocaleGroupLabel;
+ private Combo fLocaleGroupCombo;
- @Override
- public void createControl(Composite parent) {
- // Create filtered list component
- fLocaleFilter = new FilteredListComponent(fModelLocalesTable, new LocaleLabelProvider(), this);
- Composite container = fLocaleFilter.createFilteredListComponent(parent);
-
- createAllLocalesCheckbox(container);
-
- createLocaleGroupArea(container);
-
- setControl(container);
- Dialog.applyDialogFont(container);
-
- allLocalesCheckboxSelectionChanged();
- groupCheckboxSelectionChanged();
-
- try {
- int selectedIndex = getDialogSettings().getInt(SELECTED_GROUP);
- fLocaleGroupCombo.select(selectedIndex);
- } catch(NumberFormatException e) { }
-
- String pattern = not_null(getDialogSettings().get(FILTER_PATTERN), "");
- fLocaleFilter.fFilterText.setText(pattern);
- }
+ private FilteredListComponent fLocaleFilter;
- private void createAllLocalesCheckbox(Composite container) {
- fAllLocalesCheckbox = new Button(container, SWT.CHECK);
- GridData bLayout = new GridData();
- bLayout.horizontalIndent = 6;
- bLayout.horizontalSpan = 3;
- fAllLocalesCheckbox.setLayoutData(bLayout);
- fAllLocalesCheckbox.setText(Messages.getString("BuildToolWizardLocalePage_AllLocaleCheckbox"));
- fAllLocalesCheckbox.addSelectionListener(new AllLocalesCheckboxSelectionListener());
- fAllLocalesCheckbox.setSelection(getDialogSettings().getBoolean(ALL_LOCALES));
- }
-
- private void createLocaleGroupArea(Composite parent) {
- Group container = new Group(parent, SWT.NONE);
- FillLayout layout = new FillLayout(SWT.VERTICAL);
- layout.marginHeight = layout.marginWidth = 12;
- container.setLayout(layout);
+ private class GroupCheckboxSelectionListener implements SelectionListener {
+ public void widgetSelected(SelectionEvent e) {
+ groupCheckboxSelectionChanged();
+ }
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = 3;
- container.setLayoutData(gd);
-
- Composite container1 = new Composite(container, SWT.NONE);
- container1.setLayout(new GridLayout(1, false));
-
- Composite container2 = new Composite(container, SWT.NONE);
- container2.setLayout(new GridLayout(3, false));
-
- createLocaleGroupCheckbox(container1);
- createLocaleGroupDropdown(container2);
- }
-
- private void createLocaleGroupCheckbox(Composite container) {
- fLocaleGroupCheckbox = new Button(container, SWT.CHECK);
- fLocaleGroupCheckbox.setText(Messages.getString("BuildToolWizardLocalePage_GenerateForLocaleGroupLabel")); //$NON-NLS-1$
- fLocaleGroupCheckbox.addSelectionListener(new GroupCheckboxSelectionListener());
- fLocaleGroupCheckbox.setSelection(getDialogSettings().getBoolean(BY_GROUP));
- }
-
- private void createLocaleGroupDropdown(Composite container) {
- fLocaleGroupLabel = new Label(container, SWT.NONE);
- fLocaleGroupLabel.setText(Messages.getString("BuildToolWizardLocalePage_LocaleGroupLabel")); //$NON-NLS-1$
- GridData gdLabel = new GridData();
- gdLabel.horizontalIndent = 30;
- fLocaleGroupLabel.setLayoutData(gdLabel);
-
- fLocaleGroupCombo = new Combo(container, SWT.DROP_DOWN | SWT.READ_ONLY);
- GridData gdText = new GridData(GridData.FILL_HORIZONTAL);
- gdText.widthHint = 300;
- fLocaleGroupCombo.setLayoutData(gdText);
-
- fLocaleGroupCombo.add("All groups"); //$NON-NLS-1$
- fLocaleGroupCombo.add("Group1: de, es, fr, it, ja, ko, pt_BR, zh, zh_HK, zh_TW"); //$NON-NLS-1$
- fLocaleGroupCombo.add("Group2: cs, hu, pl, ru"); //$NON-NLS-1$
- fLocaleGroupCombo.add("Group2a: da, el, fi, nl, no, pt, sv, tr"); //$NON-NLS-1$
- fLocaleGroupCombo.add("GroupBidi: ar, iw"); //$NON-NLS-1$
- fLocaleGroupCombo.setText("All groups"); //$NON-NLS-1$
-
-// enableLocaleGroupArea(false);
- }
-
- private void groupCheckboxSelectionChanged() {
- if(fLocaleGroupCheckbox.getSelection()) {
- enableLocaleGroupArea(true);
- enableLocaleArea(false);
-
- setPageComplete(true);
- }
- else {
- enableLocaleGroupArea(false);
- enableLocaleArea(true);
- }
- }
-
- private void allLocalesCheckboxSelectionChanged() {
- if(fAllLocalesCheckbox.getSelection()) {
- fLocaleFilter.setEnabled(false);
- setPageComplete(true);
- }
- else {
- fLocaleFilter.setEnabled(true);
- setPageComplete(fLocaleFilter.getSelectedViewer().getTable().getItemCount() > 0);
- }
- }
-
- private void enableLocaleGroupArea(boolean enable) {
- fLocaleGroupCombo.setEnabled(enable);
- }
-
- private void enableLocaleArea(boolean enable) {
- if(enable) {
- fAllLocalesCheckbox.setEnabled(true);
- if(fAllLocalesCheckbox.getSelection()) {
- fLocaleFilter.setEnabled(false);
- setPageComplete(true);
- }
- else {
- fLocaleFilter.setEnabled(true);
- setPageComplete(fLocaleFilter.getSelectedViewer().getTable().getItemCount() > 0);
- }
- }
- else {
- fLocaleFilter.setEnabled(false);
- fAllLocalesCheckbox.setEnabled(false);
- }
- }
-
- public boolean isGeneratingFromLocales() {
- return !fLocaleGroupCheckbox.getSelection();
- }
-
- public boolean isGeneratingForAllLocales() {
- return fAllLocalesCheckbox.getSelection();
- }
-
- public Object[] getSelectedLocales() {
- return this.fLocaleFilter.getSelected();
- }
-
- public String getSelectedGroup() {
- return this.fLocaleGroupCombo.getText();
- }
-
- public boolean isCurrentPage() {
- return super.isCurrentPage();
- }
-
- public boolean canFlipToNextPage() {
- if(fAllLocalesCheckbox.getSelection() || fLocaleFilter.hasSelectedItems()){
- return true;
- }
-
- if(fLocaleGroupCheckbox.getSelection()) {
- return true;
- }
- return false;
- }
-
- @Override
- public void storeSettings() {
- Object[] objs = getSelectedLocales();
- String[] locales = new String[objs.length];
- int current = 0;
- for(Object o : objs){
- locales[current++] = o.toString();
- }
-
- IDialogSettings settings = getDialogSettings();
- settings.put(FILTER_PATTERN, fLocaleFilter.fFilterText.getText());
- settings.put(SELECTED_LOCALES, locales);
- settings.put(ALL_LOCALES, fAllLocalesCheckbox.getSelection());
- settings.put(BY_GROUP, fLocaleGroupCheckbox.getSelection());
-
- int selectionIndex = fLocaleGroupCombo.getSelectionIndex();
- if (selectionIndex != -1) {
- settings.put(SELECTED_GROUP, fLocaleGroupCombo.getSelectionIndex());
- }
- }
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ }
+
+ private class AllLocalesCheckboxSelectionListener implements
+ SelectionListener {
+ public void widgetSelected(SelectionEvent e) {
+ allLocalesCheckboxSelectionChanged();
+ }
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ }
+
+ protected BuildToolWizardLocalePage(String pageName,
+ BuildToolModelTable modelLocalesTable) {
+ super(pageName);
+ this.fModelLocalesTable = modelLocalesTable;
+
+ this.setTitle(Messages.getString("BuildToolWizardLocalePage_PageTitle")); //$NON-NLS-1$
+ this.setDescription(Messages
+ .getString("BuildToolWizardLocalePage_PageDescription")); //$NON-NLS-1$
+ }
+
+ @Override
+ public void createControl(Composite parent) {
+ // Create filtered list component
+ fLocaleFilter = new FilteredListComponent(fModelLocalesTable,
+ new LocaleLabelProvider(), this);
+ Composite container = fLocaleFilter.createFilteredListComponent(parent);
+
+ createAllLocalesCheckbox(container);
+
+ createLocaleGroupArea(container);
+
+ setControl(container);
+ Dialog.applyDialogFont(container);
+
+ allLocalesCheckboxSelectionChanged();
+ groupCheckboxSelectionChanged();
+
+ try {
+ int selectedIndex = getDialogSettings().getInt(SELECTED_GROUP);
+ fLocaleGroupCombo.select(selectedIndex);
+ } catch (NumberFormatException e) {
+ }
+
+ String pattern = not_null(getDialogSettings().get(FILTER_PATTERN), "");
+ fLocaleFilter.fFilterText.setText(pattern);
+ }
+
+ private void createAllLocalesCheckbox(Composite container) {
+ fAllLocalesCheckbox = new Button(container, SWT.CHECK);
+ GridData bLayout = new GridData();
+ bLayout.horizontalIndent = 6;
+ bLayout.horizontalSpan = 3;
+ fAllLocalesCheckbox.setLayoutData(bLayout);
+ fAllLocalesCheckbox.setText(Messages
+ .getString("BuildToolWizardLocalePage_AllLocaleCheckbox"));
+ fAllLocalesCheckbox
+ .addSelectionListener(new AllLocalesCheckboxSelectionListener());
+ fAllLocalesCheckbox.setSelection(getDialogSettings().getBoolean(
+ ALL_LOCALES));
+ }
+
+ private void createLocaleGroupArea(Composite parent) {
+ Group container = new Group(parent, SWT.NONE);
+ FillLayout layout = new FillLayout(SWT.VERTICAL);
+ layout.marginHeight = layout.marginWidth = 12;
+ container.setLayout(layout);
+
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = 3;
+ container.setLayoutData(gd);
+
+ Composite container1 = new Composite(container, SWT.NONE);
+ container1.setLayout(new GridLayout(1, false));
+
+ Composite container2 = new Composite(container, SWT.NONE);
+ container2.setLayout(new GridLayout(3, false));
+
+ createLocaleGroupCheckbox(container1);
+ createLocaleGroupDropdown(container2);
+ }
+
+ private void createLocaleGroupCheckbox(Composite container) {
+ fLocaleGroupCheckbox = new Button(container, SWT.CHECK);
+ fLocaleGroupCheckbox
+ .setText(Messages
+ .getString("BuildToolWizardLocalePage_GenerateForLocaleGroupLabel")); //$NON-NLS-1$
+ fLocaleGroupCheckbox
+ .addSelectionListener(new GroupCheckboxSelectionListener());
+ fLocaleGroupCheckbox.setSelection(getDialogSettings().getBoolean(
+ BY_GROUP));
+ }
+
+ private void createLocaleGroupDropdown(Composite container) {
+ fLocaleGroupLabel = new Label(container, SWT.NONE);
+ fLocaleGroupLabel.setText(Messages
+ .getString("BuildToolWizardLocalePage_LocaleGroupLabel")); //$NON-NLS-1$
+ GridData gdLabel = new GridData();
+ gdLabel.horizontalIndent = 30;
+ fLocaleGroupLabel.setLayoutData(gdLabel);
+
+ fLocaleGroupCombo = new Combo(container, SWT.DROP_DOWN | SWT.READ_ONLY);
+ GridData gdText = new GridData(GridData.FILL_HORIZONTAL);
+ gdText.widthHint = 300;
+ fLocaleGroupCombo.setLayoutData(gdText);
+
+ fLocaleGroupCombo.add("All groups"); //$NON-NLS-1$
+ fLocaleGroupCombo
+ .add("Group1: de, es, fr, it, ja, ko, pt_BR, zh, zh_HK, zh_TW"); //$NON-NLS-1$
+ fLocaleGroupCombo.add("Group2: cs, hu, pl, ru"); //$NON-NLS-1$
+ fLocaleGroupCombo.add("Group2a: da, el, fi, nl, no, pt, sv, tr"); //$NON-NLS-1$
+ fLocaleGroupCombo.add("GroupBidi: ar, iw"); //$NON-NLS-1$
+ fLocaleGroupCombo.setText("All groups"); //$NON-NLS-1$
+
+ // enableLocaleGroupArea(false);
+ }
+
+ private void groupCheckboxSelectionChanged() {
+ if (fLocaleGroupCheckbox.getSelection()) {
+ enableLocaleGroupArea(true);
+ enableLocaleArea(false);
+
+ setPageComplete(true);
+ } else {
+ enableLocaleGroupArea(false);
+ enableLocaleArea(true);
+ }
+ }
+
+ private void allLocalesCheckboxSelectionChanged() {
+ if (fAllLocalesCheckbox.getSelection()) {
+ fLocaleFilter.setEnabled(false);
+ setPageComplete(true);
+ } else {
+ fLocaleFilter.setEnabled(true);
+ setPageComplete(fLocaleFilter.getSelectedViewer().getTable()
+ .getItemCount() > 0);
+ }
+ }
+
+ private void enableLocaleGroupArea(boolean enable) {
+ fLocaleGroupCombo.setEnabled(enable);
+ }
+
+ private void enableLocaleArea(boolean enable) {
+ if (enable) {
+ fAllLocalesCheckbox.setEnabled(true);
+ if (fAllLocalesCheckbox.getSelection()) {
+ fLocaleFilter.setEnabled(false);
+ setPageComplete(true);
+ } else {
+ fLocaleFilter.setEnabled(true);
+ setPageComplete(fLocaleFilter.getSelectedViewer().getTable()
+ .getItemCount() > 0);
+ }
+ } else {
+ fLocaleFilter.setEnabled(false);
+ fAllLocalesCheckbox.setEnabled(false);
+ }
+ }
+
+ public boolean isGeneratingFromLocales() {
+ return !fLocaleGroupCheckbox.getSelection();
+ }
+
+ public boolean isGeneratingForAllLocales() {
+ return fAllLocalesCheckbox.getSelection();
+ }
+
+ public Object[] getSelectedLocales() {
+ return this.fLocaleFilter.getSelected();
+ }
+
+ public String getSelectedGroup() {
+ return this.fLocaleGroupCombo.getText();
+ }
+
+ public boolean isCurrentPage() {
+ return super.isCurrentPage();
+ }
+
+ public boolean canFlipToNextPage() {
+ if (fAllLocalesCheckbox.getSelection()
+ || fLocaleFilter.hasSelectedItems()) {
+ return true;
+ }
+
+ if (fLocaleGroupCheckbox.getSelection()) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public void storeSettings() {
+ Object[] objs = getSelectedLocales();
+ String[] locales = new String[objs.length];
+ int current = 0;
+ for (Object o : objs) {
+ locales[current++] = o.toString();
+ }
+
+ IDialogSettings settings = getDialogSettings();
+ settings.put(FILTER_PATTERN, fLocaleFilter.fFilterText.getText());
+ settings.put(SELECTED_LOCALES, locales);
+ settings.put(ALL_LOCALES, fAllLocalesCheckbox.getSelection());
+ settings.put(BY_GROUP, fLocaleGroupCheckbox.getSelection());
+
+ int selectionIndex = fLocaleGroupCombo.getSelectionIndex();
+ if (selectionIndex != -1) {
+ settings.put(SELECTED_GROUP, fLocaleGroupCombo.getSelectionIndex());
+ }
+ }
}
\ No newline at end of file
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizardPage.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizardPage.java
index 4405bd3..2964b7a 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizardPage.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizardPage.java
@@ -15,26 +15,28 @@
import org.eclipse.pde.core.IModelProviderListener;
import org.eclipse.swt.widgets.Composite;
-public class BuildToolWizardPage extends WizardPage implements IModelProviderListener{
+public class BuildToolWizardPage extends WizardPage implements
+ IModelProviderListener {
- public BuildToolWizardPage(String pageName) {
- super(pageName);
- }
-
- public void createControl(Composite parent) {
- }
-
- public void modelsChanged(IModelProviderEvent event) {
- }
-
- public void storeSettings(){}
+ public BuildToolWizardPage(String pageName) {
+ super(pageName);
+ }
- protected <T> T not_null(T... ts) {
- for(T t : ts){
- if(t != null){
- return t;
- }
- }
- return null;
- }
+ public void createControl(Composite parent) {
+ }
+
+ public void modelsChanged(IModelProviderEvent event) {
+ }
+
+ public void storeSettings() {
+ }
+
+ protected <T> T not_null(T... ts) {
+ for (T t : ts) {
+ if (t != null) {
+ return t;
+ }
+ }
+ return null;
+ }
}
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizardPluginPage.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizardPluginPage.java
index 9761e9e..a8a3601 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizardPluginPage.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/BuildToolWizardPluginPage.java
@@ -30,188 +30,203 @@
import org.eclipse.swt.widgets.Text;
public class BuildToolWizardPluginPage extends BuildToolWizardPage {
-
- private static final String EXTERNAL_ECLIPSE_CHECKBOX = "BuildToolWizardPluginPage#fEclipseInstallCheckbox";
- private static final String EXTERNAL_ECLIPSE_LOCATION = "BuildToolWizardPluginPage#fEclipseArchiveLocationText";
- private static final String FILTER_PATTERN = "BuildToolWizardPluginPage#fPluginFilter";
-
- private static final int MARGIN = 12;
- private static final int LABEL_WIDTH = 30;
- private static final int TEXTBOX_WIDTH = 300;
+
+ private static final String EXTERNAL_ECLIPSE_CHECKBOX = "BuildToolWizardPluginPage#fEclipseInstallCheckbox";
+ private static final String EXTERNAL_ECLIPSE_LOCATION = "BuildToolWizardPluginPage#fEclipseArchiveLocationText";
+ private static final String FILTER_PATTERN = "BuildToolWizardPluginPage#fPluginFilter";
+
+ private static final int MARGIN = 12;
+ private static final int LABEL_WIDTH = 30;
+ private static final int TEXTBOX_WIDTH = 300;
private static final String[] fEclipseArchiveExtensions = new String[] { "*.zip" }; //$NON-NLS-1$
- private BuildToolModelTable fModelPluginsTable;
-
- private Button fEclipseInstallCheckbox;
- private Button fEclipseArchiveBrowseButton;
- private Text fEclipseArchiveLocationText;
- private Label fEclipseArchiveLocationLabel;
-
- private FilteredListComponent fPluginFilter;
-
- private class TextModifyListener implements ModifyListener {
- public void modifyText(ModifyEvent e) {
- textSelectionChanged();
- }
- }
-
- private class CheckboxSelectionListener implements SelectionListener {
- public void widgetSelected(SelectionEvent e){
- checkboxSelectionChanged();
- }
+ private BuildToolModelTable fModelPluginsTable;
- public void widgetDefaultSelected(SelectionEvent e){
-
- }
- }
-
- protected BuildToolWizardPluginPage(String pageName, BuildToolModelTable modelPluginsTable) {
- super(pageName);
- this.fModelPluginsTable = modelPluginsTable;
-
- this.setTitle(Messages.getString("BuildToolWizardPluginPage_PageTitle")); //$NON-NLS-1$
- this.setDescription(Messages.getString("BuildToolWizardPluginPage_PageDescription")); //$NON-NLS-1$
- }
-
- @Override
- public void createControl(Composite parent) {
- // Create filtered list component
- fPluginFilter = new FilteredListComponent(fModelPluginsTable, new PluginLabelProvider(), this);
- Composite container = fPluginFilter.createFilteredListComponent(parent);
+ private Button fEclipseInstallCheckbox;
+ private Button fEclipseArchiveBrowseButton;
+ private Text fEclipseArchiveLocationText;
+ private Label fEclipseArchiveLocationLabel;
- createEclipseInstallArea(container);
+ private FilteredListComponent fPluginFilter;
- setControl(container);
- Dialog.applyDialogFont(container);
-
- checkboxSelectionChanged();
-
- String pattern = not_null(getDialogSettings().get(FILTER_PATTERN), "");
- fPluginFilter.fFilterText.setText(pattern);
- }
-
- private void createEclipseInstallArea(Composite parent) {
- Group container = new Group(parent, SWT.NONE);
- FillLayout layout = new FillLayout(SWT.VERTICAL);
- layout.marginHeight = layout.marginWidth = MARGIN;
- container.setLayout(layout);
+ private class TextModifyListener implements ModifyListener {
+ public void modifyText(ModifyEvent e) {
+ textSelectionChanged();
+ }
+ }
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = 3;
- container.setLayoutData(gd);
-
- Composite container1 = new Composite(container, SWT.NONE);
- container1.setLayout(new GridLayout(1, false));
-
- Composite container2 = new Composite(container, SWT.NONE);
- container2.setLayout(new GridLayout(3, false));
-
- createEclipseInstallCheckbox(container1);
- createEclipseInstallBrowse(container2);
- }
+ private class CheckboxSelectionListener implements SelectionListener {
+ public void widgetSelected(SelectionEvent e) {
+ checkboxSelectionChanged();
+ }
- private void createEclipseInstallCheckbox(Composite container) {
- IDialogSettings settings = getDialogSettings();
- boolean isSelected = settings.getBoolean(EXTERNAL_ECLIPSE_CHECKBOX);
- fEclipseInstallCheckbox = new Button(container, SWT.CHECK);
- fEclipseInstallCheckbox.setText(Messages.getString("BuildToolWizardPluginPage_GenerateFromArchiveLabel")); //$NON-NLS-1$
- fEclipseInstallCheckbox.addSelectionListener(new CheckboxSelectionListener());
- fEclipseInstallCheckbox.setSelection(isSelected);
- }
-
- private void createEclipseInstallBrowse(Composite container) {
- IDialogSettings settings = getDialogSettings();
- String archiveLocation = not_null(settings.get(EXTERNAL_ECLIPSE_LOCATION), "");
-
- fEclipseArchiveLocationLabel = new Label(container, SWT.NONE);
- fEclipseArchiveLocationLabel.setText(Messages.getString("BuildToolWizardPluginPage_ExternalArchiveLocationLabel")); //$NON-NLS-1$
- GridData gdLabel = new GridData();
- gdLabel.horizontalIndent = LABEL_WIDTH;
- fEclipseArchiveLocationLabel.setLayoutData(gdLabel);
-
- fEclipseArchiveLocationText = new Text(container, SWT.BORDER | SWT.SINGLE);
- fEclipseArchiveLocationText.setText(archiveLocation);
- fEclipseArchiveLocationText.addModifyListener(new TextModifyListener());
- GridData gdText = new GridData(GridData.FILL_HORIZONTAL);
- gdText.widthHint = TEXTBOX_WIDTH;
- fEclipseArchiveLocationText.setLayoutData(gdText);
-
-
- fEclipseArchiveBrowseButton = new Button(container, SWT.PUSH);
- fEclipseArchiveBrowseButton.setText(Messages.getString("BuildToolWizardPluginPage_BrowseButton")); //$NON-NLS-1$
+ public void widgetDefaultSelected(SelectionEvent e) {
- Listener listener = new Listener() {
- public void handleEvent(Event event) {
- FileDialog dialog = new FileDialog(getContainer().getShell(), SWT.OPEN);
- dialog.setText(Messages.getString("BuildToolWizardPluginPage_SelectEclipseArchiveDialogTitle")); //$NON-NLS-1$
- dialog.setFilterExtensions(fEclipseArchiveExtensions ); //$NON-NLS-1$
- String selectedFileName = dialog.open();
- if (selectedFileName != null) {
- fEclipseArchiveLocationText.setText(selectedFileName);
- }
- }
- };
+ }
+ }
- fEclipseArchiveBrowseButton.addListener(SWT.Selection, listener);
- enableEclipseInstallLocationArea(false);
- }
-
- private void textSelectionChanged() {
- setPageComplete(fEclipseArchiveLocationText.getText().length() > 0);
- }
-
- private void checkboxSelectionChanged() {
- if(fEclipseInstallCheckbox.getSelection()) {
- enableEclipseInstallLocationArea(true);
- fPluginFilter.setEnabled(false);
-
- setPageComplete(fEclipseArchiveLocationText.getText().length() > 0);
- }
- else {
- enableEclipseInstallLocationArea(false);
- fPluginFilter.setEnabled(true);
-
- setPageComplete(fPluginFilter.getSelectedViewer().getTable().getItemCount() > 0);
- }
- }
-
- private void enableEclipseInstallLocationArea(boolean enable) {
- fEclipseArchiveLocationText.setEnabled(enable);
- fEclipseArchiveBrowseButton.setEnabled(enable);
- }
-
- public String getEclipseArchiveLocation() {
- return this.fEclipseArchiveLocationText.getText();
- }
-
- public Object[] getSelectedPlugins() {
- return this.fPluginFilter.getSelected();
- }
-
- public boolean isGeneratingFromPlugins() {
- return !fEclipseInstallCheckbox.getSelection();
- }
-
- public boolean isCurrentPage() {
- return super.isCurrentPage();
- }
-
- @Override
- public boolean canFlipToNextPage() {
- if(!fEclipseInstallCheckbox.getSelection() && fPluginFilter.hasSelectedItems()){
- return true;
- }
- else if(fEclipseInstallCheckbox.getSelection() && fEclipseArchiveLocationText.getText().length() > 0) {
- return true;
- }
- return false;
- }
-
- @Override
- public void storeSettings() {
- IDialogSettings settings = getDialogSettings();
- settings.put(EXTERNAL_ECLIPSE_CHECKBOX, fEclipseInstallCheckbox.getSelection());
- settings.put(EXTERNAL_ECLIPSE_LOCATION, fEclipseArchiveLocationText.getText());
- settings.put(FILTER_PATTERN, fPluginFilter.fFilterText.getText());
- }
+ protected BuildToolWizardPluginPage(String pageName,
+ BuildToolModelTable modelPluginsTable) {
+ super(pageName);
+ this.fModelPluginsTable = modelPluginsTable;
+
+ this.setTitle(Messages.getString("BuildToolWizardPluginPage_PageTitle")); //$NON-NLS-1$
+ this.setDescription(Messages
+ .getString("BuildToolWizardPluginPage_PageDescription")); //$NON-NLS-1$
+ }
+
+ @Override
+ public void createControl(Composite parent) {
+ // Create filtered list component
+ fPluginFilter = new FilteredListComponent(fModelPluginsTable,
+ new PluginLabelProvider(), this);
+ Composite container = fPluginFilter.createFilteredListComponent(parent);
+
+ createEclipseInstallArea(container);
+
+ setControl(container);
+ Dialog.applyDialogFont(container);
+
+ checkboxSelectionChanged();
+
+ String pattern = not_null(getDialogSettings().get(FILTER_PATTERN), "");
+ fPluginFilter.fFilterText.setText(pattern);
+ }
+
+ private void createEclipseInstallArea(Composite parent) {
+ Group container = new Group(parent, SWT.NONE);
+ FillLayout layout = new FillLayout(SWT.VERTICAL);
+ layout.marginHeight = layout.marginWidth = MARGIN;
+ container.setLayout(layout);
+
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = 3;
+ container.setLayoutData(gd);
+
+ Composite container1 = new Composite(container, SWT.NONE);
+ container1.setLayout(new GridLayout(1, false));
+
+ Composite container2 = new Composite(container, SWT.NONE);
+ container2.setLayout(new GridLayout(3, false));
+
+ createEclipseInstallCheckbox(container1);
+ createEclipseInstallBrowse(container2);
+ }
+
+ private void createEclipseInstallCheckbox(Composite container) {
+ IDialogSettings settings = getDialogSettings();
+ boolean isSelected = settings.getBoolean(EXTERNAL_ECLIPSE_CHECKBOX);
+ fEclipseInstallCheckbox = new Button(container, SWT.CHECK);
+ fEclipseInstallCheckbox
+ .setText(Messages
+ .getString("BuildToolWizardPluginPage_GenerateFromArchiveLabel")); //$NON-NLS-1$
+ fEclipseInstallCheckbox
+ .addSelectionListener(new CheckboxSelectionListener());
+ fEclipseInstallCheckbox.setSelection(isSelected);
+ }
+
+ private void createEclipseInstallBrowse(Composite container) {
+ IDialogSettings settings = getDialogSettings();
+ String archiveLocation = not_null(
+ settings.get(EXTERNAL_ECLIPSE_LOCATION), "");
+
+ fEclipseArchiveLocationLabel = new Label(container, SWT.NONE);
+ fEclipseArchiveLocationLabel
+ .setText(Messages
+ .getString("BuildToolWizardPluginPage_ExternalArchiveLocationLabel")); //$NON-NLS-1$
+ GridData gdLabel = new GridData();
+ gdLabel.horizontalIndent = LABEL_WIDTH;
+ fEclipseArchiveLocationLabel.setLayoutData(gdLabel);
+
+ fEclipseArchiveLocationText = new Text(container, SWT.BORDER
+ | SWT.SINGLE);
+ fEclipseArchiveLocationText.setText(archiveLocation);
+ fEclipseArchiveLocationText.addModifyListener(new TextModifyListener());
+ GridData gdText = new GridData(GridData.FILL_HORIZONTAL);
+ gdText.widthHint = TEXTBOX_WIDTH;
+ fEclipseArchiveLocationText.setLayoutData(gdText);
+
+ fEclipseArchiveBrowseButton = new Button(container, SWT.PUSH);
+ fEclipseArchiveBrowseButton.setText(Messages
+ .getString("BuildToolWizardPluginPage_BrowseButton")); //$NON-NLS-1$
+
+ Listener listener = new Listener() {
+ public void handleEvent(Event event) {
+ FileDialog dialog = new FileDialog(getContainer().getShell(),
+ SWT.OPEN);
+ dialog.setText(Messages
+ .getString("BuildToolWizardPluginPage_SelectEclipseArchiveDialogTitle")); //$NON-NLS-1$
+ dialog.setFilterExtensions(fEclipseArchiveExtensions); //$NON-NLS-1$
+ String selectedFileName = dialog.open();
+ if (selectedFileName != null) {
+ fEclipseArchiveLocationText.setText(selectedFileName);
+ }
+ }
+ };
+
+ fEclipseArchiveBrowseButton.addListener(SWT.Selection, listener);
+ enableEclipseInstallLocationArea(false);
+ }
+
+ private void textSelectionChanged() {
+ setPageComplete(fEclipseArchiveLocationText.getText().length() > 0);
+ }
+
+ private void checkboxSelectionChanged() {
+ if (fEclipseInstallCheckbox.getSelection()) {
+ enableEclipseInstallLocationArea(true);
+ fPluginFilter.setEnabled(false);
+
+ setPageComplete(fEclipseArchiveLocationText.getText().length() > 0);
+ } else {
+ enableEclipseInstallLocationArea(false);
+ fPluginFilter.setEnabled(true);
+
+ setPageComplete(fPluginFilter.getSelectedViewer().getTable()
+ .getItemCount() > 0);
+ }
+ }
+
+ private void enableEclipseInstallLocationArea(boolean enable) {
+ fEclipseArchiveLocationText.setEnabled(enable);
+ fEclipseArchiveBrowseButton.setEnabled(enable);
+ }
+
+ public String getEclipseArchiveLocation() {
+ return this.fEclipseArchiveLocationText.getText();
+ }
+
+ public Object[] getSelectedPlugins() {
+ return this.fPluginFilter.getSelected();
+ }
+
+ public boolean isGeneratingFromPlugins() {
+ return !fEclipseInstallCheckbox.getSelection();
+ }
+
+ public boolean isCurrentPage() {
+ return super.isCurrentPage();
+ }
+
+ @Override
+ public boolean canFlipToNextPage() {
+ if (!fEclipseInstallCheckbox.getSelection()
+ && fPluginFilter.hasSelectedItems()) {
+ return true;
+ } else if (fEclipseInstallCheckbox.getSelection()
+ && fEclipseArchiveLocationText.getText().length() > 0) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public void storeSettings() {
+ IDialogSettings settings = getDialogSettings();
+ settings.put(EXTERNAL_ECLIPSE_CHECKBOX,
+ fEclipseInstallCheckbox.getSelection());
+ settings.put(EXTERNAL_ECLIPSE_LOCATION,
+ fEclipseArchiveLocationText.getText());
+ settings.put(FILTER_PATTERN, fPluginFilter.fFilterText.getText());
+ }
}
\ No newline at end of file
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/CoverageReportFilterDialog.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/CoverageReportFilterDialog.java
index 7e506ad..54575c2 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/CoverageReportFilterDialog.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/CoverageReportFilterDialog.java
@@ -13,16 +13,15 @@
import org.eclipse.swt.widgets.Shell;
public class CoverageReportFilterDialog extends FilterDialog {
-
- public CoverageReportFilterDialog(final Shell parent, final BuildToolWizardConfigurationPage caller) {
- super(parent, caller);
-
- parent.setText(Messages.getString("CoverageReportFilterDialog_Title"));
- }
-
- protected void setChosenFilter(String filter) {
- fCallingPage.setCoverageReportFilter(filter);
- }
+
+ public CoverageReportFilterDialog(final Shell parent,
+ final BuildToolWizardConfigurationPage caller) {
+ super(parent, caller);
+
+ parent.setText(Messages.getString("CoverageReportFilterDialog_Title"));
+ }
+
+ protected void setChosenFilter(String filter) {
+ fCallingPage.setCoverageReportFilter(filter);
+ }
}
-
-
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/FilterDialog.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/FilterDialog.java
index cf945e3..35b4b1d 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/FilterDialog.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/FilterDialog.java
@@ -29,102 +29,104 @@
public abstract class FilterDialog extends Dialog {
- protected static final int DIALOG_POSITION_Y = 350;
- protected static final int DIALOG_POSITION_X = 425;
- protected static final int DIALOG_HEIGHT = 115;
- protected static final int DIALOG_WIDTH = 425;
-
- protected Label fAddLabel;
- protected Text fAddText;
- protected Button fAddButton;
- protected Button fCancelButton;
-
- protected BuildToolWizardConfigurationPage fCallingPage;
-
- protected Label fErrorLabel;
-
- public FilterDialog(final Shell parent, final BuildToolWizardConfigurationPage caller) {
- super(parent);
-
- this.fCallingPage = caller;
-
- parent.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
- parent.setLocation(DIALOG_POSITION_X, DIALOG_POSITION_Y);
-
- // Set layouts
- parent.setLayout(new GridLayout(1, false));
- parent.setLayoutData(new GridData());
-
- // Label describes what is expected
- createLabelArea(parent);
-
- // Text allows user to enter a pattern
- createTextboxArea(parent);
-
- // Create a button area for adding
- createButtonArea(parent);
- }
+ protected static final int DIALOG_POSITION_Y = 350;
+ protected static final int DIALOG_POSITION_X = 425;
+ protected static final int DIALOG_HEIGHT = 115;
+ protected static final int DIALOG_WIDTH = 425;
- protected void createLabelArea(final Shell parent) {
- fAddLabel = new Label(parent, SWT.NONE);
- fAddLabel.setText(Messages.getString("FilterDialog_EnterPatternLabel"));
-
- GridData gdLabel = new GridData(GridData.FILL_HORIZONTAL);
- gdLabel.widthHint = 400;
- fAddLabel.setLayoutData(gdLabel);
- }
+ protected Label fAddLabel;
+ protected Text fAddText;
+ protected Button fAddButton;
+ protected Button fCancelButton;
- protected void createTextboxArea(final Shell parent) {
- fAddText = new Text(parent, SWT.BORDER | SWT.SINGLE);
-
- GridData gdText = new GridData(GridData.FILL_HORIZONTAL);
+ protected BuildToolWizardConfigurationPage fCallingPage;
+
+ protected Label fErrorLabel;
+
+ public FilterDialog(final Shell parent,
+ final BuildToolWizardConfigurationPage caller) {
+ super(parent);
+
+ this.fCallingPage = caller;
+
+ parent.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
+ parent.setLocation(DIALOG_POSITION_X, DIALOG_POSITION_Y);
+
+ // Set layouts
+ parent.setLayout(new GridLayout(1, false));
+ parent.setLayoutData(new GridData());
+
+ // Label describes what is expected
+ createLabelArea(parent);
+
+ // Text allows user to enter a pattern
+ createTextboxArea(parent);
+
+ // Create a button area for adding
+ createButtonArea(parent);
+ }
+
+ protected void createLabelArea(final Shell parent) {
+ fAddLabel = new Label(parent, SWT.NONE);
+ fAddLabel.setText(Messages.getString("FilterDialog_EnterPatternLabel"));
+
+ GridData gdLabel = new GridData(GridData.FILL_HORIZONTAL);
+ gdLabel.widthHint = 400;
+ fAddLabel.setLayoutData(gdLabel);
+ }
+
+ protected void createTextboxArea(final Shell parent) {
+ fAddText = new Text(parent, SWT.BORDER | SWT.SINGLE);
+
+ GridData gdText = new GridData(GridData.FILL_HORIZONTAL);
gdText.widthHint = 400;
- fAddText.setLayoutData(gdText);
- }
+ fAddText.setLayoutData(gdText);
+ }
- protected void createButtonArea(final Shell parent) {
- Composite container = new Composite(parent, SWT.NONE);
- container.setLayout(new GridLayout(3, false));
-
- GridData gdLabel = new GridData();
- gdLabel.widthHint = 240;
-
- fErrorLabel = new Label(container, SWT.NONE);
- fErrorLabel.setLayoutData(gdLabel);
- fErrorLabel.setForeground(new Color(null, new RGB(255,0,0)));
- fErrorLabel.setText(Messages.getString("FilterDialog_PatternValidationError"));
- fErrorLabel.setVisible(false);
-
- GridData gdButton = new GridData();
- gdButton.widthHint = 75;
-
- fAddButton = new Button(container, SWT.PUSH);
- fAddButton.setText(Messages.getString("Common_AddButton"));
- fAddButton.setLayoutData(gdButton);
- fAddButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- try {
- fErrorLabel.setVisible(false);
- Pattern.compile(fAddText.getText());
- setChosenFilter(fAddText.getText());
- parent.dispose();
- } catch (PatternSyntaxException ex) {
- fErrorLabel.setVisible(true);
- }
- }
- });
-
- fCancelButton = new Button(container, SWT.PUSH);
- fCancelButton.setText(Messages.getString("Common_CancelButton"));
- fCancelButton.setLayoutData(gdButton);
- fCancelButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- parent.dispose();
- }
- });
-
- parent.setDefaultButton(fAddButton);
- }
-
- protected abstract void setChosenFilter(String filter);
+ protected void createButtonArea(final Shell parent) {
+ Composite container = new Composite(parent, SWT.NONE);
+ container.setLayout(new GridLayout(3, false));
+
+ GridData gdLabel = new GridData();
+ gdLabel.widthHint = 240;
+
+ fErrorLabel = new Label(container, SWT.NONE);
+ fErrorLabel.setLayoutData(gdLabel);
+ fErrorLabel.setForeground(new Color(null, new RGB(255, 0, 0)));
+ fErrorLabel.setText(Messages
+ .getString("FilterDialog_PatternValidationError"));
+ fErrorLabel.setVisible(false);
+
+ GridData gdButton = new GridData();
+ gdButton.widthHint = 75;
+
+ fAddButton = new Button(container, SWT.PUSH);
+ fAddButton.setText(Messages.getString("Common_AddButton"));
+ fAddButton.setLayoutData(gdButton);
+ fAddButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ try {
+ fErrorLabel.setVisible(false);
+ Pattern.compile(fAddText.getText());
+ setChosenFilter(fAddText.getText());
+ parent.dispose();
+ } catch (PatternSyntaxException ex) {
+ fErrorLabel.setVisible(true);
+ }
+ }
+ });
+
+ fCancelButton = new Button(container, SWT.PUSH);
+ fCancelButton.setText(Messages.getString("Common_CancelButton"));
+ fCancelButton.setLayoutData(gdButton);
+ fCancelButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ parent.dispose();
+ }
+ });
+
+ parent.setDefaultButton(fAddButton);
+ }
+
+ protected abstract void setChosenFilter(String filter);
}
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/FilteredListComponent.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/FilteredListComponent.java
index 9c70dab..e3259b6 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/FilteredListComponent.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/FilteredListComponent.java
@@ -47,484 +47,515 @@
public class FilteredListComponent {
- private Button fAddButton;
- private Button fAddAllButton;
- private Button fRemoveButton;
- private Button fRemoveAllButton;
- private Label fCountLabel;
-
- protected WorkbenchJob fFilterJob;
- protected Text fFilterText;
- protected ListFilter fFilter;
-
- private boolean fBlockSelectionListeners;
-
- protected TableViewer fAvailableViewer;
- protected TableViewer fSelectedViewer;
-
- protected HashMap<Object, Object> fSelected;
- protected Composite fHighLevelContainer;
-
- protected LabelProvider fLabelProvider;
- protected boolean fEnabled;
-
- protected BuildToolWizardPage fParentPage;
- protected BuildToolModelTable fModelTable;
-
- protected class ContentProvider implements IStructuredContentProvider {
- public Object[] getElements(Object parent) {
- return fModelTable.getModels();
- }
+ private Button fAddButton;
+ private Button fAddAllButton;
+ private Button fRemoveButton;
+ private Button fRemoveAllButton;
+ private Label fCountLabel;
- public void dispose() {
- }
+ protected WorkbenchJob fFilterJob;
+ protected Text fFilterText;
+ protected ListFilter fFilter;
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
- }
+ private boolean fBlockSelectionListeners;
- protected class SelectedContentProvider implements IStructuredContentProvider {
- public Object[] getElements(Object parent) {
- return fModelTable.getPreSelected();
- }
+ protected TableViewer fAvailableViewer;
+ protected TableViewer fSelectedViewer;
- public void dispose() {
- }
+ protected HashMap<Object, Object> fSelected;
+ protected Composite fHighLevelContainer;
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
- }
-
- protected FilteredListComponent(BuildToolModelTable modelTable, LabelProvider labelProvider, BuildToolWizardPage parentPage) {
- this.fModelTable = modelTable;
- this.fLabelProvider = labelProvider;
- this.fParentPage = parentPage;
-
- fEnabled = true;
- fSelected = new HashMap<Object, Object>();
- }
-
- protected GridLayout getComponentLayout() {
- GridLayout layout = new GridLayout();
- layout.numColumns = 3;
- layout.makeColumnsEqualWidth = false;
- layout.horizontalSpacing = 5;
- layout.verticalSpacing = 20;
- return layout;
- }
-
- private GridLayout getViewerLayout() {
- GridLayout layout = new GridLayout();
- layout.marginWidth = 0;
- layout.marginHeight = 0;
- return layout;
- }
-
- public Composite createFilteredListComponent(Composite parent) {
- GridLayout gridLayout = getComponentLayout();
-
- fHighLevelContainer = new Composite(parent, SWT.NONE);
- fHighLevelContainer.setLayout(gridLayout);
+ protected LabelProvider fLabelProvider;
+ protected boolean fEnabled;
- // Create filter area component
- createFilterArea(fHighLevelContainer);
-
- // Create available plug-in list component
- createAvailableList(fHighLevelContainer);
-
- // Create control button area component
- createControlButtonArea(fHighLevelContainer);
-
- // Create selected plug-in list component
- createSelectedList(fHighLevelContainer);
-
- // Add viewer listeners
- addViewerListeners();
-
- addFilter();
-
- updateCount();
-
- initialize();
-
- return fHighLevelContainer;
- }
-
- private void addFilter() {
- fFilter = new ListFilter(fSelected, fLabelProvider);
- fAvailableViewer.addFilter(fFilter);
- fFilterJob = new WorkbenchJob("FilterJob") { //$NON-NLS-1$
- public IStatus runInUIThread(IProgressMonitor monitor) {
- handleFilter();
- return Status.OK_STATUS;
- }
- };
- fFilterJob.setSystem(true);
- }
-
- protected Composite createFilterArea(Composite parent) {
- Group container = createFilterContainer(parent);
- fFilterText = createFilterText(container, ""); //$NON-NLS-1$
- return container;
- }
-
- private Group createFilterContainer(Composite parent) {
- Group container = new Group(parent, SWT.NONE);
- GridLayout layout = new GridLayout(2, false);
- layout.marginWidth = layout.marginHeight = 6;
- container.setLayout(layout);
+ protected BuildToolWizardPage fParentPage;
+ protected BuildToolModelTable fModelTable;
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = 3;
- container.setLayoutData(gd);
- container.setText(Messages.getString("FilteredListComponent_FilterAvailableListLabel")); //$NON-NLS-1$
- return container;
- }
-
- private Text createFilterText(Composite parent, String initial) {
- Label filter = new Label(parent, SWT.NONE);
- filter.setText(Messages.getString("FilteredListComponent_FilterDescriptionLabel")); //$NON-NLS-1$
-
- Text text = new Text(parent, SWT.BORDER);
- text.setText(initial);
-
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- text.setLayoutData(gd);
- return text;
- }
-
- protected Composite createAvailableList(Composite parent) {
- Composite container = createViewerContainer(parent, Messages.getString("FilteredListComponent_AvailableListLabel")); //$NON-NLS-1$
- fAvailableViewer = createTableViewer(container, new ContentProvider(), fModelTable.getModels());
- container.setLayoutData(new GridData(GridData.FILL_BOTH));
- if(fModelTable.getModels().length > 0) {
- fAvailableViewer.getTable().setSelection(0);
- }
- return container;
- }
-
- /**
- * Handles changes to the list based on changes to the text field.
- */
- void handleFilter() {
- boolean changed = false;
- String newFilter;
- if (fFilterText == null || (newFilter = fFilterText.getText().trim()).length() == 0)
- newFilter = "*"; //$NON-NLS-1$
- changed = fFilter.setPattern(newFilter);
- if (changed) {
- fAvailableViewer.getTable().setRedraw(false);
- fAvailableViewer.refresh();
- fAvailableViewer.getTable().setRedraw(true);
- if (fEnabled) {
- updateButtonEnablement(false, false);
- updateCount();
- }
- }
- }
-
- protected Composite createSelectedList(Composite parent) {
- Composite container = createViewerContainer(parent, Messages.getString("FilteredListComponent_SelectedListLabel")); //$NON-NLS-1$
- fSelectedViewer = createTableViewer(container, new SelectedContentProvider(), fModelTable.getPreSelected());
- if(fModelTable.getPreSelected().length > 0) {
- fSelectedViewer.getTable().setSelection(0);
- }
- return container;
- }
-
- private Composite createViewerContainer(Composite parent, String message) {
- Composite container = new Composite(parent, SWT.NONE);
- GridLayout gridLayout = getViewerLayout();
- container.setLayout(gridLayout);
- container.setLayoutData(new GridData(GridData.FILL_BOTH));
+ protected class ContentProvider implements IStructuredContentProvider {
+ public Object[] getElements(Object parent) {
+ return fModelTable.getModels();
+ }
- Label label = new Label(container, SWT.NONE);
- label.setText(message);
- return container;
- }
-
- private TableViewer createTableViewer(Composite container, IContentProvider provider, Object[] input) {
- GridData gd = new GridData(GridData.FILL_BOTH);
- gd.heightHint = 200;
- gd.widthHint = 225;
-
- Table table = new Table(container, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
- table.setLayoutData(gd);
+ public void dispose() {
+ }
- TableViewer viewer = new TableViewer(table);
- viewer.setLabelProvider(fLabelProvider);
- viewer.setContentProvider(provider);
- viewer.setInput(input);
- viewer.setComparator(new ViewerComparator());
- return viewer;
- }
-
- protected Composite createControlButtonArea(Composite parent) {
- ScrolledComposite comp = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.H_SCROLL);
- GridLayout layout = new GridLayout();
- layout.marginWidth = layout.marginHeight = 0;
- comp.setLayoutData(new GridData(GridData.FILL_VERTICAL));
- Composite container = new Composite(comp, SWT.NONE);
- layout = new GridLayout();
- layout.marginWidth = 0;
- layout.marginTop = 50;
- container.setLayout(layout);
- GridData gd = new GridData(GridData.FILL_VERTICAL);
- gd.verticalIndent = 15;
- container.setLayoutData(gd);
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
+ }
- fAddButton = new Button(container, SWT.PUSH);
- fAddButton.setText(Messages.getString("FilteredListComponent_AddButton")); //$NON-NLS-1$
- fAddButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fAddButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- handleAdd();
- }
- });
+ protected class SelectedContentProvider implements
+ IStructuredContentProvider {
+ public Object[] getElements(Object parent) {
+ return fModelTable.getPreSelected();
+ }
- fAddAllButton = new Button(container, SWT.PUSH);
- fAddAllButton.setText(Messages.getString("FilteredListComponent_AddAllButton")); //$NON-NLS-1$
- fAddAllButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fAddAllButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- handleAddAll();
- }
- });
+ public void dispose() {
+ }
- fRemoveButton = new Button(container, SWT.PUSH);
- fRemoveButton.setText(Messages.getString("FilteredListComponent_RemoveButton")); //$NON-NLS-1$
- fRemoveButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fRemoveButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- handleRemove();
- }
- });
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
+ }
- fRemoveAllButton = new Button(container, SWT.PUSH);
- fRemoveAllButton.setText(Messages.getString("FilteredListComponent_RemoveAllButton")); //$NON-NLS-1$
- fRemoveAllButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fRemoveAllButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- handleRemoveAll();
- }
- });
+ protected FilteredListComponent(BuildToolModelTable modelTable,
+ LabelProvider labelProvider, BuildToolWizardPage parentPage) {
+ this.fModelTable = modelTable;
+ this.fLabelProvider = labelProvider;
+ this.fParentPage = parentPage;
- fCountLabel = new Label(container, SWT.NONE);
- fCountLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
- comp.setContent(container);
- comp.setMinHeight(250);
- comp.setExpandHorizontal(true);
- comp.setExpandVertical(true);
- return container;
- }
-
- private void handleAdd() {
- IStructuredSelection ssel = (IStructuredSelection) fAvailableViewer.getSelection();
- if (ssel.size() > 0) {
- Table table = fAvailableViewer.getTable();
- int index = table.getSelectionIndices()[0];
- Object[] selection = ssel.toArray();
- setBlockSelectionListeners(true);
- setRedraw(false);
- for (int i = 0; i < selection.length; i++) {
- doAdd(selection[i]);
- }
- setRedraw(true);
- setBlockSelectionListeners(false);
- table.setSelection(index < table.getItemCount() ? index : table.getItemCount() - 1);
- }
- }
+ fEnabled = true;
+ fSelected = new HashMap<Object, Object>();
+ }
- private void handleAddAll() {
- ArrayList<Object> data = new ArrayList<Object>();
- for(TableItem item: fAvailableViewer.getTable().getItems()) {
- data.add(item.getData());
- }
-
- if (data.size() > 0) {
- Object[] datas = data.toArray();
- setBlockSelectionListeners(true);
- setRedraw(false);
- for (int i = 0; i < datas.length; i++) {
- doAdd(datas[i]);
- }
- setRedraw(true);
- setBlockSelectionListeners(false);
- }
- }
+ protected GridLayout getComponentLayout() {
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 3;
+ layout.makeColumnsEqualWidth = false;
+ layout.horizontalSpacing = 5;
+ layout.verticalSpacing = 20;
+ return layout;
+ }
- private void handleRemove() {
- IStructuredSelection ssel = (IStructuredSelection) fSelectedViewer.getSelection();
- if (ssel.size() > 0) {
- Table table = fSelectedViewer.getTable();
- int index = table.getSelectionIndices()[0];
- Object[] selection = ssel.toArray();
- setBlockSelectionListeners(true);
- setRedraw(false);
- for (int i = 0; i < selection.length; i++) {
- doRemove(selection[i]);
- }
- setRedraw(true);
- setBlockSelectionListeners(false);
- table.setSelection(index < table.getItemCount() ? index : table.getItemCount() - 1);
- }
- }
+ private GridLayout getViewerLayout() {
+ GridLayout layout = new GridLayout();
+ layout.marginWidth = 0;
+ layout.marginHeight = 0;
+ return layout;
+ }
- private void doAdd(Object o) {
- fModelTable.removeModel(o);
- fModelTable.addToPreselected(o);
- fSelectedViewer.add(o);
- fAvailableViewer.remove(o);
- fSelected.put(o, null);
- listChanged(true, false);
- }
+ public Composite createFilteredListComponent(Composite parent) {
+ GridLayout gridLayout = getComponentLayout();
- private void doRemove(Object o) {
- fModelTable.addModel(o);
- fModelTable.removeFromPreselected(o);
- fSelected.remove(o);
- fSelectedViewer.remove(o);
- fAvailableViewer.add(o);
- listChanged(false, true);
- }
-
- private void listChanged(boolean doAddEnablement, boolean doRemoveEnablement) {
- updateCount();
- updateButtonEnablement(doAddEnablement, doRemoveEnablement);
- fParentPage.setPageComplete(fSelectedViewer.getTable().getItemCount() > 0);
- }
-
- public boolean hasSelectedItems() {
- if (fSelectedViewer.getTable().getItems().length > 0) {
- return true;
- }
- return false;
- }
+ fHighLevelContainer = new Composite(parent, SWT.NONE);
+ fHighLevelContainer.setLayout(gridLayout);
- private void handleRemoveAll() {
- ArrayList<Object> data = new ArrayList<Object>();
- for(TableItem item: fSelectedViewer.getTable().getItems()) {
- data.add(item.getData());
- }
- if (data.size() > 0) {
- Object[] datas = data.toArray();
- setBlockSelectionListeners(true);
- setRedraw(false);
- for (int i = 0; i < datas.length; i++) {
- doRemove(datas[i]);
- }
- setRedraw(true);
- setBlockSelectionListeners(false);
- }
- }
-
- private void setBlockSelectionListeners(boolean blockSelectionListeners) {
- fBlockSelectionListeners = blockSelectionListeners;
- }
-
- private void setRedraw(boolean redraw) {
- fAvailableViewer.getTable().setRedraw(redraw);
- fSelectedViewer.getTable().setRedraw(redraw);
- }
-
- protected void updateCount() {
- Integer numAvailable = new Integer(fAvailableViewer.getTable().getItemCount() + fSelectedViewer.getTable().getItemCount());
- Integer numSelected = new Integer(fSelectedViewer.getTable().getItemCount());
-
- fCountLabel.setText(numSelected.toString() + " of " + numAvailable.toString() + " selected"); //$NON-NLS-1$ //$NON-NLS-2$
- fCountLabel.getParent().layout();
- }
+ // Create filter area component
+ createFilterArea(fHighLevelContainer);
- protected void updateButtonEnablement(boolean doAddEnablement, boolean doRemoveEnablement) {
- int availableCount = fAvailableViewer.getTable().getItemCount();
- int selectedCount = fSelectedViewer.getTable().getItemCount();
+ // Create available plug-in list component
+ createAvailableList(fHighLevelContainer);
- fAddAllButton.setEnabled(availableCount > 0);
- fRemoveAllButton.setEnabled(selectedCount > 0);
-
- if(!(availableCount>0) && fAddButton.isEnabled()) {
- fAddButton.setEnabled(false);
- }
- if(!(selectedCount>0) && fRemoveButton.isEnabled()) {
- fRemoveButton.setEnabled(false);
- }
- }
-
- private void updateSelectionBasedEnablement(ISelection theSelection, boolean available) {
- if (available) {
- fAddButton.setEnabled(!theSelection.isEmpty());
- }
- else {
- fRemoveButton.setEnabled(!theSelection.isEmpty());
- }
- }
-
- protected void initialize() {
- if (fEnabled) {
- updateButtonEnablement(true, true);
- }
- //setPageComplete(false);
- }
-
- protected void addViewerListeners() {
- fAvailableViewer.addDoubleClickListener(new IDoubleClickListener() {
- public void doubleClick(DoubleClickEvent event) {
- handleAdd();
- }
- });
+ // Create control button area component
+ createControlButtonArea(fHighLevelContainer);
- fSelectedViewer.addDoubleClickListener(new IDoubleClickListener() {
- public void doubleClick(DoubleClickEvent event) {
- handleRemove();
- }
- });
+ // Create selected plug-in list component
+ createSelectedList(fHighLevelContainer);
- fAvailableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- if (!fBlockSelectionListeners)
- updateSelectionBasedEnablement(event.getSelection(), true);
- }
- });
+ // Add viewer listeners
+ addViewerListeners();
- fSelectedViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- if (!fBlockSelectionListeners)
- updateSelectionBasedEnablement(event.getSelection(), false);
- }
- });
+ addFilter();
- fFilterText.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- fFilterJob.cancel();
- fFilterJob.schedule(0);
- }
- });
- }
-
- public void setEnabled(boolean enabled) {
- fFilterText.setEnabled(enabled);
- fAddButton.setEnabled(enabled);
- fRemoveButton.setEnabled(enabled);
- fAddAllButton.setEnabled(enabled);
- fRemoveAllButton.setEnabled(enabled);
- fAvailableViewer.getControl().setEnabled(enabled);
- fSelectedViewer.getControl().setEnabled(enabled);
- if (enabled) {
- updateButtonEnablement(false, false);
- //fParentPage.setPageComplete(fSelectedViewer.getTable().getItemCount() > 0);
- }
- fEnabled = enabled;
- }
-
- public TableViewer getSelectedViewer() {
- return fSelectedViewer;
- }
-
- public Object[] getSelected() {
- return fModelTable.getPreSelected();
- }
-
- public boolean isEnabled() {
- return fEnabled;
- }
+ updateCount();
+
+ initialize();
+
+ return fHighLevelContainer;
+ }
+
+ private void addFilter() {
+ fFilter = new ListFilter(fSelected, fLabelProvider);
+ fAvailableViewer.addFilter(fFilter);
+ fFilterJob = new WorkbenchJob("FilterJob") { //$NON-NLS-1$
+ public IStatus runInUIThread(IProgressMonitor monitor) {
+ handleFilter();
+ return Status.OK_STATUS;
+ }
+ };
+ fFilterJob.setSystem(true);
+ }
+
+ protected Composite createFilterArea(Composite parent) {
+ Group container = createFilterContainer(parent);
+ fFilterText = createFilterText(container, ""); //$NON-NLS-1$
+ return container;
+ }
+
+ private Group createFilterContainer(Composite parent) {
+ Group container = new Group(parent, SWT.NONE);
+ GridLayout layout = new GridLayout(2, false);
+ layout.marginWidth = layout.marginHeight = 6;
+ container.setLayout(layout);
+
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = 3;
+ container.setLayoutData(gd);
+ container.setText(Messages
+ .getString("FilteredListComponent_FilterAvailableListLabel")); //$NON-NLS-1$
+ return container;
+ }
+
+ private Text createFilterText(Composite parent, String initial) {
+ Label filter = new Label(parent, SWT.NONE);
+ filter.setText(Messages
+ .getString("FilteredListComponent_FilterDescriptionLabel")); //$NON-NLS-1$
+
+ Text text = new Text(parent, SWT.BORDER);
+ text.setText(initial);
+
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ text.setLayoutData(gd);
+ return text;
+ }
+
+ protected Composite createAvailableList(Composite parent) {
+ Composite container = createViewerContainer(parent,
+ Messages.getString("FilteredListComponent_AvailableListLabel")); //$NON-NLS-1$
+ fAvailableViewer = createTableViewer(container, new ContentProvider(),
+ fModelTable.getModels());
+ container.setLayoutData(new GridData(GridData.FILL_BOTH));
+ if (fModelTable.getModels().length > 0) {
+ fAvailableViewer.getTable().setSelection(0);
+ }
+ return container;
+ }
+
+ /**
+ * Handles changes to the list based on changes to the text field.
+ */
+ void handleFilter() {
+ boolean changed = false;
+ String newFilter;
+ if (fFilterText == null
+ || (newFilter = fFilterText.getText().trim()).length() == 0)
+ newFilter = "*"; //$NON-NLS-1$
+ changed = fFilter.setPattern(newFilter);
+ if (changed) {
+ fAvailableViewer.getTable().setRedraw(false);
+ fAvailableViewer.refresh();
+ fAvailableViewer.getTable().setRedraw(true);
+ if (fEnabled) {
+ updateButtonEnablement(false, false);
+ updateCount();
+ }
+ }
+ }
+
+ protected Composite createSelectedList(Composite parent) {
+ Composite container = createViewerContainer(parent,
+ Messages.getString("FilteredListComponent_SelectedListLabel")); //$NON-NLS-1$
+ fSelectedViewer = createTableViewer(container,
+ new SelectedContentProvider(), fModelTable.getPreSelected());
+ if (fModelTable.getPreSelected().length > 0) {
+ fSelectedViewer.getTable().setSelection(0);
+ }
+ return container;
+ }
+
+ private Composite createViewerContainer(Composite parent, String message) {
+ Composite container = new Composite(parent, SWT.NONE);
+ GridLayout gridLayout = getViewerLayout();
+ container.setLayout(gridLayout);
+ container.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ Label label = new Label(container, SWT.NONE);
+ label.setText(message);
+ return container;
+ }
+
+ private TableViewer createTableViewer(Composite container,
+ IContentProvider provider, Object[] input) {
+ GridData gd = new GridData(GridData.FILL_BOTH);
+ gd.heightHint = 200;
+ gd.widthHint = 225;
+
+ Table table = new Table(container, SWT.BORDER | SWT.MULTI
+ | SWT.V_SCROLL);
+ table.setLayoutData(gd);
+
+ TableViewer viewer = new TableViewer(table);
+ viewer.setLabelProvider(fLabelProvider);
+ viewer.setContentProvider(provider);
+ viewer.setInput(input);
+ viewer.setComparator(new ViewerComparator());
+ return viewer;
+ }
+
+ protected Composite createControlButtonArea(Composite parent) {
+ ScrolledComposite comp = new ScrolledComposite(parent, SWT.V_SCROLL
+ | SWT.H_SCROLL);
+ GridLayout layout = new GridLayout();
+ layout.marginWidth = layout.marginHeight = 0;
+ comp.setLayoutData(new GridData(GridData.FILL_VERTICAL));
+ Composite container = new Composite(comp, SWT.NONE);
+ layout = new GridLayout();
+ layout.marginWidth = 0;
+ layout.marginTop = 50;
+ container.setLayout(layout);
+ GridData gd = new GridData(GridData.FILL_VERTICAL);
+ gd.verticalIndent = 15;
+ container.setLayoutData(gd);
+
+ fAddButton = new Button(container, SWT.PUSH);
+ fAddButton.setText(Messages
+ .getString("FilteredListComponent_AddButton")); //$NON-NLS-1$
+ fAddButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ fAddButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ handleAdd();
+ }
+ });
+
+ fAddAllButton = new Button(container, SWT.PUSH);
+ fAddAllButton.setText(Messages
+ .getString("FilteredListComponent_AddAllButton")); //$NON-NLS-1$
+ fAddAllButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ fAddAllButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ handleAddAll();
+ }
+ });
+
+ fRemoveButton = new Button(container, SWT.PUSH);
+ fRemoveButton.setText(Messages
+ .getString("FilteredListComponent_RemoveButton")); //$NON-NLS-1$
+ fRemoveButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ fRemoveButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ handleRemove();
+ }
+ });
+
+ fRemoveAllButton = new Button(container, SWT.PUSH);
+ fRemoveAllButton.setText(Messages
+ .getString("FilteredListComponent_RemoveAllButton")); //$NON-NLS-1$
+ fRemoveAllButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ fRemoveAllButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ handleRemoveAll();
+ }
+ });
+
+ fCountLabel = new Label(container, SWT.NONE);
+ fCountLabel
+ .setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
+ comp.setContent(container);
+ comp.setMinHeight(250);
+ comp.setExpandHorizontal(true);
+ comp.setExpandVertical(true);
+ return container;
+ }
+
+ private void handleAdd() {
+ IStructuredSelection ssel = (IStructuredSelection) fAvailableViewer
+ .getSelection();
+ if (ssel.size() > 0) {
+ Table table = fAvailableViewer.getTable();
+ int index = table.getSelectionIndices()[0];
+ Object[] selection = ssel.toArray();
+ setBlockSelectionListeners(true);
+ setRedraw(false);
+ for (int i = 0; i < selection.length; i++) {
+ doAdd(selection[i]);
+ }
+ setRedraw(true);
+ setBlockSelectionListeners(false);
+ table.setSelection(index < table.getItemCount() ? index : table
+ .getItemCount() - 1);
+ }
+ }
+
+ private void handleAddAll() {
+ ArrayList<Object> data = new ArrayList<Object>();
+ for (TableItem item : fAvailableViewer.getTable().getItems()) {
+ data.add(item.getData());
+ }
+
+ if (data.size() > 0) {
+ Object[] datas = data.toArray();
+ setBlockSelectionListeners(true);
+ setRedraw(false);
+ for (int i = 0; i < datas.length; i++) {
+ doAdd(datas[i]);
+ }
+ setRedraw(true);
+ setBlockSelectionListeners(false);
+ }
+ }
+
+ private void handleRemove() {
+ IStructuredSelection ssel = (IStructuredSelection) fSelectedViewer
+ .getSelection();
+ if (ssel.size() > 0) {
+ Table table = fSelectedViewer.getTable();
+ int index = table.getSelectionIndices()[0];
+ Object[] selection = ssel.toArray();
+ setBlockSelectionListeners(true);
+ setRedraw(false);
+ for (int i = 0; i < selection.length; i++) {
+ doRemove(selection[i]);
+ }
+ setRedraw(true);
+ setBlockSelectionListeners(false);
+ table.setSelection(index < table.getItemCount() ? index : table
+ .getItemCount() - 1);
+ }
+ }
+
+ private void doAdd(Object o) {
+ fModelTable.removeModel(o);
+ fModelTable.addToPreselected(o);
+ fSelectedViewer.add(o);
+ fAvailableViewer.remove(o);
+ fSelected.put(o, null);
+ listChanged(true, false);
+ }
+
+ private void doRemove(Object o) {
+ fModelTable.addModel(o);
+ fModelTable.removeFromPreselected(o);
+ fSelected.remove(o);
+ fSelectedViewer.remove(o);
+ fAvailableViewer.add(o);
+ listChanged(false, true);
+ }
+
+ private void listChanged(boolean doAddEnablement, boolean doRemoveEnablement) {
+ updateCount();
+ updateButtonEnablement(doAddEnablement, doRemoveEnablement);
+ fParentPage
+ .setPageComplete(fSelectedViewer.getTable().getItemCount() > 0);
+ }
+
+ public boolean hasSelectedItems() {
+ if (fSelectedViewer.getTable().getItems().length > 0) {
+ return true;
+ }
+ return false;
+ }
+
+ private void handleRemoveAll() {
+ ArrayList<Object> data = new ArrayList<Object>();
+ for (TableItem item : fSelectedViewer.getTable().getItems()) {
+ data.add(item.getData());
+ }
+ if (data.size() > 0) {
+ Object[] datas = data.toArray();
+ setBlockSelectionListeners(true);
+ setRedraw(false);
+ for (int i = 0; i < datas.length; i++) {
+ doRemove(datas[i]);
+ }
+ setRedraw(true);
+ setBlockSelectionListeners(false);
+ }
+ }
+
+ private void setBlockSelectionListeners(boolean blockSelectionListeners) {
+ fBlockSelectionListeners = blockSelectionListeners;
+ }
+
+ private void setRedraw(boolean redraw) {
+ fAvailableViewer.getTable().setRedraw(redraw);
+ fSelectedViewer.getTable().setRedraw(redraw);
+ }
+
+ protected void updateCount() {
+ Integer numAvailable = new Integer(fAvailableViewer.getTable()
+ .getItemCount() + fSelectedViewer.getTable().getItemCount());
+ Integer numSelected = new Integer(fSelectedViewer.getTable()
+ .getItemCount());
+
+ fCountLabel.setText(numSelected.toString()
+ + " of " + numAvailable.toString() + " selected"); //$NON-NLS-1$ //$NON-NLS-2$
+ fCountLabel.getParent().layout();
+ }
+
+ protected void updateButtonEnablement(boolean doAddEnablement,
+ boolean doRemoveEnablement) {
+ int availableCount = fAvailableViewer.getTable().getItemCount();
+ int selectedCount = fSelectedViewer.getTable().getItemCount();
+
+ fAddAllButton.setEnabled(availableCount > 0);
+ fRemoveAllButton.setEnabled(selectedCount > 0);
+
+ if (!(availableCount > 0) && fAddButton.isEnabled()) {
+ fAddButton.setEnabled(false);
+ }
+ if (!(selectedCount > 0) && fRemoveButton.isEnabled()) {
+ fRemoveButton.setEnabled(false);
+ }
+ }
+
+ private void updateSelectionBasedEnablement(ISelection theSelection,
+ boolean available) {
+ if (available) {
+ fAddButton.setEnabled(!theSelection.isEmpty());
+ } else {
+ fRemoveButton.setEnabled(!theSelection.isEmpty());
+ }
+ }
+
+ protected void initialize() {
+ if (fEnabled) {
+ updateButtonEnablement(true, true);
+ }
+ // setPageComplete(false);
+ }
+
+ protected void addViewerListeners() {
+ fAvailableViewer.addDoubleClickListener(new IDoubleClickListener() {
+ public void doubleClick(DoubleClickEvent event) {
+ handleAdd();
+ }
+ });
+
+ fSelectedViewer.addDoubleClickListener(new IDoubleClickListener() {
+ public void doubleClick(DoubleClickEvent event) {
+ handleRemove();
+ }
+ });
+
+ fAvailableViewer
+ .addSelectionChangedListener(new ISelectionChangedListener() {
+ public void selectionChanged(SelectionChangedEvent event) {
+ if (!fBlockSelectionListeners)
+ updateSelectionBasedEnablement(
+ event.getSelection(), true);
+ }
+ });
+
+ fSelectedViewer
+ .addSelectionChangedListener(new ISelectionChangedListener() {
+ public void selectionChanged(SelectionChangedEvent event) {
+ if (!fBlockSelectionListeners)
+ updateSelectionBasedEnablement(
+ event.getSelection(), false);
+ }
+ });
+
+ fFilterText.addModifyListener(new ModifyListener() {
+ public void modifyText(ModifyEvent e) {
+ fFilterJob.cancel();
+ fFilterJob.schedule(0);
+ }
+ });
+ }
+
+ public void setEnabled(boolean enabled) {
+ fFilterText.setEnabled(enabled);
+ fAddButton.setEnabled(enabled);
+ fRemoveButton.setEnabled(enabled);
+ fAddAllButton.setEnabled(enabled);
+ fRemoveAllButton.setEnabled(enabled);
+ fAvailableViewer.getControl().setEnabled(enabled);
+ fSelectedViewer.getControl().setEnabled(enabled);
+ if (enabled) {
+ updateButtonEnablement(false, false);
+ // fParentPage.setPageComplete(fSelectedViewer.getTable().getItemCount()
+ // > 0);
+ }
+ fEnabled = enabled;
+ }
+
+ public TableViewer getSelectedViewer() {
+ return fSelectedViewer;
+ }
+
+ public Object[] getSelected() {
+ return fModelTable.getPreSelected();
+ }
+
+ public boolean isEnabled() {
+ return fEnabled;
+ }
}
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/LanguagePackFilterDialog.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/LanguagePackFilterDialog.java
index 19493c2..eaa3404 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/LanguagePackFilterDialog.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/LanguagePackFilterDialog.java
@@ -13,14 +13,15 @@
import org.eclipse.swt.widgets.Shell;
public class LanguagePackFilterDialog extends FilterDialog {
-
- public LanguagePackFilterDialog(final Shell parent, final BuildToolWizardConfigurationPage caller) {
- super(parent, caller);
-
- parent.setText(Messages.getString("LanguagePackFilterDialog_Title"));
- }
-
- protected void setChosenFilter(String filter) {
- fCallingPage.setLanguagePackFilter(filter);
- }
+
+ public LanguagePackFilterDialog(final Shell parent,
+ final BuildToolWizardConfigurationPage caller) {
+ super(parent, caller);
+
+ parent.setText(Messages.getString("LanguagePackFilterDialog_Title"));
+ }
+
+ protected void setChosenFilter(String filter) {
+ fCallingPage.setLanguagePackFilter(filter);
+ }
}
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/LanguagePackGenerationHandler.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/LanguagePackGenerationHandler.java
index c7eeac0..41ca915 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/LanguagePackGenerationHandler.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/LanguagePackGenerationHandler.java
@@ -32,216 +32,210 @@
import org.eclipse.pde.core.plugin.IPluginModelBase;
public class LanguagePackGenerationHandler {
-
- private List<File> fSelectedPlugins;
- private File fEclipseArchiveLocation;
-
- private List<String> fSelectedLocales;
-
- private File fWorkingDirectoryLocation;
- private File fTranslationCatalogueLocation;
- private Set<String> fExcludeList;
- private List<String> fReportFilterPatterns;
- private boolean fIncludeXmlReport;
- private boolean fLongReport;
-
- private String fErrorMessage = "";
-
- public LanguagePackGenerationHandler(Object[] selectedPlugins,
- String[] selectedLocales,
- String workingDirectoryLocation,
- String translationCataloguelocation,
- Object[] ignoreList,
- Object[] reportFilterPatterns,
- boolean includeXmlReport,
- boolean longReport) {
- this.fIncludeXmlReport = includeXmlReport;
- this.fLongReport = longReport;
- this.fSelectedPlugins = new ArrayList<File>();
- getPluginLocations(selectedPlugins);
- this.fEclipseArchiveLocation = null;
- this.fSelectedLocales = Arrays.asList(selectedLocales);
- this.fWorkingDirectoryLocation = new File(workingDirectoryLocation);
- this.fTranslationCatalogueLocation = new File(translationCataloguelocation);
-
- this.fExcludeList = new HashSet<String>();
- for(int i=0; i<ignoreList.length; i++) {
- this.fExcludeList.add(ignoreList[i].toString());
- }
-
- this.fReportFilterPatterns = new ArrayList<String>();
- for(Object pattern : reportFilterPatterns) {
- this.fReportFilterPatterns.add(pattern.toString());
- }
- }
-
- public LanguagePackGenerationHandler(String eclipseArchivePath,
- String[] selectedLocales,
- String workingDirectoryLocation,
- String translationCataloguelocation,
- Object[] ignoreList,
- Object[] reportFilterPatterns,
- boolean includeXmlReport,
- boolean longReport) {
- this.fIncludeXmlReport = includeXmlReport;
- this.fLongReport = longReport;
- this.fSelectedPlugins = null;
- this.fEclipseArchiveLocation = new File(eclipseArchivePath);
- this.fSelectedLocales = Arrays.asList(selectedLocales);
- this.fWorkingDirectoryLocation = new File(workingDirectoryLocation);
- this.fTranslationCatalogueLocation = new File(translationCataloguelocation);
-
- this.fExcludeList = new HashSet<String>();
- for(int i=0; i<ignoreList.length; i++) {
- this.fExcludeList.add(ignoreList[i].toString());
- }
-
- this.fReportFilterPatterns = new ArrayList<String>();
- for(Object pattern : reportFilterPatterns) {
- this.fReportFilterPatterns.add(pattern.toString());
- }
- }
-
- public String generateLanguagePack(IProgressMonitor monitor) {
- UserInterfaceConfiguration config;
- monitor.beginTask(Messages.getString("LanguagePackGenerationHandler_EclipseParsingTask"), IProgressMonitor.UNKNOWN);
- if(fSelectedPlugins == null) {
- config = new UserInterfaceConfiguration(fWorkingDirectoryLocation,
- fTranslationCatalogueLocation,
- fEclipseArchiveLocation,
- fSelectedLocales,
- fExcludeList,
- fReportFilterPatterns,
- this,
- fIncludeXmlReport,
- fLongReport);
- }
- else {
- List<PluginProxy> pluginProxies = getPluginProxies();
- config = new UserInterfaceConfiguration(fWorkingDirectoryLocation,
- fTranslationCatalogueLocation,
- pluginProxies,
- fSelectedLocales,
- fExcludeList,
- fReportFilterPatterns,
- this,
- fIncludeXmlReport,
- fLongReport);
- }
- try {
- int totalWork = config.eclipseInstall().getPlugins().size() + config.eclipseInstall().getFeatures().size();
- totalWork = totalWork + (int)(totalWork*0.2);
- monitor.beginTask(Messages.getString("LanguagePackGenerationHandler_LanguagePackTask"), totalWork);
- config.setProgressMonitor(monitor);
-
- // Generate a language pack
- LanguagePack languagePack = new LanguagePack(config);
- LanguagePackCoverageReport coverage;
- coverage = languagePack.generate();
-
- // Create coverage reports
- monitor.subTask(Messages.getString("LanguagePackGenerationHandler_CoverageReportTask"));
- Configuration.helper.printLanguagePackResult(config, coverage);
- monitor.done();
- } catch (InvalidFilenameException f) {
- return Messages.getString("Error_InvalidWorkingDirectoryName");
- } catch (FailedDeletionException f) {
- return Messages.getString("Error_DeletingWorkingDirectory"); //$NON-NLS-1$
- }
- catch (Exception e) {
- if (fErrorMessage.equals("")) {
- fErrorMessage = Messages.getString("Error_LanguagePack");
- }
- return fErrorMessage;
- }
- return "";
- }
-
- private void getPluginLocations(Object[] plugins) {
- for(Object plugin : plugins) {
- String pluginPath = ((IPluginModelBase) plugin).getInstallLocation();
- fSelectedPlugins.add(new File(pluginPath));
- }
- }
-
- private List<PluginProxy> getPluginProxies() {
- PluginProxy newPlugin;
- List<PluginProxy> plugins = new ArrayList<PluginProxy>();
- for (File plugin: fSelectedPlugins) {
- List<ResourceProxy> pluginResources;
- if(plugin.isDirectory()) {
- pluginResources = extractResources(plugin, plugin.getName());
- newPlugin = new PluginProxy(plugin, pluginResources, false, false);
- plugins.add(newPlugin);
- } else {
- //Handle JAR Plug-in
- pluginResources = extractResourcesFromJar(plugin);
- newPlugin = new PluginProxy(plugin, pluginResources, true, false);
- plugins.add(newPlugin);
- }
- }
- return plugins;
- }
-
- private List<ResourceProxy> extractResources(File file, String pluginName) {
- List<ResourceProxy> resources = new LinkedList<ResourceProxy>();
- for (File subFile: file.listFiles()) {
- if (subFile.isDirectory()) {
- resources.addAll(extractResources(subFile, pluginName));
- }
- else {
- String absolutePath = subFile.getAbsolutePath();
- String relativePath = absolutePath.substring(absolutePath.indexOf(pluginName));
- relativePath = relativePath.substring(pluginName.length() + 1);
- resources.add(new ResourceProxy(subFile, relativePath));
- }
- }
- return resources;
- }
- private List<ResourceProxy> extractResourcesFromJar(File file) {
- List<ResourceProxy> jarResources = new LinkedList<ResourceProxy>();
-
- try {
- JarFile jarPluginOrFeature = new JarFile(file);
-
- Enumeration<JarEntry> jarEntries = jarPluginOrFeature.entries();
-
- JarEntry jarEntry = jarEntries.nextElement();
- while (jarEntry != null) {
- String resourceEntryName = jarEntry.getName();
-
- if ( isValidResource(resourceEntryName) ) {
- jarResources.add(new ResourceProxy(
- new File(file.getAbsolutePath() + File.separator
- + resourceEntryName), resourceEntryName)); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- if (jarEntries.hasMoreElements()) {
- jarEntry = jarEntries.nextElement();
- } else {
- jarEntry = null;
- }
- }
-
- } catch (Exception e) {
- System.out.println(e.getMessage());
- }
-
- return jarResources;
- }
-
- private boolean isValidResource(String resourceEntryName) {
- for (String exclude : this.fExcludeList) {
- if (resourceEntryName.endsWith(exclude)) {
- return false;
- }
- }
- return true;
- }
-
- public void notifyError(String errorMessage) {
- fErrorMessage = errorMessage;
- }
+ private List<File> fSelectedPlugins;
+ private File fEclipseArchiveLocation;
+
+ private List<String> fSelectedLocales;
+
+ private File fWorkingDirectoryLocation;
+ private File fTranslationCatalogueLocation;
+ private Set<String> fExcludeList;
+ private List<String> fReportFilterPatterns;
+ private boolean fIncludeXmlReport;
+ private boolean fLongReport;
+
+ private String fErrorMessage = "";
+
+ public LanguagePackGenerationHandler(Object[] selectedPlugins,
+ String[] selectedLocales, String workingDirectoryLocation,
+ String translationCataloguelocation, Object[] ignoreList,
+ Object[] reportFilterPatterns, boolean includeXmlReport,
+ boolean longReport) {
+ this.fIncludeXmlReport = includeXmlReport;
+ this.fLongReport = longReport;
+ this.fSelectedPlugins = new ArrayList<File>();
+ getPluginLocations(selectedPlugins);
+ this.fEclipseArchiveLocation = null;
+ this.fSelectedLocales = Arrays.asList(selectedLocales);
+ this.fWorkingDirectoryLocation = new File(workingDirectoryLocation);
+ this.fTranslationCatalogueLocation = new File(
+ translationCataloguelocation);
+
+ this.fExcludeList = new HashSet<String>();
+ for (int i = 0; i < ignoreList.length; i++) {
+ this.fExcludeList.add(ignoreList[i].toString());
+ }
+
+ this.fReportFilterPatterns = new ArrayList<String>();
+ for (Object pattern : reportFilterPatterns) {
+ this.fReportFilterPatterns.add(pattern.toString());
+ }
+ }
+
+ public LanguagePackGenerationHandler(String eclipseArchivePath,
+ String[] selectedLocales, String workingDirectoryLocation,
+ String translationCataloguelocation, Object[] ignoreList,
+ Object[] reportFilterPatterns, boolean includeXmlReport,
+ boolean longReport) {
+ this.fIncludeXmlReport = includeXmlReport;
+ this.fLongReport = longReport;
+ this.fSelectedPlugins = null;
+ this.fEclipseArchiveLocation = new File(eclipseArchivePath);
+ this.fSelectedLocales = Arrays.asList(selectedLocales);
+ this.fWorkingDirectoryLocation = new File(workingDirectoryLocation);
+ this.fTranslationCatalogueLocation = new File(
+ translationCataloguelocation);
+
+ this.fExcludeList = new HashSet<String>();
+ for (int i = 0; i < ignoreList.length; i++) {
+ this.fExcludeList.add(ignoreList[i].toString());
+ }
+
+ this.fReportFilterPatterns = new ArrayList<String>();
+ for (Object pattern : reportFilterPatterns) {
+ this.fReportFilterPatterns.add(pattern.toString());
+ }
+ }
+
+ public String generateLanguagePack(IProgressMonitor monitor) {
+ UserInterfaceConfiguration config;
+ monitor.beginTask(Messages
+ .getString("LanguagePackGenerationHandler_EclipseParsingTask"),
+ IProgressMonitor.UNKNOWN);
+ if (fSelectedPlugins == null) {
+ config = new UserInterfaceConfiguration(fWorkingDirectoryLocation,
+ fTranslationCatalogueLocation, fEclipseArchiveLocation,
+ fSelectedLocales, fExcludeList, fReportFilterPatterns,
+ this, fIncludeXmlReport, fLongReport);
+ } else {
+ List<PluginProxy> pluginProxies = getPluginProxies();
+ config = new UserInterfaceConfiguration(fWorkingDirectoryLocation,
+ fTranslationCatalogueLocation, pluginProxies,
+ fSelectedLocales, fExcludeList, fReportFilterPatterns,
+ this, fIncludeXmlReport, fLongReport);
+ }
+ try {
+ int totalWork = config.eclipseInstall().getPlugins().size()
+ + config.eclipseInstall().getFeatures().size();
+ totalWork = totalWork + (int) (totalWork * 0.2);
+ monitor.beginTask(
+ Messages.getString("LanguagePackGenerationHandler_LanguagePackTask"),
+ totalWork);
+ config.setProgressMonitor(monitor);
+
+ // Generate a language pack
+ LanguagePack languagePack = new LanguagePack(config);
+ LanguagePackCoverageReport coverage;
+ coverage = languagePack.generate();
+
+ // Create coverage reports
+ monitor.subTask(Messages
+ .getString("LanguagePackGenerationHandler_CoverageReportTask"));
+ Configuration.helper.printLanguagePackResult(config, coverage);
+ monitor.done();
+ } catch (InvalidFilenameException f) {
+ return Messages.getString("Error_InvalidWorkingDirectoryName");
+ } catch (FailedDeletionException f) {
+ return Messages.getString("Error_DeletingWorkingDirectory"); //$NON-NLS-1$
+ } catch (Exception e) {
+ if (fErrorMessage.equals("")) {
+ fErrorMessage = Messages.getString("Error_LanguagePack");
+ }
+ return fErrorMessage;
+ }
+ return "";
+ }
+
+ private void getPluginLocations(Object[] plugins) {
+ for (Object plugin : plugins) {
+ String pluginPath = ((IPluginModelBase) plugin)
+ .getInstallLocation();
+ fSelectedPlugins.add(new File(pluginPath));
+ }
+ }
+
+ private List<PluginProxy> getPluginProxies() {
+ PluginProxy newPlugin;
+ List<PluginProxy> plugins = new ArrayList<PluginProxy>();
+ for (File plugin : fSelectedPlugins) {
+ List<ResourceProxy> pluginResources;
+ if (plugin.isDirectory()) {
+ pluginResources = extractResources(plugin, plugin.getName());
+ newPlugin = new PluginProxy(plugin, pluginResources, false,
+ false);
+ plugins.add(newPlugin);
+ } else {
+ // Handle JAR Plug-in
+ pluginResources = extractResourcesFromJar(plugin);
+ newPlugin = new PluginProxy(plugin, pluginResources, true,
+ false);
+ plugins.add(newPlugin);
+ }
+ }
+ return plugins;
+ }
+
+ private List<ResourceProxy> extractResources(File file, String pluginName) {
+ List<ResourceProxy> resources = new LinkedList<ResourceProxy>();
+ for (File subFile : file.listFiles()) {
+ if (subFile.isDirectory()) {
+ resources.addAll(extractResources(subFile, pluginName));
+ } else {
+ String absolutePath = subFile.getAbsolutePath();
+ String relativePath = absolutePath.substring(absolutePath
+ .indexOf(pluginName));
+ relativePath = relativePath.substring(pluginName.length() + 1);
+ resources.add(new ResourceProxy(subFile, relativePath));
+ }
+ }
+ return resources;
+ }
+
+ private List<ResourceProxy> extractResourcesFromJar(File file) {
+ List<ResourceProxy> jarResources = new LinkedList<ResourceProxy>();
+
+ try {
+ JarFile jarPluginOrFeature = new JarFile(file);
+
+ Enumeration<JarEntry> jarEntries = jarPluginOrFeature.entries();
+
+ JarEntry jarEntry = jarEntries.nextElement();
+ while (jarEntry != null) {
+ String resourceEntryName = jarEntry.getName();
+
+ if (isValidResource(resourceEntryName)) {
+ jarResources.add(new ResourceProxy(new File(file
+ .getAbsolutePath()
+ + File.separator
+ + resourceEntryName), resourceEntryName)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ if (jarEntries.hasMoreElements()) {
+ jarEntry = jarEntries.nextElement();
+ } else {
+ jarEntry = null;
+ }
+ }
+
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+
+ return jarResources;
+ }
+
+ private boolean isValidResource(String resourceEntryName) {
+ for (String exclude : this.fExcludeList) {
+ if (resourceEntryName.endsWith(exclude)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public void notifyError(String errorMessage) {
+ fErrorMessage = errorMessage;
+ }
}
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/ListFilter.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/ListFilter.java
index 5431795..af4e817 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/ListFilter.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/ListFilter.java
@@ -17,83 +17,93 @@
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
-public class ListFilter extends ViewerFilter{
- public static final String WILDCARD = "*"; //$NON-NLS-1$
- private Pattern fPattern;
-
- private final Map<Object, Object> fSelected;
- private final ILabelProvider fLabelProvider;
+public class ListFilter extends ViewerFilter {
+ public static final String WILDCARD = "*"; //$NON-NLS-1$
+ private Pattern fPattern;
- public ListFilter(Map<Object, Object> selected, ILabelProvider labelProvider) {
- setPattern(WILDCARD);
- this.fSelected = selected;
- this.fLabelProvider = labelProvider;
- }
+ private final Map<Object, Object> fSelected;
+ private final ILabelProvider fLabelProvider;
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- // filter out any items that are currently selected
- // on a full refresh, these will have been added back to the list
- if (fSelected.containsKey(element))
- return false;
+ public ListFilter(Map<Object, Object> selected, ILabelProvider labelProvider) {
+ setPattern(WILDCARD);
+ this.fSelected = selected;
+ this.fLabelProvider = labelProvider;
+ }
- String displayName = fLabelProvider.getText(element);
- return matches(element.toString()) || matches(displayName);
- }
+ public boolean select(Viewer viewer, Object parentElement, Object element) {
+ // filter out any items that are currently selected
+ // on a full refresh, these will have been added back to the list
+ if (fSelected.containsKey(element))
+ return false;
- private boolean matches(String s) {
- return fPattern.matcher(s.toLowerCase()).matches();
- }
+ String displayName = fLabelProvider.getText(element);
+ return matches(element.toString()) || matches(displayName);
+ }
- public boolean setPattern(String pattern) {
- String newPattern = pattern.toLowerCase();
+ private boolean matches(String s) {
+ return fPattern.matcher(s.toLowerCase()).matches();
+ }
- if (!newPattern.endsWith(WILDCARD))
- newPattern += WILDCARD;
- if (!newPattern.startsWith(WILDCARD))
- newPattern = WILDCARD + newPattern;
- if (fPattern != null) {
- String oldPattern = fPattern.pattern();
- if (newPattern.equals(oldPattern))
- return false;
- }
- fPattern = PatternConstructor.createPattern(newPattern, true);
- return true;
- }
+ public boolean setPattern(String pattern) {
+ String newPattern = pattern.toLowerCase();
- private static class PatternConstructor {
- private static final Pattern PATTERN_BACK_SLASH = Pattern.compile("\\\\"); //$NON-NLS-1$
- private static final Pattern PATTERN_QUESTION = Pattern.compile("\\?"); //$NON-NLS-1$
- private static final Pattern PATTERN_STAR = Pattern.compile("\\*"); //$NON-NLS-1$
- private static final Pattern PATTERN_LBRACKET = Pattern.compile("\\("); //$NON-NLS-1$
- private static final Pattern PATTERN_RBRACKET = Pattern.compile("\\)"); //$NON-NLS-1$
+ if (!newPattern.endsWith(WILDCARD))
+ newPattern += WILDCARD;
+ if (!newPattern.startsWith(WILDCARD))
+ newPattern = WILDCARD + newPattern;
+ if (fPattern != null) {
+ String oldPattern = fPattern.pattern();
+ if (newPattern.equals(oldPattern))
+ return false;
+ }
+ fPattern = PatternConstructor.createPattern(newPattern, true);
+ return true;
+ }
- private static String asRegEx(String pattern, boolean group) {
- // Replace \ with \\, * with .* and ? with .
- // Quote remaining characters
- String result1 = PATTERN_BACK_SLASH.matcher(pattern).replaceAll("\\\\E\\\\\\\\\\\\Q"); //$NON-NLS-1$
- String result2 = PATTERN_STAR.matcher(result1).replaceAll("\\\\E.*\\\\Q"); //$NON-NLS-1$
- String result3 = PATTERN_QUESTION.matcher(result2).replaceAll("\\\\E.\\\\Q"); //$NON-NLS-1$
- if (group) {
- result3 = PATTERN_LBRACKET.matcher(result3).replaceAll("\\\\E(\\\\Q"); //$NON-NLS-1$
- result3 = PATTERN_RBRACKET.matcher(result3).replaceAll("\\\\E)\\\\Q"); //$NON-NLS-1$
- }
- return "\\Q" + result3 + "\\E"; //$NON-NLS-1$ //$NON-NLS-2$
- }
+ private static class PatternConstructor {
+ private static final Pattern PATTERN_BACK_SLASH = Pattern
+ .compile("\\\\"); //$NON-NLS-1$
+ private static final Pattern PATTERN_QUESTION = Pattern.compile("\\?"); //$NON-NLS-1$
+ private static final Pattern PATTERN_STAR = Pattern.compile("\\*"); //$NON-NLS-1$
+ private static final Pattern PATTERN_LBRACKET = Pattern.compile("\\("); //$NON-NLS-1$
+ private static final Pattern PATTERN_RBRACKET = Pattern.compile("\\)"); //$NON-NLS-1$
- public static Pattern createPattern(String pattern, boolean isCaseSensitive) {
- if (isCaseSensitive)
- return Pattern.compile(asRegEx(pattern, false));
- return Pattern.compile(asRegEx(pattern, false), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
- }
+ private static String asRegEx(String pattern, boolean group) {
+ // Replace \ with \\, * with .* and ? with .
+ // Quote remaining characters
+ String result1 = PATTERN_BACK_SLASH.matcher(pattern).replaceAll(
+ "\\\\E\\\\\\\\\\\\Q"); //$NON-NLS-1$
+ String result2 = PATTERN_STAR.matcher(result1).replaceAll(
+ "\\\\E.*\\\\Q"); //$NON-NLS-1$
+ String result3 = PATTERN_QUESTION.matcher(result2).replaceAll(
+ "\\\\E.\\\\Q"); //$NON-NLS-1$
+ if (group) {
+ result3 = PATTERN_LBRACKET.matcher(result3).replaceAll(
+ "\\\\E(\\\\Q"); //$NON-NLS-1$
+ result3 = PATTERN_RBRACKET.matcher(result3).replaceAll(
+ "\\\\E)\\\\Q"); //$NON-NLS-1$
+ }
+ return "\\Q" + result3 + "\\E"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
- public static Pattern createGroupedPattern(String pattern, boolean isCaseSensitive) {
- if (isCaseSensitive)
- return Pattern.compile(asRegEx(pattern, true));
- return Pattern.compile(asRegEx(pattern, true), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
- }
+ public static Pattern createPattern(String pattern,
+ boolean isCaseSensitive) {
+ if (isCaseSensitive)
+ return Pattern.compile(asRegEx(pattern, false));
+ return Pattern.compile(asRegEx(pattern, false),
+ Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
+ }
- private PatternConstructor() {
- }
- }
+ public static Pattern createGroupedPattern(String pattern,
+ boolean isCaseSensitive) {
+ if (isCaseSensitive)
+ return Pattern.compile(asRegEx(pattern, true));
+ return Pattern.compile(asRegEx(pattern, true),
+ Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
+ }
+
+ private PatternConstructor() {
+ }
+ }
}
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/LocaleLabelProvider.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/LocaleLabelProvider.java
index 401f80c..b834269 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/LocaleLabelProvider.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/LocaleLabelProvider.java
@@ -15,33 +15,33 @@
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Image;
-public class LocaleLabelProvider extends LabelProvider{
- public LocaleLabelProvider() {
- }
-
- @Override
- public Image getImage(Object element) {
- //return BuildToolImages.LOCALE.createImage();
- return null;
- }
+public class LocaleLabelProvider extends LabelProvider {
+ public LocaleLabelProvider() {
+ }
- @Override
- public String getText(Object element) {
- Locale locale = (Locale) element;
- String country = locale.getDisplayCountry();
- String varient = locale.getDisplayVariant();
-
- return locale.getDisplayLanguage() + " " + getDisplay(country, varient); //$NON-NLS-1$
- }
+ @Override
+ public Image getImage(Object element) {
+ // return BuildToolImages.LOCALE.createImage();
+ return null;
+ }
- private String getDisplay(String country, String varient) {
- if("".equals(country)){
- return "";
- }
-
- if("".equals(varient)){
- return String.format("(%s)", country);
- }
- return String.format("(%s: %s)", country, varient);
- }
+ @Override
+ public String getText(Object element) {
+ Locale locale = (Locale) element;
+ String country = locale.getDisplayCountry();
+ String varient = locale.getDisplayVariant();
+
+ return locale.getDisplayLanguage() + " " + getDisplay(country, varient); //$NON-NLS-1$
+ }
+
+ private String getDisplay(String country, String varient) {
+ if ("".equals(country)) {
+ return "";
+ }
+
+ if ("".equals(varient)) {
+ return String.format("(%s)", country);
+ }
+ return String.format("(%s: %s)", country, varient);
+ }
}
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/Messages.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/Messages.java
index 3aca892..4045ffc 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/Messages.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/Messages.java
@@ -14,18 +14,19 @@
import java.util.ResourceBundle;
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.babel.build.ui.wizard.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.babel.build.ui.wizard.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/PluginLabelProvider.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/PluginLabelProvider.java
index adff36b..f46904c 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/PluginLabelProvider.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/PluginLabelProvider.java
@@ -13,19 +13,19 @@
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Image;
-public class PluginLabelProvider extends LabelProvider{
+public class PluginLabelProvider extends LabelProvider {
- public PluginLabelProvider() {
- }
-
- @Override
- public Image getImage(Object element) {
- //return BuildToolImages.PLUGIN.createImage();
- return null;
- }
+ public PluginLabelProvider() {
+ }
- @Override
- public String getText(Object element) {
- return element == null ? "" : element.toString(); //$NON-NLS-1$
- }
+ @Override
+ public Image getImage(Object element) {
+ // return BuildToolImages.PLUGIN.createImage();
+ return null;
+ }
+
+ @Override
+ public String getText(Object element) {
+ return element == null ? "" : element.toString(); //$NON-NLS-1$
+ }
}
diff --git a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/UserInterfaceConfiguration.java b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/UserInterfaceConfiguration.java
index 758ee3b..d8ef265 100644
--- a/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/UserInterfaceConfiguration.java
+++ b/org.eclipse.babel.build.ui/src/org/eclipse/babel/build/ui/wizard/UserInterfaceConfiguration.java
@@ -34,244 +34,250 @@
public class UserInterfaceConfiguration implements Configuration {
- private IProgressMonitor fMonitor;
-
- private final File fWorkingDirectory;
- private final File fEclipseRoot;
- private final File fTranslationsRoot;
-
- private EclipseTarget fEclipseTarget = null;
- private TranslationCatalogue fTranslationCatalogue = null;
-
- private final List<PluginProxy> fPluginProxies;
- private final Set<LocaleProxy> fLocales;
- private final Set<LocaleGroup> fLocaleGroups;
- private final Set<String> fExcludeList;
- private List<Filter> fReportFilters;
- private File fReport;
- private final LanguagePackGenerationHandler fParentHandler;
- private final boolean fIncludeXmlReport;
- private final boolean fLongReport;
- private String fLocaleExtension;
+ private IProgressMonitor fMonitor;
-
- public UserInterfaceConfiguration(File workingDirectoryPath,
- File translationCatalogueLocation,
- File eclipseArchiveLocation,
- List<String> locales,
- Set<String> excludeList,
- List<String> reportFilterPatterns,
- LanguagePackGenerationHandler parentHandler,
- boolean includeXmlReport,
- boolean longReport) {
- this.fIncludeXmlReport = includeXmlReport;
- this.fLongReport = longReport;
- this.fParentHandler = parentHandler;
- this.fWorkingDirectory = workingDirectoryPath;
- this.fEclipseRoot = eclipseArchiveLocation;
- this.fTranslationsRoot = translationCatalogueLocation;
- this.fPluginProxies = null;
-
- this.fLocales = getLocaleProxies(locales);
- this.fLocaleGroups = getLocaleGroups(locales);
-
- this.fExcludeList = excludeList;
- this.fReport = new File(fWorkingDirectory, "coverage.xml");
- this.fReportFilters = buildFilterList(reportFilterPatterns);
- eclipseInstall();
-
- fLocaleExtension = "";
- if (this.fLocales.size() == 1 && this.fLocaleGroups.isEmpty()) {
- LocaleProxy singleLocale = this.fLocales.iterator().next();
- fLocaleExtension += Messages.getString("Characters_Underscore") + singleLocale.getName(); //$NON-NLS-1$
- }
- }
-
- public UserInterfaceConfiguration(File workingDirectoryPath,
- File translationCatalogueLocation,
- List<PluginProxy> pluginProxies,
- List<String> locales,
- Set<String> excludeList,
- List<String> reportFilterPatterns,
- LanguagePackGenerationHandler parentHandler,
- boolean includeXmlReport,
- boolean longReport) {
- this.fIncludeXmlReport = includeXmlReport;
- this.fLongReport = longReport;
- this.fParentHandler = parentHandler;
- this.fWorkingDirectory = workingDirectoryPath;
- this.fEclipseRoot = null;
- this.fTranslationsRoot = translationCatalogueLocation;
- this.fPluginProxies = pluginProxies;
-
- this.fLocales = getLocaleProxies(locales);
- this.fLocaleGroups = getLocaleGroups(locales);
-
- this.fExcludeList = excludeList;
- this.fReport = new File(fWorkingDirectory, "coverage.xml");
- this.fReportFilters = buildFilterList(reportFilterPatterns);
- eclipseInstall();
-
- fLocaleExtension = "";
- if (this.fLocales.size() == 1 && this.fLocaleGroups.isEmpty()) {
- LocaleProxy singleLocale = this.fLocales.iterator().next();
- fLocaleExtension += Messages.getString("Characters_Underscore") + singleLocale.getName(); //$NON-NLS-1$
- }
- }
-
- private List<Filter> buildFilterList(List<String> filterPatterns){
- List<Filter> filters = new LinkedList<Filter>();
- for(String pattern : filterPatterns){
- filters.add(new Filter(pattern));
- }
- return filters;
- }
-
- private static Set<LocaleProxy> getLocaleProxies(List<String> localeNames){
- Set<LocaleProxy> locales = new HashSet<LocaleProxy>();
- for(String localeName : localeNames){
- if (! LocaleGroup.isValidGroupName(localeName) && !LocaleGroup.isValidGroupFullName(localeName)){
- locales.add(new LocaleProxy(localeName));
- }
- }
-
- return locales;
- }
-
- private static Set<LocaleGroup> getLocaleGroups(List<String> locales){
- Set<LocaleGroup> set = new HashSet<LocaleGroup>();
- for(String localeName : locales){
- if (LocaleGroup.isValidGroupName(localeName)) {
- set.add(LocaleGroup.get(localeName));
- }
- else if(LocaleGroup.isValidGroupFullName(localeName)) {
- set.add(LocaleGroup.getByFullName(localeName));
- }
- }
- return set;
- }
-
- public Range compatibilityRange() {
- // TODO Auto-generated method stub
- return null;
- }
+ private final File fWorkingDirectory;
+ private final File fEclipseRoot;
+ private final File fTranslationsRoot;
- public EclipseTarget eclipseInstall() {
- try {
- if (fEclipseTarget == null){
- if(fEclipseRoot == null) {
- fEclipseTarget = new EclipseTarget(fPluginProxies);
- }
- else {
- fEclipseTarget = new EclipseTarget(fEclipseRoot, fExcludeList);
- fEclipseTarget.populatePlugins();
- }
- }
- } catch (InvalidLocationException i) {
- fParentHandler.notifyError(Messages.getString("Error_InvalidEclipseTarget") + Messages.getString("Error_EclipseEntryLocation") + fEclipseRoot); //$NON-NLS-1$
- return null;
- } catch (MissingLocationException m) {
- fParentHandler.notifyError(Messages.getString("Error_MissingEclipseTarget") + Messages.getString("Error_EclipseEntryLocation") + fEclipseRoot); //$NON-NLS-1$
- return null;
- } catch(InvalidFilenameException f) {
- fParentHandler.notifyError(Messages.getString("Error_InvalidEclipseTargetName") + Messages.getString("Error_EclipseEntryLocation") + fEclipseRoot); //$NON-NLS-1$
- return null;
- } catch (Exception e) {
- fParentHandler.notifyError(Messages.getString("Error_EclipseTarget") + Messages.getString("Error_EclipseEntryLocation") + fEclipseRoot ); //$NON-NLS-1$
- return null;
- }
- return fEclipseTarget;
- }
+ private EclipseTarget fEclipseTarget = null;
+ private TranslationCatalogue fTranslationCatalogue = null;
- public Set<String> excludeList() {
- return fExcludeList;
- }
+ private final List<PluginProxy> fPluginProxies;
+ private final Set<LocaleProxy> fLocales;
+ private final Set<LocaleGroup> fLocaleGroups;
+ private final Set<String> fExcludeList;
+ private List<Filter> fReportFilters;
+ private File fReport;
+ private final LanguagePackGenerationHandler fParentHandler;
+ private final boolean fIncludeXmlReport;
+ private final boolean fLongReport;
+ private String fLocaleExtension;
- public List<Filter> filters() {
- // TODO Auto-generated method stub
- return null;
- }
+ public UserInterfaceConfiguration(File workingDirectoryPath,
+ File translationCatalogueLocation, File eclipseArchiveLocation,
+ List<String> locales, Set<String> excludeList,
+ List<String> reportFilterPatterns,
+ LanguagePackGenerationHandler parentHandler,
+ boolean includeXmlReport, boolean longReport) {
+ this.fIncludeXmlReport = includeXmlReport;
+ this.fLongReport = longReport;
+ this.fParentHandler = parentHandler;
+ this.fWorkingDirectory = workingDirectoryPath;
+ this.fEclipseRoot = eclipseArchiveLocation;
+ this.fTranslationsRoot = translationCatalogueLocation;
+ this.fPluginProxies = null;
- public boolean includePseudoTranslations() {
- // TODO Auto-generated method stub
- return false;
- }
+ this.fLocales = getLocaleProxies(locales);
+ this.fLocaleGroups = getLocaleGroups(locales);
- public Set<LocaleGroup> localeGroups() {
- return fLocaleGroups;
- }
+ this.fExcludeList = excludeList;
+ this.fReport = new File(fWorkingDirectory, "coverage.xml");
+ this.fReportFilters = buildFilterList(reportFilterPatterns);
+ eclipseInstall();
- public Set<LocaleProxy> locales() {
- return fLocales;
- }
+ fLocaleExtension = "";
+ if (this.fLocales.size() == 1 && this.fLocaleGroups.isEmpty()) {
+ LocaleProxy singleLocale = this.fLocales.iterator().next();
+ fLocaleExtension += Messages.getString("Characters_Underscore") + singleLocale.getName(); //$NON-NLS-1$
+ }
+ }
- public File reportLocation() {
- return fReport;
- }
+ public UserInterfaceConfiguration(File workingDirectoryPath,
+ File translationCatalogueLocation, List<PluginProxy> pluginProxies,
+ List<String> locales, Set<String> excludeList,
+ List<String> reportFilterPatterns,
+ LanguagePackGenerationHandler parentHandler,
+ boolean includeXmlReport, boolean longReport) {
+ this.fIncludeXmlReport = includeXmlReport;
+ this.fLongReport = longReport;
+ this.fParentHandler = parentHandler;
+ this.fWorkingDirectory = workingDirectoryPath;
+ this.fEclipseRoot = null;
+ this.fTranslationsRoot = translationCatalogueLocation;
+ this.fPluginProxies = pluginProxies;
- public Date timestamp() {
- // TODO Auto-generated method stub
- return null;
- }
+ this.fLocales = getLocaleProxies(locales);
+ this.fLocaleGroups = getLocaleGroups(locales);
- public TranslationCatalogue translations() {
- if (fTranslationCatalogue == null){
- try {
-
- if (fLocaleGroups.isEmpty()) {
- fTranslationCatalogue = new TranslationCatalogue(fTranslationsRoot, fLocales);
- } else {
- fLocales.clear();
- fTranslationCatalogue = new TranslationCatalogue(fTranslationsRoot, fLocaleGroups);
- fLocales.addAll(fTranslationCatalogue.getAllLocales());
- }
-
- } catch (MissingLocationException m) {
- fParentHandler.notifyError(Messages.getString("Error_MissingTranslationCatalogue") + Messages.getString("Error_TranslationsEntryLocation") + fTranslationsRoot); //$NON-NLS-1$
- return null;
- } catch (InvalidLocationException i) {
- fParentHandler.notifyError(i.getMessage());
- return null;
- } catch(InvalidFilenameException f) {
- fParentHandler.notifyError(Messages.getString("Error_InvalidTranslationCatalogueName") + Messages.getString("Error_TranslationsEntryLocation") + fTranslationsRoot); //$NON-NLS-1$
- return null;
- }
- }
- return fTranslationCatalogue;
- }
+ this.fExcludeList = excludeList;
+ this.fReport = new File(fWorkingDirectory, "coverage.xml");
+ this.fReportFilters = buildFilterList(reportFilterPatterns);
+ eclipseInstall();
- public File workingDirectory() {
- return fWorkingDirectory;
- }
+ fLocaleExtension = "";
+ if (this.fLocales.size() == 1 && this.fLocaleGroups.isEmpty()) {
+ LocaleProxy singleLocale = this.fLocales.iterator().next();
+ fLocaleExtension += Messages.getString("Characters_Underscore") + singleLocale.getName(); //$NON-NLS-1$
+ }
+ }
- public boolean includeResource(PluginProxy plugin, ResourceProxy resource) {
- for(Filter filter : fReportFilters){
- if(filter.matches(plugin, resource)){
- return filter.isInclusive();
- }
- }
- return true;
- }
-
- public void setProgressMonitor(IProgressMonitor monitor) {
- this.fMonitor = monitor;
- }
+ private List<Filter> buildFilterList(List<String> filterPatterns) {
+ List<Filter> filters = new LinkedList<Filter>();
+ for (String pattern : filterPatterns) {
+ filters.add(new Filter(pattern));
+ }
+ return filters;
+ }
- public void notifyProgress(String fragmentName) {
- fMonitor.subTask("Generating fragment for " + fragmentName);
- fMonitor.worked(1);
- }
+ private static Set<LocaleProxy> getLocaleProxies(List<String> localeNames) {
+ Set<LocaleProxy> locales = new HashSet<LocaleProxy>();
+ for (String localeName : localeNames) {
+ if (!LocaleGroup.isValidGroupName(localeName)
+ && !LocaleGroup.isValidGroupFullName(localeName)) {
+ locales.add(new LocaleProxy(localeName));
+ }
+ }
- public boolean includeXmlReport() {
- return fIncludeXmlReport;
- }
+ return locales;
+ }
- public boolean longReport() {
- return fLongReport;
- }
+ private static Set<LocaleGroup> getLocaleGroups(List<String> locales) {
+ Set<LocaleGroup> set = new HashSet<LocaleGroup>();
+ for (String localeName : locales) {
+ if (LocaleGroup.isValidGroupName(localeName)) {
+ set.add(LocaleGroup.get(localeName));
+ } else if (LocaleGroup.isValidGroupFullName(localeName)) {
+ set.add(LocaleGroup.getByFullName(localeName));
+ }
+ }
+ return set;
+ }
- public String localeExtension() {
- return fLocaleExtension;
- }
+ public Range compatibilityRange() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public EclipseTarget eclipseInstall() {
+ try {
+ if (fEclipseTarget == null) {
+ if (fEclipseRoot == null) {
+ fEclipseTarget = new EclipseTarget(fPluginProxies);
+ } else {
+ fEclipseTarget = new EclipseTarget(fEclipseRoot,
+ fExcludeList);
+ fEclipseTarget.populatePlugins();
+ }
+ }
+ } catch (InvalidLocationException i) {
+ fParentHandler
+ .notifyError(Messages
+ .getString("Error_InvalidEclipseTarget") + Messages.getString("Error_EclipseEntryLocation") + fEclipseRoot); //$NON-NLS-1$
+ return null;
+ } catch (MissingLocationException m) {
+ fParentHandler
+ .notifyError(Messages
+ .getString("Error_MissingEclipseTarget") + Messages.getString("Error_EclipseEntryLocation") + fEclipseRoot); //$NON-NLS-1$
+ return null;
+ } catch (InvalidFilenameException f) {
+ fParentHandler
+ .notifyError(Messages
+ .getString("Error_InvalidEclipseTargetName") + Messages.getString("Error_EclipseEntryLocation") + fEclipseRoot); //$NON-NLS-1$
+ return null;
+ } catch (Exception e) {
+ fParentHandler
+ .notifyError(Messages.getString("Error_EclipseTarget") + Messages.getString("Error_EclipseEntryLocation") + fEclipseRoot); //$NON-NLS-1$
+ return null;
+ }
+ return fEclipseTarget;
+ }
+
+ public Set<String> excludeList() {
+ return fExcludeList;
+ }
+
+ public List<Filter> filters() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public boolean includePseudoTranslations() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public Set<LocaleGroup> localeGroups() {
+ return fLocaleGroups;
+ }
+
+ public Set<LocaleProxy> locales() {
+ return fLocales;
+ }
+
+ public File reportLocation() {
+ return fReport;
+ }
+
+ public Date timestamp() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public TranslationCatalogue translations() {
+ if (fTranslationCatalogue == null) {
+ try {
+
+ if (fLocaleGroups.isEmpty()) {
+ fTranslationCatalogue = new TranslationCatalogue(
+ fTranslationsRoot, fLocales);
+ } else {
+ fLocales.clear();
+ fTranslationCatalogue = new TranslationCatalogue(
+ fTranslationsRoot, fLocaleGroups);
+ fLocales.addAll(fTranslationCatalogue.getAllLocales());
+ }
+
+ } catch (MissingLocationException m) {
+ fParentHandler
+ .notifyError(Messages
+ .getString("Error_MissingTranslationCatalogue") + Messages.getString("Error_TranslationsEntryLocation") + fTranslationsRoot); //$NON-NLS-1$
+ return null;
+ } catch (InvalidLocationException i) {
+ fParentHandler.notifyError(i.getMessage());
+ return null;
+ } catch (InvalidFilenameException f) {
+ fParentHandler
+ .notifyError(Messages
+ .getString("Error_InvalidTranslationCatalogueName") + Messages.getString("Error_TranslationsEntryLocation") + fTranslationsRoot); //$NON-NLS-1$
+ return null;
+ }
+ }
+ return fTranslationCatalogue;
+ }
+
+ public File workingDirectory() {
+ return fWorkingDirectory;
+ }
+
+ public boolean includeResource(PluginProxy plugin, ResourceProxy resource) {
+ for (Filter filter : fReportFilters) {
+ if (filter.matches(plugin, resource)) {
+ return filter.isInclusive();
+ }
+ }
+ return true;
+ }
+
+ public void setProgressMonitor(IProgressMonitor monitor) {
+ this.fMonitor = monitor;
+ }
+
+ public void notifyProgress(String fragmentName) {
+ fMonitor.subTask("Generating fragment for " + fragmentName);
+ fMonitor.worked(1);
+ }
+
+ public boolean includeXmlReport() {
+ return fIncludeXmlReport;
+ }
+
+ public boolean longReport() {
+ return fLongReport;
+ }
+
+ public String localeExtension() {
+ return fLocaleExtension;
+ }
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/ConfigurationManager.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/ConfigurationManager.java
index d31226e..69d8fb4 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/ConfigurationManager.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/ConfigurationManager.java
@@ -22,88 +22,92 @@
import org.eclipse.core.runtime.Platform;
/**
- * Singelton, which provides information regarding the configuration of:
- * <li>TapiJI Preference Page: interface is {@link IConfiguration}</li>
- * <li>Serializing {@link MessagesBundleGroup} to property file</li>
- * <li>Deserializing {@link MessagesBundleGroup} from property file</li>
- * <br><br>
+ * Singelton, which provides information regarding the configuration of: <li>
+ * TapiJI Preference Page: interface is {@link IConfiguration}</li> <li>
+ * Serializing {@link MessagesBundleGroup} to property file</li> <li>
+ * Deserializing {@link MessagesBundleGroup} from property file</li> <br>
+ * <br>
*
* @author Alexej Strelzow
*/
public class ConfigurationManager {
- private static ConfigurationManager INSTANCE;
-
- private IConfiguration config;
-
- private IPropertiesSerializerConfig serializerConfig;
-
- private IPropertiesDeserializerConfig deserializerConfig;
-
- private ConfigurationManager() {
- config = getConfig();
- }
-
- private IConfiguration getConfig() {
-
- IExtensionPoint extp = Platform.getExtensionRegistry().getExtensionPoint(
- "org.eclipse.babel.core" + ".babelConfiguration");
+ private static ConfigurationManager INSTANCE;
+
+ private IConfiguration config;
+
+ private IPropertiesSerializerConfig serializerConfig;
+
+ private IPropertiesDeserializerConfig deserializerConfig;
+
+ private ConfigurationManager() {
+ config = getConfig();
+ }
+
+ private IConfiguration getConfig() {
+
+ IExtensionPoint extp = Platform.getExtensionRegistry()
+ .getExtensionPoint(
+ "org.eclipse.babel.core" + ".babelConfiguration");
IConfigurationElement[] elements = extp.getConfigurationElements();
-
+
if (elements.length != 0) {
- try {
- return (IConfiguration) elements[0].createExecutableExtension("class");
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
+ try {
+ return (IConfiguration) elements[0]
+ .createExecutableExtension("class");
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ return null;
+ }
- /**
- * @return The singleton instance
- */
- public static ConfigurationManager getInstance() {
- if (INSTANCE == null) {
- INSTANCE = new ConfigurationManager();
- }
- return INSTANCE;
- }
-
- /**
- * @return TapiJI configuration
- */
- public IConfiguration getConfiguration() {
- return this.config;
- }
+ /**
+ * @return The singleton instance
+ */
+ public static ConfigurationManager getInstance() {
+ if (INSTANCE == null) {
+ INSTANCE = new ConfigurationManager();
+ }
+ return INSTANCE;
+ }
- /**
- * @return Config needed for {@link PropertiesSerializer}
- */
- public IPropertiesSerializerConfig getSerializerConfig() {
- return serializerConfig;
- }
+ /**
+ * @return TapiJI configuration
+ */
+ public IConfiguration getConfiguration() {
+ return this.config;
+ }
- /**
- * @param serializerConfig The config for serialization
- */
- public void setSerializerConfig(IPropertiesSerializerConfig serializerConfig) {
- this.serializerConfig = serializerConfig;
- }
+ /**
+ * @return Config needed for {@link PropertiesSerializer}
+ */
+ public IPropertiesSerializerConfig getSerializerConfig() {
+ return serializerConfig;
+ }
- /**
- * @return Config needed for {@link PropertiesDeserializer}
- */
- public IPropertiesDeserializerConfig getDeserializerConfig() {
- return deserializerConfig;
- }
+ /**
+ * @param serializerConfig
+ * The config for serialization
+ */
+ public void setSerializerConfig(IPropertiesSerializerConfig serializerConfig) {
+ this.serializerConfig = serializerConfig;
+ }
- /**
- * @param serializerConfig The config for deserialization
- */
- public void setDeserializerConfig(
- IPropertiesDeserializerConfig deserializerConfig) {
- this.deserializerConfig = deserializerConfig;
- }
-
+ /**
+ * @return Config needed for {@link PropertiesDeserializer}
+ */
+ public IPropertiesDeserializerConfig getDeserializerConfig() {
+ return deserializerConfig;
+ }
+
+ /**
+ * @param serializerConfig
+ * The config for deserialization
+ */
+ public void setDeserializerConfig(
+ IPropertiesDeserializerConfig deserializerConfig) {
+ this.deserializerConfig = deserializerConfig;
+ }
+
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/DirtyHack.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/DirtyHack.java
index cc0de07..e72c9d7 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/DirtyHack.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/DirtyHack.java
@@ -14,37 +14,41 @@
import org.eclipse.babel.core.message.internal.AbstractMessageModel;
/**
- * Contains following two <b>dirty</b> workaround flags:
- * <li><b>fireEnabled:</b> deactivates {@link PropertyChangeEvent}-fire in {@link AbstractMessageModel}</li>
- * <li><b>editorModificationEnabled:</b> prevents <code>EclipsePropertiesEditorResource#setText</code></li>
- * <br><br>
- * <b>We need to get rid of this somehow!!!!!!!!!</b>
- * <br><br>
+ * Contains following two <b>dirty</b> workaround flags: <li><b>fireEnabled:</b>
+ * deactivates {@link PropertyChangeEvent}-fire in {@link AbstractMessageModel}</li>
+ * <li><b>editorModificationEnabled:</b> prevents
+ * <code>EclipsePropertiesEditorResource#setText</code></li> <br>
+ * <br>
+ * <b>We need to get rid of this somehow!!!!!!!!!</b> <br>
+ * <br>
*
* @author Alexej Strelzow
*/
public final class DirtyHack {
- private static boolean fireEnabled = true; // no property-fire calls in AbstractMessageModel
-
- private static boolean editorModificationEnabled = true; // no setText in EclipsePropertiesEditorResource
- // set this, if you serialize!
+ private static boolean fireEnabled = true; // no property-fire calls in
+ // AbstractMessageModel
- public static boolean isFireEnabled() {
- return fireEnabled;
- }
+ private static boolean editorModificationEnabled = true; // no setText in
+ // EclipsePropertiesEditorResource
- public static void setFireEnabled(boolean fireEnabled) {
- DirtyHack.fireEnabled = fireEnabled;
- }
+ // set this, if you serialize!
- public static boolean isEditorModificationEnabled() {
- return editorModificationEnabled;
- }
+ public static boolean isFireEnabled() {
+ return fireEnabled;
+ }
- public static void setEditorModificationEnabled(
- boolean editorModificationEnabled) {
- DirtyHack.editorModificationEnabled = editorModificationEnabled;
- }
-
+ public static void setFireEnabled(boolean fireEnabled) {
+ DirtyHack.fireEnabled = fireEnabled;
+ }
+
+ public static boolean isEditorModificationEnabled() {
+ return editorModificationEnabled;
+ }
+
+ public static void setEditorModificationEnabled(
+ boolean editorModificationEnabled) {
+ DirtyHack.editorModificationEnabled = editorModificationEnabled;
+ }
+
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/IConfiguration.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/IConfiguration.java
index b35d556..2247873 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/IConfiguration.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/IConfiguration.java
@@ -18,16 +18,16 @@
*/
public interface IConfiguration {
- boolean getAuditSameValue();
+ boolean getAuditSameValue();
- boolean getAuditMissingValue();
+ boolean getAuditMissingValue();
- boolean getAuditMissingLanguage();
+ boolean getAuditMissingLanguage();
- boolean getAuditRb();
+ boolean getAuditRb();
- boolean getAuditResource();
+ boolean getAuditResource();
- String getNonRbPattern();
+ String getNonRbPattern();
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessageFactory.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessageFactory.java
index ade7c19..d3c8a04 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessageFactory.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessageFactory.java
@@ -25,18 +25,21 @@
*/
public class MessageFactory {
- static Logger logger = Logger.getLogger(MessageFactory.class.getSimpleName());
-
+ static Logger logger = Logger.getLogger(MessageFactory.class
+ .getSimpleName());
+
/**
- * @param key The key of the message
- * @param locale The {@link Locale}
+ * @param key
+ * The key of the message
+ * @param locale
+ * The {@link Locale}
* @return An instance of {@link IMessage}
*/
public static IMessage createMessage(String key, Locale locale) {
String l = locale == null ? "[default]" : locale.toString();
logger.log(Level.INFO, "createMessage, key: " + key + " locale: " + l);
-
+
return new Message(key, locale);
}
-
+
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessagesBundleGroupFactory.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessagesBundleGroupFactory.java
index f9945e6..1c59b1b 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessagesBundleGroupFactory.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessagesBundleGroupFactory.java
@@ -20,20 +20,21 @@
import org.eclipse.core.resources.IResource;
/**
- * Factory class for creating a {@link MessagesBundleGroup} with a {@link PropertiesFileGroupStrategy}.
- * This is in use when we work with TapiJI only and not with <code>EclipsePropertiesEditorResource</code>.
- * <br><br>
+ * Factory class for creating a {@link MessagesBundleGroup} with a
+ * {@link PropertiesFileGroupStrategy}. This is in use when we work with TapiJI
+ * only and not with <code>EclipsePropertiesEditorResource</code>. <br>
+ * <br>
*
* @author Alexej Strelzow
*/
public class MessagesBundleGroupFactory {
-
+
public static IMessagesBundleGroup createBundleGroup(IResource resource) {
-
- File ioFile = new File(resource.getRawLocation().toFile().getPath());
-
- return new MessagesBundleGroup(new PropertiesFileGroupStrategy(ioFile,
- ConfigurationManager.getInstance().getSerializerConfig(),
- ConfigurationManager.getInstance().getDeserializerConfig()));
+
+ File ioFile = new File(resource.getRawLocation().toFile().getPath());
+
+ return new MessagesBundleGroup(new PropertiesFileGroupStrategy(ioFile,
+ ConfigurationManager.getInstance().getSerializerConfig(),
+ ConfigurationManager.getInstance().getDeserializerConfig()));
}
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessage.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessage.java
index 85dae2e..88aaa52 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessage.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessage.java
@@ -17,8 +17,8 @@
/**
* Interface, implemented by {@link Message}. A message is an abstraction of a
- * key-value pair, which can be found in resource bundles (1 row).
- * <br><br>
+ * key-value pair, which can be found in resource bundles (1 row). <br>
+ * <br>
*
* @author Martin Reiterer, Alexej Strelzow
*/
@@ -26,60 +26,71 @@
/**
* Gets the message key attribute.
+ *
* @return Returns the key.
*/
- String getKey();
+ String getKey();
/**
* Gets the message text.
+ *
* @return Returns the text.
*/
- String getValue();
+ String getValue();
/**
* Gets the message locale.
+ *
* @return Returns the locale
*/
- Locale getLocale();
+ Locale getLocale();
/**
- * Gets the comment associated with this message (<code>null</code> if
- * no comments).
+ * Gets the comment associated with this message (<code>null</code> if no
+ * comments).
+ *
* @return Returns the comment.
*/
- String getComment();
+ String getComment();
/**
* Gets whether this message is active or not.
+ *
* @return <code>true</code> if this message is active.
*/
- boolean isActive();
-
- /**
- * @return The toString representation
- */
- String toString();
+ boolean isActive();
/**
- * Sets whether the message is active or not. An inactive message is
- * one that we continue to keep track of, but will not be picked
- * up by internationalization mechanism (e.g. <code>ResourceBundle</code>).
- * Typically, those are commented (i.e. //) key/text pairs in a
- * *.properties file.
- * @param active The active to set.
+ * @return The toString representation
*/
- void setActive(boolean active);
+ String toString();
+
+ /**
+ * Sets whether the message is active or not. An inactive message is one
+ * that we continue to keep track of, but will not be picked up by
+ * internationalization mechanism (e.g. <code>ResourceBundle</code>).
+ * Typically, those are commented (i.e. //) key/text pairs in a *.properties
+ * file.
+ *
+ * @param active
+ * The active to set.
+ */
+ void setActive(boolean active);
/**
* Sets the message comment.
- * @param comment The comment to set.
+ *
+ * @param comment
+ * The comment to set.
*/
- void setComment(String comment);
+ void setComment(String comment);
/**
* Sets the actual message text.
- * @param text The text to set.
+ *
+ * @param text
+ * The text to set.
*/
- void setText(String test);
+ void setText(String test);
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundle.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundle.java
index ef843f5..273a438 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundle.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundle.java
@@ -19,9 +19,9 @@
import org.eclipse.babel.core.message.resource.IMessagesResource;
/**
- * Interface, implemented by {@link MessagesBundle}. A messages bundle is an abstraction of a
- * resource bundle (the *.properties-file).
- * <br><br>
+ * Interface, implemented by {@link MessagesBundle}. A messages bundle is an
+ * abstraction of a resource bundle (the *.properties-file). <br>
+ * <br>
*
* @author Martin Reiterer, Alexej Strelzow
*/
@@ -30,97 +30,125 @@
/**
* Called before this object will be discarded.
*/
- void dispose();
+ void dispose();
/**
* Renames a message key.
- * @param sourceKey the message key to rename
- * @param targetKey the new key for the message
- * @throws MessageException if the target key already exists
+ *
+ * @param sourceKey
+ * the message key to rename
+ * @param targetKey
+ * the new key for the message
+ * @throws MessageException
+ * if the target key already exists
*/
- void renameMessageKey(String sourceKey, String targetKey);
+ void renameMessageKey(String sourceKey, String targetKey);
/**
* Removes a message from this messages bundle.
- * @param messageKey the key of the message to remove
+ *
+ * @param messageKey
+ * the key of the message to remove
*/
- void removeMessage(String messageKey);
+ void removeMessage(String messageKey);
/**
* Duplicates a message.
- * @param sourceKey the message key to duplicate
- * @param targetKey the new message key
- * @throws MessageException if the target key already exists
+ *
+ * @param sourceKey
+ * the message key to duplicate
+ * @param targetKey
+ * the new message key
+ * @throws MessageException
+ * if the target key already exists
*/
- void duplicateMessage(String sourceKey, String targetKey);
+ void duplicateMessage(String sourceKey, String targetKey);
/**
- * Gets the locale for the messages bundle (<code>null</code> assumes
- * the default system locale).
+ * Gets the locale for the messages bundle (<code>null</code> assumes the
+ * default system locale).
+ *
* @return Returns the locale.
*/
- Locale getLocale();
+ Locale getLocale();
/**
* Gets all message keys making up this messages bundle.
+ *
* @return message keys
*/
- String[] getKeys();
+ String[] getKeys();
/**
* Returns the value to the given key, if the key exists.
- * @param key, the key of a message.
+ *
+ * @param key
+ * , the key of a message.
* @return The value to the given key.
*/
- String getValue(String key);
+ String getValue(String key);
/**
* Obtains the set of <code>Message</code> objects in this bundle.
+ *
* @return a collection of <code>Message</code> objects in this bundle
*/
- Collection<IMessage> getMessages();
+ Collection<IMessage> getMessages();
/**
* Gets a message.
- * @param key a message key
+ *
+ * @param key
+ * a message key
* @return a message
*/
- IMessage getMessage(String key);
+ IMessage getMessage(String key);
/**
* Adds an empty message.
- * @param key the new message key
+ *
+ * @param key
+ * the new message key
*/
- void addMessage(IMessage message);
+ void addMessage(IMessage message);
/**
* Removes messages from this messages bundle.
- * @param messageKeys the keys of the messages to remove
+ *
+ * @param messageKeys
+ * the keys of the messages to remove
*/
- void removeMessages(String[] messageKeys);
+ void removeMessages(String[] messageKeys);
/**
* Sets the comment for this messages bundle.
- * @param comment The comment to set.
+ *
+ * @param comment
+ * The comment to set.
*/
- void setComment(String comment);
+ void setComment(String comment);
/**
* Gets the overall comment, or description, for this messages bundle..
+ *
* @return Returns the comment.
*/
- String getComment();
+ String getComment();
/**
* Gets the underlying messages resource implementation.
+ *
* @return
*/
- IMessagesResource getResource();
+ IMessagesResource getResource();
/**
- * Removes a message from this messages bundle and adds it's parent key to bundle.
- * E.g.: key = a.b.c gets deleted, a.b gets added with a default message
- * @param messageKey the key of the message to remove
+ * Removes a message from this messages bundle and adds it's parent key to
+ * bundle. E.g.: key = a.b.c gets deleted, a.b gets added with a default
+ * message
+ *
+ * @param messageKey
+ * the key of the message to remove
*/
- void removeMessageAddParentKey(String key);
+ void removeMessageAddParentKey(String key);
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleGroup.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleGroup.java
index 5de5c0a..bceee59 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleGroup.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleGroup.java
@@ -27,132 +27,164 @@
*/
public interface IMessagesBundleGroup {
- /**
- * Returns a collection of all bundles in this group.
- * @return the bundles in this group
- */
- Collection<IMessagesBundle> getMessagesBundles();
+ /**
+ * Returns a collection of all bundles in this group.
+ *
+ * @return the bundles in this group
+ */
+ Collection<IMessagesBundle> getMessagesBundles();
- /**
- * Returns true if the supplied key is already existing in this group.
- * @param key The key that shall be tested.
- * @return true <=> The key is already existing.
- */
- boolean containsKey(String key);
+ /**
+ * Returns true if the supplied key is already existing in this group.
+ *
+ * @param key
+ * The key that shall be tested.
+ * @return true <=> The key is already existing.
+ */
+ boolean containsKey(String key);
- /**
- * Gets all messages associated with the given message key.
- * @param key a message key
- * @return messages
- */
- IMessage[] getMessages(String key);
+ /**
+ * Gets all messages associated with the given message key.
+ *
+ * @param key
+ * a message key
+ * @return messages
+ */
+ IMessage[] getMessages(String key);
/**
* Gets the message matching given key and locale.
- * @param locale The locale for which to retrieve the message
- * @param key The key matching entry to retrieve the message
+ *
+ * @param locale
+ * The locale for which to retrieve the message
+ * @param key
+ * The key matching entry to retrieve the message
* @return a message
*/
- IMessage getMessage(String key, Locale locale);
+ IMessage getMessage(String key, Locale locale);
/**
* Gets the messages bundle matching given locale.
- * @param locale The locale of bundle to retreive
+ *
+ * @param locale
+ * The locale of bundle to retreive
* @return a bundle
*/
- IMessagesBundle getMessagesBundle(Locale locale);
+ IMessagesBundle getMessagesBundle(Locale locale);
/**
* Removes messages matching the given key from all messages bundle.
- * @param key The key of messages to remove
+ *
+ * @param key
+ * The key of messages to remove
*/
- void removeMessages(String messageKey);
+ void removeMessages(String messageKey);
/**
* Is the given key found in this bundle group.
- * @param key The key to find
+ *
+ * @param key
+ * The key to find
* @return <code>true</code> if the key exists in this bundle group.
*/
- boolean isKey(String key);
+ boolean isKey(String key);
/**
* Adds a messages bundle to this group.
- * @param locale The locale of the bundle
- * @param messagesBundle bundle to add
- * @throws MessageException if a messages bundle for the same locale already exists.
+ *
+ * @param locale
+ * The locale of the bundle
+ * @param messagesBundle
+ * bundle to add
+ * @throws MessageException
+ * if a messages bundle for the same locale already exists.
*/
- void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle);
+ void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle);
/**
* Gets all keys from all messages bundles.
+ *
* @return all keys from all messages bundles
*/
- String[] getMessageKeys();
+ String[] getMessageKeys();
/**
* Adds an empty message to every messages bundle of this group with the
* given.
- * @param key The message key
+ *
+ * @param key
+ * The message key
*/
- void addMessages(String key);
+ void addMessages(String key);
/**
* Gets the number of messages bundles in this group.
+ *
* @return the number of messages bundles in this group
*/
- int getMessagesBundleCount();
+ int getMessagesBundleCount();
/**
- * Gets this messages bundle group name. That is the name, which is used
- * for the tab of the MultiPageEditorPart.
+ * Gets this messages bundle group name. That is the name, which is used for
+ * the tab of the MultiPageEditorPart.
+ *
* @return bundle group name
*/
- String getName();
+ String getName();
- /**
- * Gets the unique id of the bundle group. That is usually: <directory>"."<default-filename>.
- * The default filename is without the suffix (e.g. _en, or _en_GB).
- * @return The unique identifier for the resource bundle group
- */
- String getResourceBundleId();
+ /**
+ * Gets the unique id of the bundle group. That is usually:
+ * <directory>"."<default-filename>. The default filename is without the
+ * suffix (e.g. _en, or _en_GB).
+ *
+ * @return The unique identifier for the resource bundle group
+ */
+ String getResourceBundleId();
- /**
- * @return <code>true</code> if the bundle group has {@link PropertiesFileGroupStrategy} as strategy,
- * else <code>false</code>. This is the case, when only TapiJI edits the resource bundles and no
- * have been opened.
- */
- boolean hasPropertiesFileGroupStrategy();
+ /**
+ * @return <code>true</code> if the bundle group has
+ * {@link PropertiesFileGroupStrategy} as strategy, else
+ * <code>false</code>. This is the case, when only TapiJI edits the
+ * resource bundles and no have been opened.
+ */
+ boolean hasPropertiesFileGroupStrategy();
- /**
- * Whether the given key is found in this messages bundle group.
- * @param key The key to find
- * @return <code>true</code> if the key exists in this bundle group.
- */
- public boolean isMessageKey(String key);
+ /**
+ * Whether the given key is found in this messages bundle group.
+ *
+ * @param key
+ * The key to find
+ * @return <code>true</code> if the key exists in this bundle group.
+ */
+ public boolean isMessageKey(String key);
- /**
- * Gets the name of the project, the resource bundle group is in.
- * @return The project name
- */
- public String getProjectName();
+ /**
+ * Gets the name of the project, the resource bundle group is in.
+ *
+ * @return The project name
+ */
+ public String getProjectName();
- /**
- * Removes the {@link IMessagesBundle} from the group.
- * @param messagesBundle The bundle to remove.
- */
- public void removeMessagesBundle(IMessagesBundle messagesBundle);
+ /**
+ * Removes the {@link IMessagesBundle} from the group.
+ *
+ * @param messagesBundle
+ * The bundle to remove.
+ */
+ public void removeMessagesBundle(IMessagesBundle messagesBundle);
- /**
- * Called before this object will be discarded. Disposes the underlying
- * MessageBundles
- */
- public void dispose();
+ /**
+ * Called before this object will be discarded. Disposes the underlying
+ * MessageBundles
+ */
+ public void dispose();
- /**
- * Removes messages matching the given key from all messages bundle and add
- * it's parent key to bundles.
- *
- * @param key The key of messages to remove
- */
- void removeMessagesAddParentKey(String key);
+ /**
+ * Removes messages matching the given key from all messages bundle and add
+ * it's parent key to bundles.
+ *
+ * @param key
+ * The key of messages to remove
+ */
+ void removeMessagesAddParentKey(String key);
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesResourceChangeListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesResourceChangeListener.java
index 70f8650..172e255 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesResourceChangeListener.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesResourceChangeListener.java
@@ -20,11 +20,11 @@
*/
public interface IMessagesResourceChangeListener {
- /**
- * Method called when the messages resource has changed.
- *
- * @param resource
- * the resource that changed
- */
- void resourceChanged(IMessagesResource resource);
+ /**
+ * Method called when the messages resource has changed.
+ *
+ * @param resource
+ * the resource that changed
+ */
+ void resourceChanged(IMessagesResource resource);
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/IMessageCheck.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/IMessageCheck.java
index 6258638..21807cc 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/IMessageCheck.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/IMessageCheck.java
@@ -16,18 +16,22 @@
import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
/**
- * All purpose {@link Message} testing. Use this interface to establish
- * whether a message within a {@link MessagesBundleGroup} is answering
- * successfully to any condition.
+ * All purpose {@link Message} testing. Use this interface to establish whether
+ * a message within a {@link MessagesBundleGroup} is answering successfully to
+ * any condition.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public interface IMessageCheck {
- /**
- * Checks whether a {@link Message} meets the implemented condition.
- * @param messagesBundleGroup messages bundle group
- * @param message the message being tested
- * @return <code>true</code> if condition is successfully tested
- */
+ /**
+ * Checks whether a {@link Message} meets the implemented condition.
+ *
+ * @param messagesBundleGroup
+ * messages bundle group
+ * @param message
+ * the message being tested
+ * @return <code>true</code> if condition is successfully tested
+ */
boolean checkKey(IMessagesBundleGroup messagesBundleGroup, IMessage message);
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/DuplicateValueCheck.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/DuplicateValueCheck.java
index 2cf96dc..f03cb85 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/DuplicateValueCheck.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/DuplicateValueCheck.java
@@ -21,36 +21,37 @@
/**
* Checks if key as a duplicate value.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public class DuplicateValueCheck implements IMessageCheck {
private String[] duplicateKeys;
-
+
/**
* Constructor.
*/
public DuplicateValueCheck() {
super();
}
-
+
/**
* Resets the collected keys to null.
*/
public void reset() {
- duplicateKeys = null;
+ duplicateKeys = null;
}
- public boolean checkKey(
- IMessagesBundleGroup messagesBundleGroup, IMessage message) {
+ public boolean checkKey(IMessagesBundleGroup messagesBundleGroup,
+ IMessage message) {
Collection<String> keys = new ArrayList<String>();
if (message != null) {
- IMessagesBundle messagesBundle =
- messagesBundleGroup.getMessagesBundle(message.getLocale());
+ IMessagesBundle messagesBundle = messagesBundleGroup
+ .getMessagesBundle(message.getLocale());
for (IMessage duplicateEntry : messagesBundle.getMessages()) {
if (!message.getKey().equals(duplicateEntry.getKey())
- && BabelUtils.equals(message.getValue(),
- duplicateEntry.getValue())) {
+ && BabelUtils.equals(message.getValue(),
+ duplicateEntry.getValue())) {
keys.add(duplicateEntry.getKey());
}
}
@@ -59,12 +60,12 @@
}
}
- duplicateKeys = keys.toArray(new String[]{});
+ duplicateKeys = keys.toArray(new String[] {});
return !keys.isEmpty();
}
-
+
public String[] getDuplicateKeys() {
return duplicateKeys;
}
-
+
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/MissingValueCheck.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/MissingValueCheck.java
index e5a5295..68acb6c 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/MissingValueCheck.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/MissingValueCheck.java
@@ -15,15 +15,16 @@
import org.eclipse.babel.core.message.checks.IMessageCheck;
/**
- * Visitor for finding if a key has at least one corresponding bundle entry
- * with a missing value.
+ * Visitor for finding if a key has at least one corresponding bundle entry with
+ * a missing value.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public class MissingValueCheck implements IMessageCheck {
- /** The singleton */
- public static MissingValueCheck MISSING_KEY = new MissingValueCheck();
-
+ /** The singleton */
+ public static MissingValueCheck MISSING_KEY = new MissingValueCheck();
+
/**
* Constructor.
*/
@@ -32,12 +33,11 @@
}
/**
- * @see org.eclipse.babel.core.message.internal.checks.IMessageCheck#checkKey(
- * org.eclipse.babel.core.message.internal.MessagesBundleGroup,
- * org.eclipse.babel.core.message.internal.Message)
+ * @see org.eclipse.babel.core.message.internal.checks.IMessageCheck#checkKey(org.eclipse.babel.core.message.internal.MessagesBundleGroup,
+ * org.eclipse.babel.core.message.internal.Message)
*/
- public boolean checkKey(
- IMessagesBundleGroup messagesBundleGroup, IMessage message) {
+ public boolean checkKey(IMessagesBundleGroup messagesBundleGroup,
+ IMessage message) {
if (message == null || message.getValue() == null
|| message.getValue().length() == 0) {
return true;
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/SimilarValueCheck.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/SimilarValueCheck.java
index be333ca..277a887 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/SimilarValueCheck.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/SimilarValueCheck.java
@@ -20,16 +20,16 @@
import org.eclipse.babel.core.message.checks.proximity.IProximityAnalyzer;
import org.eclipse.babel.core.util.BabelUtils;
-
/**
* Checks if key as a duplicate value.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public class SimilarValueCheck implements IMessageCheck {
private String[] similarKeys;
private IProximityAnalyzer analyzer;
-
+
/**
* Constructor.
*/
@@ -39,26 +39,26 @@
}
/**
- * @see org.eclipse.babel.core.message.internal.checks.IMessageCheck#checkKey(
- * org.eclipse.babel.core.message.internal.MessagesBundleGroup,
- * org.eclipse.babel.core.message.internal.Message)
+ * @see org.eclipse.babel.core.message.internal.checks.IMessageCheck#checkKey(org.eclipse.babel.core.message.internal.MessagesBundleGroup,
+ * org.eclipse.babel.core.message.internal.Message)
*/
- public boolean checkKey(
- IMessagesBundleGroup messagesBundleGroup, IMessage message) {
+ public boolean checkKey(IMessagesBundleGroup messagesBundleGroup,
+ IMessage message) {
Collection<String> keys = new ArrayList<String>();
if (message != null) {
- //TODO have case as preference
+ // TODO have case as preference
String value1 = message.getValue().toLowerCase();
- IMessagesBundle messagesBundle =
- messagesBundleGroup.getMessagesBundle(message.getLocale());
+ IMessagesBundle messagesBundle = messagesBundleGroup
+ .getMessagesBundle(message.getLocale());
for (IMessage similarEntry : messagesBundle.getMessages()) {
if (!message.getKey().equals(similarEntry.getKey())) {
String value2 = similarEntry.getValue().toLowerCase();
- //TODO have preference to report identical as similar
+ // TODO have preference to report identical as similar
if (!BabelUtils.equals(value1, value2)
&& analyzer.analyse(value1, value2) >= 0.75) {
- //TODO use preferences
-// >= RBEPreferences.getReportSimilarValuesPrecision()) {
+ // TODO use preferences
+ // >= RBEPreferences.getReportSimilarValuesPrecision())
+ // {
keys.add(similarEntry.getKey());
}
}
@@ -67,12 +67,13 @@
keys.add(message.getKey());
}
}
- similarKeys = keys.toArray(new String[]{});
+ similarKeys = keys.toArray(new String[] {});
return !keys.isEmpty();
}
-
+
/**
* Gets similar keys.
+ *
* @return similar keys
*/
public String[] getSimilarMessageKeys() {
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/IProximityAnalyzer.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/IProximityAnalyzer.java
index 6e71338..bf743f3 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/IProximityAnalyzer.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/IProximityAnalyzer.java
@@ -12,18 +12,21 @@
/**
* Analyse the proximity of two objects (i.e., how similar they are) and return
- * a proximity level between zero and one. The higher the return value is,
- * the closer the two objects are to each other. "One" does not need to mean
- * "identical", but it has to be the closest match and analyser can
- * potentially achieve.
+ * a proximity level between zero and one. The higher the return value is, the
+ * closer the two objects are to each other. "One" does not need to mean
+ * "identical", but it has to be the closest match and analyser can potentially
+ * achieve.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public interface IProximityAnalyzer {
/**
* Analyses two objects and return the proximity level.
*
- * @param str1 first object to analyse (cannot be null)
- * @param str2 second object to analyse (cannot be null)
+ * @param str1
+ * first object to analyse (cannot be null)
+ * @param str2
+ * second object to analyse (cannot be null)
* @return proximity level
*/
double analyse(String str1, String str2);
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/LevenshteinDistanceAnalyzer.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/LevenshteinDistanceAnalyzer.java
index 4874869..70f0ad2 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/LevenshteinDistanceAnalyzer.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/LevenshteinDistanceAnalyzer.java
@@ -10,53 +10,56 @@
******************************************************************************/
package org.eclipse.babel.core.message.checks.proximity;
-
/**
* Compares two strings (case insensitive) and returns a proximity level based
* on the number of character transformation required to have identical strings.
* Non-string objects are converted to strings using the <code>toString()</code>
- * method. The exact algorithm was taken from Micheal Gilleland
- * (<a href="http://merriampark.com/ld.htm">http://merriampark.com/ld.htm</a>).
+ * method. The exact algorithm was taken from Micheal Gilleland (<a
+ * href="http://merriampark.com/ld.htm">http://merriampark.com/ld.htm</a>).
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public class LevenshteinDistanceAnalyzer implements IProximityAnalyzer {
- private static final IProximityAnalyzer INSTANCE =
- new LevenshteinDistanceAnalyzer();
-
+ private static final IProximityAnalyzer INSTANCE = new LevenshteinDistanceAnalyzer();
+
/**
* Constructor.
*/
private LevenshteinDistanceAnalyzer() {
- //TODO add case sensitivity?
+ // TODO add case sensitivity?
super();
}
/**
* Gets the unique instance.
+ *
* @return a proximity analyzer
*/
public static IProximityAnalyzer getInstance() {
return INSTANCE;
}
-
+
/**
* @see com.essiembre.eclipse.rbe.model.utils.IProximityAnalyzer
* #analyse(java.lang.Object, java.lang.Object)
*/
- public double analyse(String str1, String str2) {
+ public double analyse(String str1, String str2) {
int maxLength = Math.max(str1.length(), str2.length());
double distance = distance(str1, str2);
return 1d - (distance / maxLength);
}
-
-
+
/**
* Retuns the minimum of three values.
- * @param a first value
- * @param b second value
- * @param c third value
+ *
+ * @param a
+ * first value
+ * @param b
+ * second value
+ * @param c
+ * third value
* @return lowest value
*/
private int minimum(int a, int b, int c) {
@@ -75,8 +78,11 @@
/***
* Compute the distance
- * @param s source string
- * @param t target string
+ *
+ * @param s
+ * source string
+ * @param t
+ * target string
* @return distance
*/
public int distance(String s, String t) {
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/WordCountAnalyzer.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/WordCountAnalyzer.java
index 6fbccbb..72d6a71 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/WordCountAnalyzer.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/WordCountAnalyzer.java
@@ -15,28 +15,29 @@
import java.util.Collection;
/**
- * Compares two strings (case insensitive) and returns a proximity level
- * based on how many words there are, and how many words are the same
- * in both strings. Non-string objects are converted to strings using
- * the <code>toString()</code> method.
+ * Compares two strings (case insensitive) and returns a proximity level based
+ * on how many words there are, and how many words are the same in both strings.
+ * Non-string objects are converted to strings using the <code>toString()</code>
+ * method.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public class WordCountAnalyzer implements IProximityAnalyzer {
private static final IProximityAnalyzer INSTANCE = new WordCountAnalyzer();
- private static final String WORD_SPLIT_PATTERN =
- "\r\n|\r|\n|\\s"; //$NON-NLS-1$
+ private static final String WORD_SPLIT_PATTERN = "\r\n|\r|\n|\\s"; //$NON-NLS-1$
/**
* Constructor.
*/
private WordCountAnalyzer() {
- //TODO add case sensitivity?
+ // TODO add case sensitivity?
super();
}
/**
* Gets the unique instance.
+ *
* @return a proximity analyzer
*/
public static IProximityAnalyzer getInstance() {
@@ -45,19 +46,19 @@
/**
* @see com.essiembre.eclipse.rbe.model.utils.IProximityAnalyzer
- * #analyse(java.lang.Object, java.lang.Object)
+ * #analyse(java.lang.Object, java.lang.Object)
*/
public double analyse(String words1, String words2) {
- Collection<String> str1 = new ArrayList<String>(
- Arrays.asList(words1.split(WORD_SPLIT_PATTERN)));
- Collection<String> str2 = new ArrayList<String>(
- Arrays.asList(words2.split(WORD_SPLIT_PATTERN)));
-
+ Collection<String> str1 = new ArrayList<String>(Arrays.asList(words1
+ .split(WORD_SPLIT_PATTERN)));
+ Collection<String> str2 = new ArrayList<String>(Arrays.asList(words2
+ .split(WORD_SPLIT_PATTERN)));
+
int maxWords = Math.max(str1.size(), str2.size());
if (maxWords == 0) {
return 0;
}
-
+
int matchedWords = 0;
for (String str : str1) {
if (str2.remove(str)) {
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/AbstractIFileChangeListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/AbstractIFileChangeListener.java
index 83179c9..c3c72a9 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/AbstractIFileChangeListener.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/AbstractIFileChangeListener.java
@@ -15,75 +15,81 @@
import org.eclipse.core.resources.IResourceChangeListener;
/**
- * Same functionality than an {@link IResourceChangeListener} but listens to
- * a single file at a time. Subscribed and unsubscribed directly on
- * the MessageEditorPlugin.
+ * Same functionality than an {@link IResourceChangeListener} but listens to a
+ * single file at a time. Subscribed and unsubscribed directly on the
+ * MessageEditorPlugin.
*
* @author Hugues Malphettes
*/
public abstract class AbstractIFileChangeListener {
-
- /**
- * Takes a IResourceChangeListener and wraps it into an AbstractIFileChangeListener.
- * <p>
- * Delegates the listenedFileChanged calls to the underlying
- * IResourceChangeListener#resourceChanged.
- * </p>
- * @param rcl
- * @param listenedFile
- * @return
- */
- public static AbstractIFileChangeListener wrapResourceChangeListener(
- final IResourceChangeListener rcl, IFile listenedFile) {
- return new AbstractIFileChangeListener(listenedFile) {
- public void listenedFileChanged(IResourceChangeEvent event) {
- rcl.resourceChanged(event);
- }
- };
- }
-
- //we use a string to be certain that no memory will leak from this class:
- //there is nothing to do a priori to dispose of this class.
- private final String listenedFileFullPath;
-
- /**
- * @param listenedFile The file this object listens to. It is final.
- */
- public AbstractIFileChangeListener(IFile listenedFile) {
- listenedFileFullPath = listenedFile.getFullPath().toString();
- }
-
- /**
- * @return The file listened to. It is final.
- */
- public final String getListenedFileFullPath() {
- return listenedFileFullPath;
- }
-
- /**
- * @param event The change event. It is guaranteed that this
- * event's getResource() method returns the file that this object listens to.
- */
- public abstract void listenedFileChanged(IResourceChangeEvent event);
-
- /**
- * Interface implemented by the MessageEditorPlugin.
- * <p>
- * Describes the registry of file change listeners.
- *
- * </p>
- */
- public interface IFileChangeListenerRegistry {
- /**
- * @param rcl Adds a subscriber to a resource change event.
- */
- public void subscribe(AbstractIFileChangeListener fileChangeListener);
-
- /**
- * @param rcl Removes a subscriber to a resource change event.
- */
- public void unsubscribe(AbstractIFileChangeListener fileChangeListener);
- }
+ /**
+ * Takes a IResourceChangeListener and wraps it into an
+ * AbstractIFileChangeListener.
+ * <p>
+ * Delegates the listenedFileChanged calls to the underlying
+ * IResourceChangeListener#resourceChanged.
+ * </p>
+ *
+ * @param rcl
+ * @param listenedFile
+ * @return
+ */
+ public static AbstractIFileChangeListener wrapResourceChangeListener(
+ final IResourceChangeListener rcl, IFile listenedFile) {
+ return new AbstractIFileChangeListener(listenedFile) {
+ public void listenedFileChanged(IResourceChangeEvent event) {
+ rcl.resourceChanged(event);
+ }
+ };
+ }
+
+ // we use a string to be certain that no memory will leak from this class:
+ // there is nothing to do a priori to dispose of this class.
+ private final String listenedFileFullPath;
+
+ /**
+ * @param listenedFile
+ * The file this object listens to. It is final.
+ */
+ public AbstractIFileChangeListener(IFile listenedFile) {
+ listenedFileFullPath = listenedFile.getFullPath().toString();
+ }
+
+ /**
+ * @return The file listened to. It is final.
+ */
+ public final String getListenedFileFullPath() {
+ return listenedFileFullPath;
+ }
+
+ /**
+ * @param event
+ * The change event. It is guaranteed that this event's
+ * getResource() method returns the file that this object listens
+ * to.
+ */
+ public abstract void listenedFileChanged(IResourceChangeEvent event);
+
+ /**
+ * Interface implemented by the MessageEditorPlugin.
+ * <p>
+ * Describes the registry of file change listeners.
+ *
+ * </p>
+ */
+ public interface IFileChangeListenerRegistry {
+ /**
+ * @param rcl
+ * Adds a subscriber to a resource change event.
+ */
+ public void subscribe(AbstractIFileChangeListener fileChangeListener);
+
+ /**
+ * @param rcl
+ * Removes a subscriber to a resource change event.
+ */
+ public void unsubscribe(AbstractIFileChangeListener fileChangeListener);
+ }
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/AbstractMessageModel.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/AbstractMessageModel.java
index ee50712..c8ced31 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/AbstractMessageModel.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/AbstractMessageModel.java
@@ -19,13 +19,12 @@
import org.eclipse.babel.core.configuration.DirtyHack;
import org.eclipse.babel.core.util.BabelUtils;
-
/**
- * A convenience base class for observable message-related classes.
- * This class follows the conventions and recommendations as described
- * in the <a href="http://java.sun.com/products/javabeans/docs/spec.html">SUN
- * JavaBean specifications</a>.
- *
+ * A convenience base class for observable message-related classes. This class
+ * follows the conventions and recommendations as described in the <a
+ * href="http://java.sun.com/products/javabeans/docs/spec.html">SUN JavaBean
+ * specifications</a>.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
* @author Karsten Lentzsch (karsten@jgoodies.com)
*/
@@ -34,13 +33,15 @@
private transient PropertyChangeSupport changeSupport;
/**
- * Adds a PropertyChangeListener to the listener list. The listener is
- * registered for all properties of this class.<p>
+ * Adds a PropertyChangeListener to the listener list. The listener is
+ * registered for all properties of this class.
+ * <p>
* Adding a <code>null</code> listener has no effect.
*
- * @param listener the PropertyChangeListener to be added
+ * @param listener
+ * the PropertyChangeListener to be added
*/
- /*default*/ final synchronized void addPropertyChangeListener(
+ /* default */final synchronized void addPropertyChangeListener(
final PropertyChangeListener listener) {
if (listener == null) {
return;
@@ -53,13 +54,15 @@
/**
* Removes a PropertyChangeListener from the listener list. This method
- * should be used to remove PropertyChangeListeners that were registered
- * for all bound properties of this class.<p>
+ * should be used to remove PropertyChangeListeners that were registered for
+ * all bound properties of this class.
+ * <p>
* Removing a <code>null</code> listener has no effect.
- *
- * @param listener the PropertyChangeListener to be removed
+ *
+ * @param listener
+ * the PropertyChangeListener to be removed
*/
- /*default*/ final synchronized void removePropertyChangeListener(
+ /* default */final synchronized void removePropertyChangeListener(
final PropertyChangeListener listener) {
if (listener == null || changeSupport == null) {
return;
@@ -68,15 +71,14 @@
}
/**
- * Returns an array of all the property change listeners registered on
- * this component.
- *
- * @return all of this component's <code>PropertyChangeListener</code>s
- * or an empty array if no property change
- * listeners are currently registered
+ * Returns an array of all the property change listeners registered on this
+ * component.
+ *
+ * @return all of this component's <code>PropertyChangeListener</code>s or
+ * an empty array if no property change listeners are currently
+ * registered
*/
- /*default*/ final synchronized
- PropertyChangeListener[] getPropertyChangeListeners() {
+ /* default */final synchronized PropertyChangeListener[] getPropertyChangeListeners() {
if (changeSupport == null) {
return new PropertyChangeListener[0];
}
@@ -84,19 +86,20 @@
}
/**
- * Support for reporting bound property changes for Object properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
+ * Support for reporting bound property changes for Object properties. This
+ * method can be called when a bound property has changed and it will send
+ * the appropriate PropertyChangeEvent to any registered
* PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
+ *
+ * @param propertyName
+ * the property whose value has changed
+ * @param oldValue
+ * the property's previous value
+ * @param newValue
+ * the property's new value
*/
- protected final void firePropertyChange(
- final String propertyName,
- final Object oldValue,
- final Object newValue) {
+ protected final void firePropertyChange(final String propertyName,
+ final Object oldValue, final Object newValue) {
if (changeSupport == null || !DirtyHack.isFireEnabled()) {
return;
}
@@ -104,19 +107,20 @@
}
/**
- * Support for reporting bound property changes for boolean properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
+ * Support for reporting bound property changes for boolean properties. This
+ * method can be called when a bound property has changed and it will send
+ * the appropriate PropertyChangeEvent to any registered
* PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
+ *
+ * @param propertyName
+ * the property whose value has changed
+ * @param oldValue
+ * the property's previous value
+ * @param newValue
+ * the property's new value
*/
- protected final void firePropertyChange(
- final String propertyName,
- final boolean oldValue,
- final boolean newValue) {
+ protected final void firePropertyChange(final String propertyName,
+ final boolean oldValue, final boolean newValue) {
if (changeSupport == null || !DirtyHack.isFireEnabled()) {
return;
}
@@ -124,71 +128,74 @@
}
/**
- * Support for reporting bound property changes for events.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
+ * Support for reporting bound property changes for events. This method can
+ * be called when a bound property has changed and it will send the
+ * appropriate PropertyChangeEvent to any registered
* PropertyChangeListeners.
- *
- * @param event the event that triggered the change
+ *
+ * @param event
+ * the event that triggered the change
*/
- protected final void firePropertyChange(
- final PropertyChangeEvent event) {
+ protected final void firePropertyChange(final PropertyChangeEvent event) {
if (changeSupport == null || !DirtyHack.isFireEnabled()) {
return;
}
changeSupport.firePropertyChange(event);
}
-
+
/**
- * Support for reporting bound property changes for integer properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
+ * Support for reporting bound property changes for integer properties. This
+ * method can be called when a bound property has changed and it will send
+ * the appropriate PropertyChangeEvent to any registered
* PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
+ *
+ * @param propertyName
+ * the property whose value has changed
+ * @param oldValue
+ * the property's previous value
+ * @param newValue
+ * the property's new value
*/
- protected final void firePropertyChange(
- final String propertyName,
- final double oldValue,
- final double newValue) {
- firePropertyChange(
- propertyName, new Double(oldValue), new Double(newValue));
+ protected final void firePropertyChange(final String propertyName,
+ final double oldValue, final double newValue) {
+ firePropertyChange(propertyName, new Double(oldValue), new Double(
+ newValue));
}
/**
- * Support for reporting bound property changes for integer properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
+ * Support for reporting bound property changes for integer properties. This
+ * method can be called when a bound property has changed and it will send
+ * the appropriate PropertyChangeEvent to any registered
* PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
+ *
+ * @param propertyName
+ * the property whose value has changed
+ * @param oldValue
+ * the property's previous value
+ * @param newValue
+ * the property's new value
*/
- protected final void firePropertyChange(
- final String propertyName,
- final float oldValue,
- final float newValue) {
- firePropertyChange(
- propertyName, new Float(oldValue), new Float(newValue));
+ protected final void firePropertyChange(final String propertyName,
+ final float oldValue, final float newValue) {
+ firePropertyChange(propertyName, new Float(oldValue), new Float(
+ newValue));
}
/**
- * Support for reporting bound property changes for integer properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
+ * Support for reporting bound property changes for integer properties. This
+ * method can be called when a bound property has changed and it will send
+ * the appropriate PropertyChangeEvent to any registered
* PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
+ *
+ * @param propertyName
+ * the property whose value has changed
+ * @param oldValue
+ * the property's previous value
+ * @param newValue
+ * the property's new value
*/
- protected final void firePropertyChange(
- final String propertyName,
- final int oldValue,
- final int newValue) {
+ protected final void firePropertyChange(final String propertyName,
+ final int oldValue, final int newValue) {
if (changeSupport == null || !DirtyHack.isFireEnabled()) {
return;
}
@@ -196,31 +203,33 @@
}
/**
- * Support for reporting bound property changes for integer properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
+ * Support for reporting bound property changes for integer properties. This
+ * method can be called when a bound property has changed and it will send
+ * the appropriate PropertyChangeEvent to any registered
* PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
+ *
+ * @param propertyName
+ * the property whose value has changed
+ * @param oldValue
+ * the property's previous value
+ * @param newValue
+ * the property's new value
*/
- protected final void firePropertyChange(
- final String propertyName,
- final long oldValue,
- final long newValue) {
- firePropertyChange(
- propertyName, new Long(oldValue), new Long(newValue));
+ protected final void firePropertyChange(final String propertyName,
+ final long oldValue, final long newValue) {
+ firePropertyChange(propertyName, new Long(oldValue), new Long(newValue));
}
/**
- * Checks and answers if the two objects are both <code>null</code>
- * or equal.
- *
- * @param o1 the first object to compare
- * @param o2 the second object to compare
- * @return boolean true if and only if both objects are <code>null</code>
- * or equal
+ * Checks and answers if the two objects are both <code>null</code> or
+ * equal.
+ *
+ * @param o1
+ * the first object to compare
+ * @param o2
+ * the second object to compare
+ * @return boolean true if and only if both objects are <code>null</code> or
+ * equal
*/
protected final boolean equals(final Object o1, final Object o2) {
return BabelUtils.equals(o1, o2);
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/IMessagesBundleGroupListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/IMessagesBundleGroupListener.java
index 7fb97c5..0fa25b3 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/IMessagesBundleGroupListener.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/IMessagesBundleGroupListener.java
@@ -14,6 +14,7 @@
/**
* A listener for changes on a {@link MessagesBundleGroup}.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
* @see MessagesBundleGroup
*/
@@ -21,29 +22,43 @@
/**
* A message key has been added.
- * @param key the added key
+ *
+ * @param key
+ * the added key
*/
void keyAdded(String key);
+
/**
* A message key has been removed.
- * @param key the removed key
+ *
+ * @param key
+ * the removed key
*/
void keyRemoved(String key);
+
/**
* A messages bundle has been added.
- * @param messagesBundle the messages bundle
+ *
+ * @param messagesBundle
+ * the messages bundle
*/
void messagesBundleAdded(MessagesBundle messagesBundle);
+
/**
* A messages bundle has been removed.
- * @param messagesBundle the messages bundle
+ *
+ * @param messagesBundle
+ * the messages bundle
*/
void messagesBundleRemoved(MessagesBundle messagesBundle);
+
/**
* A messages bundle was modified.
- * @param messagesBundle the messages bundle
+ *
+ * @param messagesBundle
+ * the messages bundle
*/
- void messagesBundleChanged(
- MessagesBundle messagesBundle, PropertyChangeEvent changeEvent);
+ void messagesBundleChanged(MessagesBundle messagesBundle,
+ PropertyChangeEvent changeEvent);
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/IMessagesBundleListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/IMessagesBundleListener.java
index 108601b..7573743 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/IMessagesBundleListener.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/IMessagesBundleListener.java
@@ -15,29 +15,39 @@
/**
* A listener for changes on a {@link MessagesBundle}.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
* @see MessagesBundle
*/
public interface IMessagesBundleListener extends PropertyChangeListener {
/**
* A message was added.
- * @param messagesBundle the messages bundle on which the message was added.
- * @param message the message
+ *
+ * @param messagesBundle
+ * the messages bundle on which the message was added.
+ * @param message
+ * the message
*/
void messageAdded(MessagesBundle messagesBundle, Message message);
+
/**
* A message was removed.
- * @param messagesBundle the messages bundle on which the message was
- * removed.
- * @param message the message
+ *
+ * @param messagesBundle
+ * the messages bundle on which the message was removed.
+ * @param message
+ * the message
*/
void messageRemoved(MessagesBundle messagesBundle, Message message);
+
/**
* A message was changed.
- * @param messagesBundle the messages bundle on which the message was
- * changed.
- * @param message the message
+ *
+ * @param messagesBundle
+ * the messages bundle on which the message was changed.
+ * @param message
+ * the message
*/
- void messageChanged(
- MessagesBundle messagesBundle, PropertyChangeEvent changeEvent);
+ void messageChanged(MessagesBundle messagesBundle,
+ PropertyChangeEvent changeEvent);
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/Message.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/Message.java
index 90eac41..4952d6d 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/Message.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/Message.java
@@ -44,9 +44,12 @@
private String text;
/**
- * Constructor. Key and locale arguments are <code>null</code> safe.
- * @param key unique identifier within a messages bundle
- * @param locale the message locale
+ * Constructor. Key and locale arguments are <code>null</code> safe.
+ *
+ * @param key
+ * unique identifier within a messages bundle
+ * @param locale
+ * the message locale
*/
public Message(final String key, final Locale locale) {
super();
@@ -54,33 +57,35 @@
this.locale = locale;
}
-
-
/**
* Sets the message comment.
- * @param comment The comment to set.
+ *
+ * @param comment
+ * The comment to set.
*/
public void setComment(String comment) {
Object oldValue = this.comment;
this.comment = comment;
firePropertyChange(PROPERTY_COMMENT, oldValue, comment);
}
-
+
public void setComment(String comment, boolean silent) {
Object oldValue = this.comment;
this.comment = comment;
if (!silent) {
- firePropertyChange(PROPERTY_COMMENT, oldValue, comment);
+ firePropertyChange(PROPERTY_COMMENT, oldValue, comment);
}
}
/**
- * Sets whether the message is active or not. An inactive message is
- * one that we continue to keep track of, but will not be picked
- * up by internationalisation mechanism (e.g. <code>ResourceBundle</code>).
- * Typically, those are commented (i.e. //) key/text pairs in a
- * *.properties file.
- * @param active The active to set.
+ * Sets whether the message is active or not. An inactive message is one
+ * that we continue to keep track of, but will not be picked up by
+ * internationalisation mechanism (e.g. <code>ResourceBundle</code>).
+ * Typically, those are commented (i.e. //) key/text pairs in a *.properties
+ * file.
+ *
+ * @param active
+ * The active to set.
*/
public void setActive(boolean active) {
boolean oldValue = this.active;
@@ -90,40 +95,46 @@
/**
* Sets the actual message text.
- * @param text The text to set.
+ *
+ * @param text
+ * The text to set.
*/
public void setText(String text) {
Object oldValue = this.text;
this.text = text;
firePropertyChange(PROPERTY_TEXT, oldValue, text);
}
-
+
public void setText(String text, boolean silent) {
Object oldValue = this.text;
this.text = text;
if (!silent) {
- firePropertyChange(PROPERTY_TEXT, oldValue, text);
+ firePropertyChange(PROPERTY_TEXT, oldValue, text);
}
}
/**
- * Gets the comment associated with this message (<code>null</code> if
- * no comments).
+ * Gets the comment associated with this message (<code>null</code> if no
+ * comments).
+ *
* @return Returns the comment.
*/
public String getComment() {
return comment;
}
+
/**
* Gets the message key attribute.
+ *
* @return Returns the key.
*/
public String getKey() {
return key;
}
-
+
/**
* Gets the message text.
+ *
* @return Returns the text.
*/
public String getValue() {
@@ -132,24 +143,26 @@
/**
* Gets the message locale.
+ *
* @return Returns the locale
*/
public Locale getLocale() {
return locale;
}
-
+
/**
* Gets whether this message is active or not.
+ *
* @return <code>true</code> if this message is active.
*/
public boolean isActive() {
return active;
}
-
+
/**
- * Copies properties of the given message to this message.
- * The properties copied over are all properties but the
- * message key and locale.
+ * Copies properties of the given message to this message. The properties
+ * copied over are all properties but the message key and locale.
+ *
* @param message
*/
protected void copyFrom(IMessage message) {
@@ -166,32 +179,32 @@
return false;
}
Message entry = (Message) obj;
- return equals(key, entry.key)
- && equals(locale, entry.locale)
- && active == entry.active
- && equals(text, entry.text)
- && equals(comment, entry.comment);
+ return equals(key, entry.key) && equals(locale, entry.locale)
+ && active == entry.active && equals(text, entry.text)
+ && equals(comment, entry.comment);
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
- return "Message=[[key=" + key //$NON-NLS-1$
+ return "Message=[[key=" + key //$NON-NLS-1$
+ "][text=" + text //$NON-NLS-1$
+ "][comment=" + comment //$NON-NLS-1$
+ "][active=" + active //$NON-NLS-1$
- + "]]"; //$NON-NLS-1$
+ + "]]"; //$NON-NLS-1$
}
-
+
public final synchronized void addMessageListener(
final PropertyChangeListener listener) {
addPropertyChangeListener(listener);
}
+
public final synchronized void removeMessageListener(
final PropertyChangeListener listener) {
removePropertyChangeListener(listener);
}
+
public final synchronized PropertyChangeListener[] getMessageListeners() {
return getPropertyChangeListeners();
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessageException.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessageException.java
index 242b902..c48caed 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessageException.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessageException.java
@@ -11,7 +11,8 @@
package org.eclipse.babel.core.message.internal;
/**
- * Exception thrown when a message-related operation raised a problem.
+ * Exception thrown when a message-related operation raised a problem.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public class MessageException extends RuntimeException {
@@ -28,7 +29,9 @@
/**
* Creates a new <code>MessageException</code>.
- * @param message exception message
+ *
+ * @param message
+ * exception message
*/
public MessageException(String message) {
super(message);
@@ -36,8 +39,11 @@
/**
* Creates a new <code>MessageException</code>.
- * @param message exception message
- * @param cause root cause
+ *
+ * @param message
+ * exception message
+ * @param cause
+ * root cause
*/
public MessageException(String message, Throwable cause) {
super(message, cause);
@@ -45,7 +51,9 @@
/**
* Creates a new <code>MessageException</code>.
- * @param cause root cause
+ *
+ * @param cause
+ * root cause
*/
public MessageException(Throwable cause) {
super(cause);
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundle.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundle.java
index ef7f249..3518e0d 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundle.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundle.java
@@ -28,44 +28,43 @@
import org.eclipse.babel.core.util.BabelUtils;
/**
- * For a given scope, all messages for a national language.
+ * For a given scope, all messages for a national language.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
-public class MessagesBundle extends AbstractMessageModel
- implements IMessagesResourceChangeListener, IMessagesBundle {
+public class MessagesBundle extends AbstractMessageModel implements
+ IMessagesResourceChangeListener, IMessagesBundle {
private static final long serialVersionUID = -331515196227475652L;
public static final String PROPERTY_COMMENT = "comment"; //$NON-NLS-1$
- public static final String PROPERTY_MESSAGES_COUNT =
- "messagesCount"; //$NON-NLS-1$
+ public static final String PROPERTY_MESSAGES_COUNT = "messagesCount"; //$NON-NLS-1$
- private static final IMessagesBundleListener[] EMPTY_MSG_BUNDLE_LISTENERS =
- new IMessagesBundleListener[] {};
+ private static final IMessagesBundleListener[] EMPTY_MSG_BUNDLE_LISTENERS = new IMessagesBundleListener[] {};
private final Collection<String> orderedKeys = new ArrayList<String>();
private final Map<String, IMessage> keyedMessages = new HashMap<String, IMessage>();
private final IMessagesResource resource;
-
- private final PropertyChangeListener messageListener =
- new PropertyChangeListener(){
- public void propertyChange(PropertyChangeEvent event) {
- fireMessageChanged(event);
- }
+
+ private final PropertyChangeListener messageListener = new PropertyChangeListener() {
+ public void propertyChange(PropertyChangeEvent event) {
+ fireMessageChanged(event);
+ }
};
private String comment;
/**
* Creates a new <code>MessagesBundle</code>.
- * @param resource the messages bundle resource
+ *
+ * @param resource
+ * the messages bundle resource
*/
public MessagesBundle(IMessagesResource resource) {
super();
this.resource = resource;
readFromResource();
// Handle resource changes
- resource.addMessagesResourceChangeListener(
- new IMessagesResourceChangeListener(){
+ resource.addMessagesResourceChangeListener(new IMessagesResourceChangeListener() {
public void resourceChanged(IMessagesResource changedResource) {
readFromResource();
}
@@ -76,6 +75,7 @@
PropertyChangeEvent changeEvent) {
writetoResource();
}
+
public void propertyChange(PropertyChangeEvent evt) {
writetoResource();
}
@@ -86,24 +86,26 @@
* Called before this object will be discarded.
*/
public void dispose() {
- this.resource.dispose();
+ this.resource.dispose();
}
-
+
/**
* Gets the underlying messages resource implementation.
+ *
* @return
*/
public IMessagesResource getResource() {
return resource;
}
-
+
public int getMessagesCount() {
return keyedMessages.size();
}
-
+
/**
- * Gets the locale for the messages bundle (<code>null</code> assumes
- * the default system locale).
+ * Gets the locale for the messages bundle (<code>null</code> assumes the
+ * default system locale).
+ *
* @return Returns the locale.
*/
public Locale getLocale() {
@@ -112,6 +114,7 @@
/**
* Gets the overall comment, or description, for this messages bundle..
+ *
* @return Returns the comment.
*/
public String getComment() {
@@ -120,7 +123,9 @@
/**
* Sets the comment for this messages bundle.
- * @param comment The comment to set.
+ *
+ * @param comment
+ * The comment to set.
*/
public void setComment(String comment) {
Object oldValue = this.comment;
@@ -130,17 +135,18 @@
/**
* @see org.eclipse.babel.core.message.resource
- * .IMessagesResourceChangeListener#resourceChanged(
- * org.eclipse.babel.core.message.internal.resource.IMessagesResource)
+ * .IMessagesResourceChangeListener#resourceChanged(org.eclipse.babel.core.message.internal.resource.IMessagesResource)
*/
public void resourceChanged(IMessagesResource changedResource) {
this.resource.deserialize(this);
}
/**
- * Adds a message to this messages bundle. If the message already exists
- * its properties are updated and no new message is added.
- * @param message the message to add
+ * Adds a message to this messages bundle. If the message already exists its
+ * properties are updated and no new message is added.
+ *
+ * @param message
+ * the message to add
*/
public void addMessage(IMessage message) {
Message m = (Message) message;
@@ -151,8 +157,8 @@
if (!keyedMessages.containsKey(m.getKey())) {
keyedMessages.put(m.getKey(), m);
m.addMessageListener(messageListener);
- firePropertyChange(
- PROPERTY_MESSAGES_COUNT, oldCount, getMessagesCount());
+ firePropertyChange(PROPERTY_MESSAGES_COUNT, oldCount,
+ getMessagesCount());
fireMessageAdded(m);
} else {
// Entry already exists, update it.
@@ -160,9 +166,12 @@
matchingEntry.copyFrom(m);
}
}
+
/**
* Removes a message from this messages bundle.
- * @param messageKey the key of the message to remove
+ *
+ * @param messageKey
+ * the key of the message to remove
*/
public void removeMessage(String messageKey) {
int oldCount = getMessagesCount();
@@ -171,31 +180,36 @@
if (message != null) {
message.removePropertyChangeListener(messageListener);
keyedMessages.remove(messageKey);
- firePropertyChange(
- PROPERTY_MESSAGES_COUNT, oldCount, getMessagesCount());
+ firePropertyChange(PROPERTY_MESSAGES_COUNT, oldCount,
+ getMessagesCount());
fireMessageRemoved(message);
}
}
-
+
/**
- * Removes a message from this messages bundle and adds it's parent key to bundle.
- * E.g.: key = a.b.c gets deleted, a.b gets added with a default message
- * @param messageKey the key of the message to remove
+ * Removes a message from this messages bundle and adds it's parent key to
+ * bundle. E.g.: key = a.b.c gets deleted, a.b gets added with a default
+ * message
+ *
+ * @param messageKey
+ * the key of the message to remove
*/
public void removeMessageAddParentKey(String messageKey) {
- removeMessage(messageKey);
-
+ removeMessage(messageKey);
+
// add parent key
int index = messageKey.lastIndexOf(".");
messageKey = (index == -1 ? "" : messageKey.substring(0, index));
-
- if (! messageKey.isEmpty())
- addMessage(new Message(messageKey, getLocale()));
+
+ if (!messageKey.isEmpty())
+ addMessage(new Message(messageKey, getLocale()));
}
-
+
/**
* Removes messages from this messages bundle.
- * @param messageKeys the keys of the messages to remove
+ *
+ * @param messageKeys
+ * the keys of the messages to remove
*/
public void removeMessages(String[] messageKeys) {
for (int i = 0; i < messageKeys.length; i++) {
@@ -205,14 +219,18 @@
/**
* Renames a message key.
- * @param sourceKey the message key to rename
- * @param targetKey the new key for the message
- * @throws MessageException if the target key already exists
+ *
+ * @param sourceKey
+ * the message key to rename
+ * @param targetKey
+ * the new key for the message
+ * @throws MessageException
+ * if the target key already exists
*/
public void renameMessageKey(String sourceKey, String targetKey) {
if (getMessage(targetKey) != null) {
throw new MessageException(
- "Cannot rename: target key already exists."); //$NON-NLS-1$
+ "Cannot rename: target key already exists."); //$NON-NLS-1$
}
IMessage sourceEntry = getMessage(sourceKey);
if (sourceEntry != null) {
@@ -222,16 +240,21 @@
addMessage(targetEntry);
}
}
+
/**
* Duplicates a message.
- * @param sourceKey the message key to duplicate
- * @param targetKey the new message key
- * @throws MessageException if the target key already exists
+ *
+ * @param sourceKey
+ * the message key to duplicate
+ * @param targetKey
+ * the new message key
+ * @throws MessageException
+ * if the target key already exists
*/
public void duplicateMessage(String sourceKey, String targetKey) {
if (getMessage(sourceKey) != null) {
throw new MessageException(
- "Cannot duplicate: target key already exists."); //$NON-NLS-1$
+ "Cannot duplicate: target key already exists."); //$NON-NLS-1$
}
IMessage sourceEntry = getMessage(sourceKey);
if (sourceEntry != null) {
@@ -243,7 +266,9 @@
/**
* Gets a message.
- * @param key a message key
+ *
+ * @param key
+ * a message key
* @return a message
*/
public IMessage getMessage(String key) {
@@ -252,7 +277,9 @@
/**
* Adds an empty message.
- * @param key the new message key
+ *
+ * @param key
+ * the new message key
*/
public void addMessage(String key) {
addMessage(new Message(key, getLocale()));
@@ -260,14 +287,16 @@
/**
* Gets all message keys making up this messages bundle.
+ *
* @return message keys
*/
public String[] getKeys() {
return orderedKeys.toArray(BabelUtils.EMPTY_STRINGS);
}
-
+
/**
* Obtains the set of <code>Message</code> objects in this bundle.
+ *
* @return a collection of <code>Message</code> objects in this bundle
*/
public Collection<IMessage> getMessages() {
@@ -279,8 +308,8 @@
*/
public String toString() {
String str = "MessagesBundle=[[locale=" + getLocale() //$NON-NLS-1$
- + "][comment=" + comment //$NON-NLS-1$
- + "][entries="; //$NON-NLS-1$
+ + "][comment=" + comment //$NON-NLS-1$
+ + "][entries="; //$NON-NLS-1$
for (IMessage message : getMessages()) {
str += message.toString();
}
@@ -295,14 +324,14 @@
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((comment == null) ? 0 : comment.hashCode());
- result = PRIME * result + ((messageListener == null)
- ? 0 : messageListener.hashCode());
- result = PRIME * result + ((keyedMessages == null)
- ? 0 : keyedMessages.hashCode());
- result = PRIME * result + ((orderedKeys == null)
- ? 0 : orderedKeys.hashCode());
- result = PRIME * result + ((resource == null)
- ? 0 : resource.hashCode());
+ result = PRIME * result
+ + ((messageListener == null) ? 0 : messageListener.hashCode());
+ result = PRIME * result
+ + ((keyedMessages == null) ? 0 : keyedMessages.hashCode());
+ result = PRIME * result
+ + ((orderedKeys == null) ? 0 : orderedKeys.hashCode());
+ result = PRIME * result
+ + ((resource == null) ? 0 : resource.hashCode());
return result;
}
@@ -315,33 +344,33 @@
}
MessagesBundle messagesBundle = (MessagesBundle) obj;
return equals(comment, messagesBundle.comment)
- && equals(keyedMessages, messagesBundle.keyedMessages);
- }
+ && equals(keyedMessages, messagesBundle.keyedMessages);
+ }
public final synchronized void addMessagesBundleListener(
final IMessagesBundleListener listener) {
addPropertyChangeListener(listener);
}
+
public final synchronized void removeMessagesBundleListener(
final IMessagesBundleListener listener) {
removePropertyChangeListener(listener);
}
- public final synchronized IMessagesBundleListener[]
- getMessagesBundleListeners() {
- //TODO find more efficient way to avoid class cast.
- return Arrays.asList(
- getPropertyChangeListeners()).toArray(
- EMPTY_MSG_BUNDLE_LISTENERS);
+
+ public final synchronized IMessagesBundleListener[] getMessagesBundleListeners() {
+ // TODO find more efficient way to avoid class cast.
+ return Arrays.asList(getPropertyChangeListeners()).toArray(
+ EMPTY_MSG_BUNDLE_LISTENERS);
}
-
private void readFromResource() {
this.resource.deserialize(this);
}
+
private void writetoResource() {
this.resource.serialize(this);
}
-
+
private void fireMessageAdded(Message message) {
IMessagesBundleListener[] listeners = getMessagesBundleListeners();
for (int i = 0; i < listeners.length; i++) {
@@ -349,6 +378,7 @@
listener.messageAdded(this, message);
}
}
+
private void fireMessageRemoved(Message message) {
IMessagesBundleListener[] listeners = getMessagesBundleListeners();
for (int i = 0; i < listeners.length; i++) {
@@ -356,6 +386,7 @@
listener.messageRemoved(this, message);
}
}
+
private void fireMessageChanged(PropertyChangeEvent event) {
IMessagesBundleListener[] listeners = getMessagesBundleListeners();
for (int i = 0; i < listeners.length; i++) {
@@ -363,11 +394,13 @@
listener.messageChanged(this, event);
}
}
-
+
/**
- * Returns the value to the given key, if the key exists.
- * Otherwise may throw a NPE.
- * @param key, the key of a message.
+ * Returns the value to the given key, if the key exists. Otherwise may
+ * throw a NPE.
+ *
+ * @param key
+ * , the key of a message.
* @return The value to the given key.
*/
public String getValue(String key) {
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleAdapter.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleAdapter.java
index d33d6c3..7252237 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleAdapter.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleAdapter.java
@@ -13,40 +13,42 @@
import java.beans.PropertyChangeEvent;
/**
- * An adapter class for a {@link IMessagesBundleListener}. Methods
+ * An adapter class for a {@link IMessagesBundleListener}. Methods
* implementation do nothing.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public class MessagesBundleAdapter implements IMessagesBundleListener {
/**
- * @see org.eclipse.babel.core.message.internal.IMessagesBundleListener#messageAdded(
- * org.eclipse.babel.core.message.internal.MessagesBundle,
- * org.eclipse.babel.core.message.internal.Message)
+ * @see org.eclipse.babel.core.message.internal.IMessagesBundleListener#messageAdded(org.eclipse.babel.core.message.internal.MessagesBundle,
+ * org.eclipse.babel.core.message.internal.Message)
*/
public void messageAdded(MessagesBundle messagesBundle, Message message) {
// do nothing
}
+
/**
* @see org.eclipse.babel.core.message.internal.IMessagesBundleListener
* #messageChanged(org.eclipse.babel.core.message.internal.MessagesBundle,
- * java.beans.PropertyChangeEvent)
+ * java.beans.PropertyChangeEvent)
*/
public void messageChanged(MessagesBundle messagesBundle,
PropertyChangeEvent changeEvent) {
// do nothing
}
+
/**
* @see org.eclipse.babel.core.message.internal.IMessagesBundleListener
* #messageRemoved(org.eclipse.babel.core.message.internal.MessagesBundle,
- * org.eclipse.babel.core.message.internal.Message)
+ * org.eclipse.babel.core.message.internal.Message)
*/
public void messageRemoved(MessagesBundle messagesBundle, Message message) {
// do nothing
}
+
/**
- * @see java.beans.PropertyChangeListener#propertyChange(
- * java.beans.PropertyChangeEvent)
+ * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent evt) {
// do nothing
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroup.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroup.java
index 4cc1040..42dc07f 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroup.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroup.java
@@ -38,7 +38,7 @@
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public class MessagesBundleGroup extends AbstractMessageModel implements
- IMessagesBundleGroup {
+ IMessagesBundleGroup {
private String projectName;
@@ -67,24 +67,24 @@
* a IMessagesBundleGroupStrategy instance
*/
public MessagesBundleGroup(IMessagesBundleGroupStrategy groupStrategy) {
- super();
- this.groupStrategy = groupStrategy;
- this.name = groupStrategy.createMessagesBundleGroupName();
- this.resourceBundleId = groupStrategy.createMessagesBundleId();
+ super();
+ this.groupStrategy = groupStrategy;
+ this.name = groupStrategy.createMessagesBundleGroupName();
+ this.resourceBundleId = groupStrategy.createMessagesBundleId();
- this.projectName = groupStrategy.getProjectName();
+ this.projectName = groupStrategy.getProjectName();
- MessagesBundle[] bundles = groupStrategy.loadMessagesBundles();
- if (bundles != null) {
- for (int i = 0; i < bundles.length; i++) {
- addMessagesBundle(bundles[i]);
- }
- }
+ MessagesBundle[] bundles = groupStrategy.loadMessagesBundles();
+ if (bundles != null) {
+ for (int i = 0; i < bundles.length; i++) {
+ addMessagesBundle(bundles[i]);
+ }
+ }
- if (this.projectName != null) {
- RBManager.getInstance(this.projectName)
- .notifyMessagesBundleGroupCreated(this);
- }
+ if (this.projectName != null) {
+ RBManager.getInstance(this.projectName)
+ .notifyMessagesBundleGroupCreated(this);
+ }
}
/**
@@ -93,20 +93,20 @@
*/
@Override
public void dispose() {
- for (IMessagesBundle mb : getMessagesBundles()) {
- try {
- mb.dispose();
- } catch (Throwable t) {
- // FIXME: remove debug:
- System.err.println("Error disposing message-bundle "
- + ((MessagesBundle) mb).getResource()
- .getResourceLocationLabel());
- // disregard crashes: this is a best effort to dispose things.
- }
- }
+ for (IMessagesBundle mb : getMessagesBundles()) {
+ try {
+ mb.dispose();
+ } catch (Throwable t) {
+ // FIXME: remove debug:
+ System.err.println("Error disposing message-bundle "
+ + ((MessagesBundle) mb).getResource()
+ .getResourceLocationLabel());
+ // disregard crashes: this is a best effort to dispose things.
+ }
+ }
- RBManager.getInstance(this.projectName)
- .notifyMessagesBundleGroupDeleted(this);
+ RBManager.getInstance(this.projectName)
+ .notifyMessagesBundleGroupDeleted(this);
}
/**
@@ -118,7 +118,7 @@
*/
@Override
public IMessagesBundle getMessagesBundle(Locale locale) {
- return localeBundles.get(locale);
+ return localeBundles.get(locale);
}
/**
@@ -133,13 +133,13 @@
* @see IMessagesResource
*/
public MessagesBundle getMessagesBundle(Object source) {
- for (IMessagesBundle messagesBundle : getMessagesBundles()) {
- if (equals(source, ((MessagesBundle) messagesBundle).getResource()
- .getSource())) {
- return (MessagesBundle) messagesBundle;
- }
- }
- return null;
+ for (IMessagesBundle messagesBundle : getMessagesBundles()) {
+ if (equals(source, ((MessagesBundle) messagesBundle).getResource()
+ .getSource())) {
+ return (MessagesBundle) messagesBundle;
+ }
+ }
+ return null;
}
/**
@@ -150,14 +150,14 @@
* locale for the new bundle added
*/
public void addMessagesBundle(Locale locale) {
- addMessagesBundle(groupStrategy.createMessagesBundle(locale));
+ addMessagesBundle(groupStrategy.createMessagesBundle(locale));
}
/**
* Gets all locales making up this messages bundle group.
*/
public Locale[] getLocales() {
- return localeBundles.keySet().toArray(EMPTY_LOCALES);
+ return localeBundles.keySet().toArray(EMPTY_LOCALES);
}
/**
@@ -169,14 +169,14 @@
*/
@Override
public IMessage[] getMessages(String key) {
- List<IMessage> messages = new ArrayList<IMessage>();
- for (IMessagesBundle messagesBundle : getMessagesBundles()) {
- IMessage message = messagesBundle.getMessage(key);
- if (message != null) {
- messages.add(message);
- }
- }
- return messages.toArray(EMPTY_MESSAGES);
+ List<IMessage> messages = new ArrayList<IMessage>();
+ for (IMessagesBundle messagesBundle : getMessagesBundles()) {
+ IMessage message = messagesBundle.getMessage(key);
+ if (message != null) {
+ messages.add(message);
+ }
+ }
+ return messages.toArray(EMPTY_MESSAGES);
}
/**
@@ -190,11 +190,11 @@
*/
@Override
public IMessage getMessage(String key, Locale locale) {
- IMessagesBundle messagesBundle = getMessagesBundle(locale);
- if (messagesBundle != null) {
- return messagesBundle.getMessage(key);
- }
- return null;
+ IMessagesBundle messagesBundle = getMessagesBundle(locale);
+ if (messagesBundle != null) {
+ return messagesBundle.getMessage(key);
+ }
+ return null;
}
/**
@@ -206,7 +206,7 @@
* if a messages bundle for the same locale already exists.
*/
public void addMessagesBundle(IMessagesBundle messagesBundle) {
- addMessagesBundle(messagesBundle.getLocale(), messagesBundle);
+ addMessagesBundle(messagesBundle.getLocale(), messagesBundle);
}
/**
@@ -221,30 +221,30 @@
*/
@Override
public void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle) {
- MessagesBundle mb = (MessagesBundle) messagesBundle;
- if (localeBundles.get(mb.getLocale()) != null) {
- throw new MessageException(
- "A bundle with the same locale already exists."); //$NON-NLS-1$
- }
+ MessagesBundle mb = (MessagesBundle) messagesBundle;
+ if (localeBundles.get(mb.getLocale()) != null) {
+ throw new MessageException(
+ "A bundle with the same locale already exists."); //$NON-NLS-1$
+ }
- int oldBundleCount = localeBundles.size();
- localeBundles.put(mb.getLocale(), mb);
+ int oldBundleCount = localeBundles.size();
+ localeBundles.put(mb.getLocale(), mb);
- firePropertyChange(PROPERTY_MESSAGES_BUNDLE_COUNT, oldBundleCount,
- localeBundles.size());
- fireMessagesBundleAdded(mb);
+ firePropertyChange(PROPERTY_MESSAGES_BUNDLE_COUNT, oldBundleCount,
+ localeBundles.size());
+ fireMessagesBundleAdded(mb);
- String[] bundleKeys = mb.getKeys();
- for (int i = 0; i < bundleKeys.length; i++) {
- String key = bundleKeys[i];
- if (!keys.contains(key)) {
- int oldKeyCount = keys.size();
- keys.add(key);
- firePropertyChange(PROPERTY_KEY_COUNT, oldKeyCount, keys.size());
- fireKeyAdded(key);
- }
- }
- mb.addMessagesBundleListener(messagesBundleListener);
+ String[] bundleKeys = mb.getKeys();
+ for (int i = 0; i < bundleKeys.length; i++) {
+ String key = bundleKeys[i];
+ if (!keys.contains(key)) {
+ int oldKeyCount = keys.size();
+ keys.add(key);
+ firePropertyChange(PROPERTY_KEY_COUNT, oldKeyCount, keys.size());
+ fireKeyAdded(key);
+ }
+ }
+ mb.addMessagesBundleListener(messagesBundleListener);
}
@@ -256,29 +256,29 @@
*/
@Override
public void removeMessagesBundle(IMessagesBundle messagesBundle) {
- Locale locale = messagesBundle.getLocale();
+ Locale locale = messagesBundle.getLocale();
- if (localeBundles.containsKey(locale)) {
- localeBundles.remove(locale);
- }
+ if (localeBundles.containsKey(locale)) {
+ localeBundles.remove(locale);
+ }
- // which keys should I not remove?
- Set<String> keysNotToRemove = new TreeSet<String>();
+ // which keys should I not remove?
+ Set<String> keysNotToRemove = new TreeSet<String>();
- for (String key : messagesBundle.getKeys()) {
- for (IMessagesBundle bundle : localeBundles.values()) {
- if (bundle.getMessage(key) != null) {
- keysNotToRemove.add(key);
- }
- }
- }
+ for (String key : messagesBundle.getKeys()) {
+ for (IMessagesBundle bundle : localeBundles.values()) {
+ if (bundle.getMessage(key) != null) {
+ keysNotToRemove.add(key);
+ }
+ }
+ }
- // remove keys
- for (String keyToRemove : messagesBundle.getKeys()) {
- if (!keysNotToRemove.contains(keyToRemove)) { // we can remove
- keys.remove(keyToRemove);
- }
- }
+ // remove keys
+ for (String keyToRemove : messagesBundle.getKeys()) {
+ if (!keysNotToRemove.contains(keyToRemove)) { // we can remove
+ keys.remove(keyToRemove);
+ }
+ }
}
/**
@@ -289,7 +289,7 @@
*/
@Override
public String getName() {
- return name;
+ return name;
}
/**
@@ -301,9 +301,9 @@
*/
@Override
public void addMessages(String key) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- ((MessagesBundle) msgBundle).addMessage(key);
- }
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ ((MessagesBundle) msgBundle).addMessage(key);
+ }
}
/**
@@ -315,9 +315,9 @@
* the new message name
*/
public void renameMessageKeys(String sourceKey, String targetKey) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- msgBundle.renameMessageKey(sourceKey, targetKey);
- }
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ msgBundle.renameMessageKey(sourceKey, targetKey);
+ }
}
/**
@@ -328,9 +328,9 @@
*/
@Override
public void removeMessages(String key) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- msgBundle.removeMessage(key);
- }
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ msgBundle.removeMessage(key);
+ }
}
/**
@@ -342,9 +342,9 @@
*/
@Override
public void removeMessagesAddParentKey(String key) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- msgBundle.removeMessageAddParentKey(key);
- }
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ msgBundle.removeMessageAddParentKey(key);
+ }
}
/**
@@ -354,12 +354,12 @@
* key of messages
*/
public void setMessagesActive(String key, boolean active) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- IMessage entry = msgBundle.getMessage(key);
- if (entry != null) {
- entry.setActive(active);
- }
- }
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ IMessage entry = msgBundle.getMessage(key);
+ if (entry != null) {
+ entry.setActive(active);
+ }
+ }
}
/**
@@ -374,12 +374,12 @@
* if a target key already exists
*/
public void duplicateMessages(String sourceKey, String targetKey) {
- if (sourceKey.equals(targetKey)) {
- return;
- }
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- msgBundle.duplicateMessage(sourceKey, targetKey);
- }
+ if (sourceKey.equals(targetKey)) {
+ return;
+ }
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ msgBundle.duplicateMessage(sourceKey, targetKey);
+ }
}
/**
@@ -389,7 +389,7 @@
*/
@Override
public Collection<IMessagesBundle> getMessagesBundles() {
- return localeBundles.values();
+ return localeBundles.values();
}
/**
@@ -399,7 +399,7 @@
*/
@Override
public String[] getMessageKeys() {
- return keys.toArray(BabelUtils.EMPTY_STRINGS);
+ return keys.toArray(BabelUtils.EMPTY_STRINGS);
}
/**
@@ -411,7 +411,7 @@
*/
@Override
public boolean isMessageKey(String key) {
- return keys.contains(key);
+ return keys.contains(key);
}
/**
@@ -421,7 +421,7 @@
*/
@Override
public int getMessagesBundleCount() {
- return localeBundles.size();
+ return localeBundles.size();
}
/**
@@ -429,59 +429,59 @@
*/
@Override
public boolean equals(Object obj) {
- if (!(obj instanceof MessagesBundleGroup)) {
- return false;
- }
- MessagesBundleGroup messagesBundleGroup = (MessagesBundleGroup) obj;
- return equals(localeBundles, messagesBundleGroup.localeBundles);
+ if (!(obj instanceof MessagesBundleGroup)) {
+ return false;
+ }
+ MessagesBundleGroup messagesBundleGroup = (MessagesBundleGroup) obj;
+ return equals(localeBundles, messagesBundleGroup.localeBundles);
}
public final synchronized void addMessagesBundleGroupListener(
- final IMessagesBundleGroupListener listener) {
- addPropertyChangeListener(listener);
+ final IMessagesBundleGroupListener listener) {
+ addPropertyChangeListener(listener);
}
public final synchronized void removeMessagesBundleGroupListener(
- final IMessagesBundleGroupListener listener) {
- removePropertyChangeListener(listener);
+ final IMessagesBundleGroupListener listener) {
+ removePropertyChangeListener(listener);
}
public final synchronized IMessagesBundleGroupListener[] getMessagesBundleGroupListeners() {
- // TODO find more efficient way to avoid class cast.
- return Arrays.asList(getPropertyChangeListeners()).toArray(
- EMPTY_GROUP_LISTENERS);
+ // TODO find more efficient way to avoid class cast.
+ return Arrays.asList(getPropertyChangeListeners()).toArray(
+ EMPTY_GROUP_LISTENERS);
}
private void fireKeyAdded(String key) {
- IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.keyAdded(key);
- }
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.keyAdded(key);
+ }
}
private void fireKeyRemoved(String key) {
- IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.keyRemoved(key);
- }
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.keyRemoved(key);
+ }
}
private void fireMessagesBundleAdded(MessagesBundle messagesBundle) {
- IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messagesBundleAdded(messagesBundle);
- }
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messagesBundleAdded(messagesBundle);
+ }
}
private void fireMessagesBundleRemoved(MessagesBundle messagesBundle) {
- IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messagesBundleRemoved(messagesBundle);
- }
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messagesBundleRemoved(messagesBundle);
+ }
}
/**
@@ -494,17 +494,17 @@
*/
@Override
public boolean containsKey(String key) {
- for (Locale locale : localeBundles.keySet()) {
- IMessagesBundle messagesBundle = localeBundles.get(locale);
- for (String k : messagesBundle.getKeys()) {
- if (k.equals(key)) {
- return true;
- } else {
- continue;
- }
- }
- }
- return false;
+ for (Locale locale : localeBundles.keySet()) {
+ IMessagesBundle messagesBundle = localeBundles.get(locale);
+ for (String k : messagesBundle.getKeys()) {
+ if (k.equals(key)) {
+ return true;
+ } else {
+ continue;
+ }
+ }
+ }
+ return false;
}
/**
@@ -516,7 +516,7 @@
*/
@Override
public boolean isKey(String key) {
- return keys.contains(key);
+ return keys.contains(key);
}
/**
@@ -528,7 +528,7 @@
*/
@Override
public String getResourceBundleId() {
- return resourceBundleId;
+ return resourceBundleId;
}
/**
@@ -538,7 +538,7 @@
*/
@Override
public String getProjectName() {
- return this.projectName;
+ return this.projectName;
}
/**
@@ -546,60 +546,60 @@
* to the listeners for MessagesBundleGroup.
*/
private class MessagesBundleListener implements IMessagesBundleListener {
- @Override
- public void messageAdded(MessagesBundle messagesBundle, Message message) {
- int oldCount = keys.size();
- IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messageAdded(messagesBundle, message);
- if (getMessages(message.getKey()).length == 1) {
- keys.add(message.getKey());
- firePropertyChange(PROPERTY_KEY_COUNT, oldCount,
- keys.size());
- fireKeyAdded(message.getKey());
- }
- }
- }
+ @Override
+ public void messageAdded(MessagesBundle messagesBundle, Message message) {
+ int oldCount = keys.size();
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messageAdded(messagesBundle, message);
+ if (getMessages(message.getKey()).length == 1) {
+ keys.add(message.getKey());
+ firePropertyChange(PROPERTY_KEY_COUNT, oldCount,
+ keys.size());
+ fireKeyAdded(message.getKey());
+ }
+ }
+ }
- @Override
- public void messageRemoved(MessagesBundle messagesBundle,
- Message message) {
- int oldCount = keys.size();
- IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messageRemoved(messagesBundle, message);
- int keyMessagesCount = getMessages(message.getKey()).length;
- if (keyMessagesCount == 0 && keys.contains(message.getKey())) {
- keys.remove(message.getKey());
- firePropertyChange(PROPERTY_KEY_COUNT, oldCount,
- keys.size());
- fireKeyRemoved(message.getKey());
- }
- }
- }
+ @Override
+ public void messageRemoved(MessagesBundle messagesBundle,
+ Message message) {
+ int oldCount = keys.size();
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messageRemoved(messagesBundle, message);
+ int keyMessagesCount = getMessages(message.getKey()).length;
+ if (keyMessagesCount == 0 && keys.contains(message.getKey())) {
+ keys.remove(message.getKey());
+ firePropertyChange(PROPERTY_KEY_COUNT, oldCount,
+ keys.size());
+ fireKeyRemoved(message.getKey());
+ }
+ }
+ }
- @Override
- public void messageChanged(MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messageChanged(messagesBundle, changeEvent);
- }
- }
+ @Override
+ public void messageChanged(MessagesBundle messagesBundle,
+ PropertyChangeEvent changeEvent) {
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messageChanged(messagesBundle, changeEvent);
+ }
+ }
- // MessagesBundle property changes:
- @Override
- public void propertyChange(PropertyChangeEvent evt) {
- MessagesBundle bundle = (MessagesBundle) evt.getSource();
- IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messagesBundleChanged(bundle, evt);
- }
- }
+ // MessagesBundle property changes:
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+ MessagesBundle bundle = (MessagesBundle) evt.getSource();
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messagesBundleChanged(bundle, evt);
+ }
+ }
}
/**
@@ -610,6 +610,6 @@
*/
@Override
public boolean hasPropertiesFileGroupStrategy() {
- return groupStrategy instanceof PropertiesFileGroupStrategy;
+ return groupStrategy instanceof PropertiesFileGroupStrategy;
}
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroupAdapter.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroupAdapter.java
index 0a1a696..ebf43a4 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroupAdapter.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroupAdapter.java
@@ -3,26 +3,28 @@
import java.beans.PropertyChangeEvent;
/**
- * An adapter class for a {@link IMessagesBundleGroupListener}. Methods
+ * An adapter class for a {@link IMessagesBundleGroupListener}. Methods
* implementation do nothing.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
-public class MessagesBundleGroupAdapter
- implements IMessagesBundleGroupListener {
+public class MessagesBundleGroupAdapter implements IMessagesBundleGroupListener {
/**
* @see org.eclipse.babel.core.message.internal.IMessagesBundleGroupListener#
- * keyAdded(java.lang.String)
+ * keyAdded(java.lang.String)
*/
public void keyAdded(String key) {
// do nothing
}
+
/**
* @see org.eclipse.babel.core.message.internal.IMessagesBundleGroupListener#
- * keyRemoved(java.lang.String)
+ * keyRemoved(java.lang.String)
*/
public void keyRemoved(String key) {
// do nothing
}
+
/**
* @see org.eclipse.babel.core.message.internal.IMessagesBundleGroupListener#
* messagesBundleAdded(org.eclipse.babel.core.message.internal.MessagesBundle)
@@ -30,50 +32,54 @@
public void messagesBundleAdded(MessagesBundle messagesBundle) {
// do nothing
}
+
/**
* @see org.eclipse.babel.core.message.internal.IMessagesBundleGroupListener#
* messagesBundleChanged(org.eclipse.babel.core.message.internal.MessagesBundle,
- * java.beans.PropertyChangeEvent)
+ * java.beans.PropertyChangeEvent)
*/
public void messagesBundleChanged(MessagesBundle messagesBundle,
PropertyChangeEvent changeEvent) {
// do nothing
}
+
/**
* @see org.eclipse.babel.core.message.internal.IMessagesBundleGroupListener
- * #messagesBundleRemoved(org.eclipse.babel.core.message.internal.MessagesBundle)
+ * #messagesBundleRemoved(org.eclipse.babel.core.message.internal.MessagesBundle)
*/
public void messagesBundleRemoved(MessagesBundle messagesBundle) {
// do nothing
}
+
/**
- * @see org.eclipse.babel.core.message.internal.IMessagesBundleListener#messageAdded(
- * org.eclipse.babel.core.message.internal.MessagesBundle,
- * org.eclipse.babel.core.message.internal.Message)
+ * @see org.eclipse.babel.core.message.internal.IMessagesBundleListener#messageAdded(org.eclipse.babel.core.message.internal.MessagesBundle,
+ * org.eclipse.babel.core.message.internal.Message)
*/
public void messageAdded(MessagesBundle messagesBundle, Message message) {
// do nothing
}
+
/**
* @see org.eclipse.babel.core.message.internal.IMessagesBundleListener#
* messageChanged(org.eclipse.babel.core.message.internal.MessagesBundle,
- * java.beans.PropertyChangeEvent)
+ * java.beans.PropertyChangeEvent)
*/
public void messageChanged(MessagesBundle messagesBundle,
PropertyChangeEvent changeEvent) {
// do nothing
}
+
/**
* @see org.eclipse.babel.core.message.internal.IMessagesBundleListener#
* messageRemoved(org.eclipse.babel.core.message.internal.MessagesBundle,
- * org.eclipse.babel.core.message.internal.Message)
+ * org.eclipse.babel.core.message.internal.Message)
*/
public void messageRemoved(MessagesBundle messagesBundle, Message message) {
// do nothing
}
+
/**
- * @see java.beans.PropertyChangeListener#propertyChange(
- * java.beans.PropertyChangeEvent)
+ * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent evt) {
// do nothing
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IMessagesEditorListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IMessagesEditorListener.java
index a3d04c5..22f9975 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IMessagesEditorListener.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IMessagesEditorListener.java
@@ -13,28 +13,29 @@
import org.eclipse.babel.core.message.IMessagesBundle;
/**
- * Used to sync TapiJI with Babel and vice versa.
- * <br><br>
+ * Used to sync TapiJI with Babel and vice versa. <br>
+ * <br>
*
* @author Alexej Strelzow
*/
public interface IMessagesEditorListener {
- /**
- * Should only be called when the editor performs save!
- */
- void onSave();
-
- /**
- * Can be called when the Editor changes.
- */
- void onModify();
-
- /**
- * Called when a {@link IMessagesBundle} changed.
- * @param bundle
- */
- void onResourceChanged(IMessagesBundle bundle);
- // TODO: Get rid of this method, maybe merge with onModify()
-
+ /**
+ * Should only be called when the editor performs save!
+ */
+ void onSave();
+
+ /**
+ * Can be called when the Editor changes.
+ */
+ void onModify();
+
+ /**
+ * Called when a {@link IMessagesBundle} changed.
+ *
+ * @param bundle
+ */
+ void onResourceChanged(IMessagesBundle bundle);
+ // TODO: Get rid of this method, maybe merge with onModify()
+
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IResourceDeltaListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IResourceDeltaListener.java
index fba2d0f..9ada1f5 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IResourceDeltaListener.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IResourceDeltaListener.java
@@ -13,26 +13,30 @@
import org.eclipse.babel.core.message.IMessagesBundleGroup;
import org.eclipse.core.resources.IResource;
-
/**
- * Used to update TapiJI (ResourceBundleManager) when bundles have been removed.
- * <br><br>
+ * Used to update TapiJI (ResourceBundleManager) when bundles have been removed. <br>
+ * <br>
*
* @author Alexej Strelzow
*/
public interface IResourceDeltaListener {
- /**
- * Called when a resource (= bundle) has been removed
- * @param resourceBundleId The {@link IMessagesBundleGroup} which contains the bundle
- * @param resource The resource itself
- */
- public void onDelete(String resourceBundleId, IResource resource);
-
- /**
- * Called when a {@link IMessagesBundleGroup} has been removed
- * @param bundleGroup The removed bundle group
- */
- public void onDelete(IMessagesBundleGroup bundleGroup);
-
+ /**
+ * Called when a resource (= bundle) has been removed
+ *
+ * @param resourceBundleId
+ * The {@link IMessagesBundleGroup} which contains the bundle
+ * @param resource
+ * The resource itself
+ */
+ public void onDelete(String resourceBundleId, IResource resource);
+
+ /**
+ * Called when a {@link IMessagesBundleGroup} has been removed
+ *
+ * @param bundleGroup
+ * The removed bundle group
+ */
+ public void onDelete(IMessagesBundleGroup bundleGroup);
+
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/RBManager.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/RBManager.java
index 0cb5378..fa37f86 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/RBManager.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/RBManager.java
@@ -64,12 +64,12 @@
private static final String TAPIJI_NATURE = "org.eclipse.babel.tapiji.tools.core.ui.nature";
private static Logger logger = Logger.getLogger(RBManager.class
- .getSimpleName());
+ .getSimpleName());
private RBManager() {
- resourceBundles = new HashMap<String, IMessagesBundleGroup>();
- editorListeners = new ArrayList<IMessagesEditorListener>(3);
- resourceListeners = new ArrayList<IResourceDeltaListener>(2);
+ resourceBundles = new HashMap<String, IMessagesBundleGroup>();
+ editorListeners = new ArrayList<IMessagesEditorListener>(3);
+ resourceListeners = new ArrayList<IResourceDeltaListener>(2);
}
/**
@@ -78,14 +78,14 @@
* @return {@link IMessagesBundleGroup} if found, else <code>null</code>
*/
public IMessagesBundleGroup getMessagesBundleGroup(String resourceBundleId) {
- if (!resourceBundles.containsKey(resourceBundleId)) {
- logger.log(Level.SEVERE,
- "getMessagesBundleGroup with non-existing Id: "
- + resourceBundleId);
- return null;
- } else {
- return resourceBundles.get(resourceBundleId);
- }
+ if (!resourceBundles.containsKey(resourceBundleId)) {
+ logger.log(Level.SEVERE,
+ "getMessagesBundleGroup with non-existing Id: "
+ + resourceBundleId);
+ return null;
+ } else {
+ return resourceBundles.get(resourceBundleId);
+ }
}
/**
@@ -93,12 +93,12 @@
* <projectName>/<resourceBundleId>
*/
public List<String> getMessagesBundleGroupNames() {
- List<String> bundleGroupNames = new ArrayList<String>();
+ List<String> bundleGroupNames = new ArrayList<String>();
- for (String key : resourceBundles.keySet()) {
- bundleGroupNames.add(project.getName() + "/" + key);
- }
- return bundleGroupNames;
+ for (String key : resourceBundles.keySet()) {
+ bundleGroupNames.add(project.getName() + "/" + key);
+ }
+ return bundleGroupNames;
}
/**
@@ -106,17 +106,17 @@
* projects.
*/
public static List<String> getAllMessagesBundleGroupNames() {
- List<String> bundleGroupNames = new ArrayList<String>();
+ List<String> bundleGroupNames = new ArrayList<String>();
- for (IProject project : getAllSupportedProjects()) {
- RBManager manager = getInstance(project);
- for (String name : manager.getMessagesBundleGroupNames()) {
- if (!bundleGroupNames.contains(name)) {
- bundleGroupNames.add(name);
- }
- }
- }
- return bundleGroupNames;
+ for (IProject project : getAllSupportedProjects()) {
+ RBManager manager = getInstance(project);
+ for (String name : manager.getMessagesBundleGroupNames()) {
+ if (!bundleGroupNames.contains(name)) {
+ bundleGroupNames.add(name);
+ }
+ }
+ }
+ return bundleGroupNames;
}
/**
@@ -127,74 +127,74 @@
* The new {@link IMessagesBundleGroup}
*/
public void notifyMessagesBundleGroupCreated(
- IMessagesBundleGroup bundleGroup) {
- if (resourceBundles.containsKey(bundleGroup.getResourceBundleId())) {
- IMessagesBundleGroup oldbundleGroup = resourceBundles
- .get(bundleGroup.getResourceBundleId());
+ IMessagesBundleGroup bundleGroup) {
+ if (resourceBundles.containsKey(bundleGroup.getResourceBundleId())) {
+ IMessagesBundleGroup oldbundleGroup = resourceBundles
+ .get(bundleGroup.getResourceBundleId());
- // not the same object
- if (!equalHash(oldbundleGroup, bundleGroup)) {
- // we need to distinguish between 2 kinds of resources:
- // 1) Property-File
- // 2) Eclipse-Editor
- // When first 1) is used, and some operations where made, we
- // need to
- // sync 2) when it appears!
- boolean oldHasPropertiesStrategy = oldbundleGroup
- .hasPropertiesFileGroupStrategy();
- boolean newHasPropertiesStrategy = bundleGroup
- .hasPropertiesFileGroupStrategy();
+ // not the same object
+ if (!equalHash(oldbundleGroup, bundleGroup)) {
+ // we need to distinguish between 2 kinds of resources:
+ // 1) Property-File
+ // 2) Eclipse-Editor
+ // When first 1) is used, and some operations where made, we
+ // need to
+ // sync 2) when it appears!
+ boolean oldHasPropertiesStrategy = oldbundleGroup
+ .hasPropertiesFileGroupStrategy();
+ boolean newHasPropertiesStrategy = bundleGroup
+ .hasPropertiesFileGroupStrategy();
- // in this case, the old one is only writing to the property
- // file, not the editor
- // we have to sync them and store the bundle with the editor as
- // resource
- if (oldHasPropertiesStrategy && !newHasPropertiesStrategy) {
+ // in this case, the old one is only writing to the property
+ // file, not the editor
+ // we have to sync them and store the bundle with the editor as
+ // resource
+ if (oldHasPropertiesStrategy && !newHasPropertiesStrategy) {
- syncBundles(bundleGroup, oldbundleGroup);
- resourceBundles.put(bundleGroup.getResourceBundleId(),
- bundleGroup);
+ syncBundles(bundleGroup, oldbundleGroup);
+ resourceBundles.put(bundleGroup.getResourceBundleId(),
+ bundleGroup);
- logger.log(
- Level.INFO,
- "sync: " + bundleGroup.getResourceBundleId()
- + " with "
- + oldbundleGroup.getResourceBundleId());
+ logger.log(
+ Level.INFO,
+ "sync: " + bundleGroup.getResourceBundleId()
+ + " with "
+ + oldbundleGroup.getResourceBundleId());
- oldbundleGroup.dispose();
+ oldbundleGroup.dispose();
- } else if ((oldHasPropertiesStrategy && newHasPropertiesStrategy)
- || (!oldHasPropertiesStrategy && !newHasPropertiesStrategy)) {
+ } else if ((oldHasPropertiesStrategy && newHasPropertiesStrategy)
+ || (!oldHasPropertiesStrategy && !newHasPropertiesStrategy)) {
- // syncBundles(oldbundleGroup, bundleGroup); do not need
- // that, because we take the new one
- // and we do that, because otherwise we cache old
- // Text-Editor instances, which we
- // do not need -> read only phenomenon
- resourceBundles.put(bundleGroup.getResourceBundleId(),
- bundleGroup);
+ // syncBundles(oldbundleGroup, bundleGroup); do not need
+ // that, because we take the new one
+ // and we do that, because otherwise we cache old
+ // Text-Editor instances, which we
+ // do not need -> read only phenomenon
+ resourceBundles.put(bundleGroup.getResourceBundleId(),
+ bundleGroup);
- logger.log(
- Level.INFO,
- "replace: " + bundleGroup.getResourceBundleId()
- + " with "
- + oldbundleGroup.getResourceBundleId());
+ logger.log(
+ Level.INFO,
+ "replace: " + bundleGroup.getResourceBundleId()
+ + " with "
+ + oldbundleGroup.getResourceBundleId());
- oldbundleGroup.dispose();
- } else {
- // in this case our old resource has an EditorSite, but not
- // the new one
- logger.log(Level.INFO,
- "dispose: " + bundleGroup.getResourceBundleId());
+ oldbundleGroup.dispose();
+ } else {
+ // in this case our old resource has an EditorSite, but not
+ // the new one
+ logger.log(Level.INFO,
+ "dispose: " + bundleGroup.getResourceBundleId());
- bundleGroup.dispose();
- }
- }
- } else {
- resourceBundles.put(bundleGroup.getResourceBundleId(), bundleGroup);
+ bundleGroup.dispose();
+ }
+ }
+ } else {
+ resourceBundles.put(bundleGroup.getResourceBundleId(), bundleGroup);
- logger.log(Level.INFO, "add: " + bundleGroup.getResourceBundleId());
- }
+ logger.log(Level.INFO, "add: " + bundleGroup.getResourceBundleId());
+ }
}
/**
@@ -204,18 +204,18 @@
* The {@link IMessagesBundleGroup} to remove
*/
public void notifyMessagesBundleGroupDeleted(
- IMessagesBundleGroup bundleGroup) {
- if (resourceBundles.containsKey(bundleGroup.getResourceBundleId())) {
- if (equalHash(
- resourceBundles.get(bundleGroup.getResourceBundleId()),
- bundleGroup)) {
- resourceBundles.remove(bundleGroup.getResourceBundleId());
+ IMessagesBundleGroup bundleGroup) {
+ if (resourceBundles.containsKey(bundleGroup.getResourceBundleId())) {
+ if (equalHash(
+ resourceBundles.get(bundleGroup.getResourceBundleId()),
+ bundleGroup)) {
+ resourceBundles.remove(bundleGroup.getResourceBundleId());
- for (IResourceDeltaListener deltaListener : resourceListeners) {
- deltaListener.onDelete(bundleGroup);
- }
- }
- }
+ for (IResourceDeltaListener deltaListener : resourceListeners) {
+ deltaListener.onDelete(bundleGroup);
+ }
+ }
+ }
}
/**
@@ -226,31 +226,31 @@
* The removed {@link MessagesBundle}
*/
public void notifyResourceRemoved(IResource resourceBundle) {
- String resourceBundleId = NameUtils.getResourceBundleId(resourceBundle);
+ String resourceBundleId = NameUtils.getResourceBundleId(resourceBundle);
- IMessagesBundleGroup bundleGroup = resourceBundles
- .get(resourceBundleId);
+ IMessagesBundleGroup bundleGroup = resourceBundles
+ .get(resourceBundleId);
- if (bundleGroup != null) {
- Locale locale = NameUtils.getLocaleByName(
- NameUtils.getResourceBundleName(resourceBundle),
- resourceBundle.getName());
- IMessagesBundle messagesBundle = bundleGroup
- .getMessagesBundle(locale);
- if (messagesBundle != null) {
- bundleGroup.removeMessagesBundle(messagesBundle);
- }
+ if (bundleGroup != null) {
+ Locale locale = NameUtils.getLocaleByName(
+ NameUtils.getResourceBundleName(resourceBundle),
+ resourceBundle.getName());
+ IMessagesBundle messagesBundle = bundleGroup
+ .getMessagesBundle(locale);
+ if (messagesBundle != null) {
+ bundleGroup.removeMessagesBundle(messagesBundle);
+ }
- for (IResourceDeltaListener deltaListener : resourceListeners) {
- deltaListener.onDelete(resourceBundleId, resourceBundle);
- }
+ for (IResourceDeltaListener deltaListener : resourceListeners) {
+ deltaListener.onDelete(resourceBundleId, resourceBundle);
+ }
- if (bundleGroup.getMessagesBundleCount() == 0) {
- notifyMessagesBundleGroupDeleted(bundleGroup);
- }
- }
+ if (bundleGroup.getMessagesBundleCount() == 0) {
+ notifyMessagesBundleGroupDeleted(bundleGroup);
+ }
+ }
- // TODO: maybe save and reinit the editor?
+ // TODO: maybe save and reinit the editor?
}
@@ -266,8 +266,8 @@
* <code>false</code>
*/
private boolean equalHash(IMessagesBundleGroup oldBundleGroup,
- IMessagesBundleGroup newBundleGroup) {
- return oldBundleGroup.hashCode() == newBundleGroup.hashCode();
+ IMessagesBundleGroup newBundleGroup) {
+ return oldBundleGroup.hashCode() == newBundleGroup.hashCode();
}
/**
@@ -281,68 +281,68 @@
* The replacement
*/
private void syncBundles(IMessagesBundleGroup oldBundleGroup,
- IMessagesBundleGroup newBundleGroup) {
- List<IMessagesBundle> bundlesToRemove = new ArrayList<IMessagesBundle>();
- List<IMessage> keysToRemove = new ArrayList<IMessage>();
+ IMessagesBundleGroup newBundleGroup) {
+ List<IMessagesBundle> bundlesToRemove = new ArrayList<IMessagesBundle>();
+ List<IMessage> keysToRemove = new ArrayList<IMessage>();
- DirtyHack.setFireEnabled(false); // hebelt AbstractMessageModel aus
- // sonst m�ssten wir in setText von EclipsePropertiesEditorResource
- // ein
- // asyncExec zulassen
+ DirtyHack.setFireEnabled(false); // hebelt AbstractMessageModel aus
+ // sonst m�ssten wir in setText von EclipsePropertiesEditorResource
+ // ein
+ // asyncExec zulassen
- for (IMessagesBundle newBundle : newBundleGroup.getMessagesBundles()) {
- IMessagesBundle oldBundle = oldBundleGroup
- .getMessagesBundle(newBundle.getLocale());
- if (oldBundle == null) { // it's a new one
- oldBundleGroup.addMessagesBundle(newBundle.getLocale(),
- newBundle);
- } else { // check keys
- for (IMessage newMsg : newBundle.getMessages()) {
- if (oldBundle.getMessage(newMsg.getKey()) == null) {
- // new entry, create new message
- oldBundle.addMessage(new Message(newMsg.getKey(),
- newMsg.getLocale()));
- } else { // update old entries
- IMessage oldMsg = oldBundle.getMessage(newMsg.getKey());
- if (oldMsg == null) { // it's a new one
- oldBundle.addMessage(newMsg);
- } else { // check value
- oldMsg.setComment(newMsg.getComment());
- oldMsg.setText(newMsg.getValue());
- }
- }
- }
- }
- }
+ for (IMessagesBundle newBundle : newBundleGroup.getMessagesBundles()) {
+ IMessagesBundle oldBundle = oldBundleGroup
+ .getMessagesBundle(newBundle.getLocale());
+ if (oldBundle == null) { // it's a new one
+ oldBundleGroup.addMessagesBundle(newBundle.getLocale(),
+ newBundle);
+ } else { // check keys
+ for (IMessage newMsg : newBundle.getMessages()) {
+ if (oldBundle.getMessage(newMsg.getKey()) == null) {
+ // new entry, create new message
+ oldBundle.addMessage(new Message(newMsg.getKey(),
+ newMsg.getLocale()));
+ } else { // update old entries
+ IMessage oldMsg = oldBundle.getMessage(newMsg.getKey());
+ if (oldMsg == null) { // it's a new one
+ oldBundle.addMessage(newMsg);
+ } else { // check value
+ oldMsg.setComment(newMsg.getComment());
+ oldMsg.setText(newMsg.getValue());
+ }
+ }
+ }
+ }
+ }
- // check keys
- for (IMessagesBundle oldBundle : oldBundleGroup.getMessagesBundles()) {
- IMessagesBundle newBundle = newBundleGroup
- .getMessagesBundle(oldBundle.getLocale());
- if (newBundle == null) { // we have an old one
- bundlesToRemove.add(oldBundle);
- } else {
- for (IMessage oldMsg : oldBundle.getMessages()) {
- if (newBundle.getMessage(oldMsg.getKey()) == null) {
- keysToRemove.add(oldMsg);
- }
- }
- }
- }
+ // check keys
+ for (IMessagesBundle oldBundle : oldBundleGroup.getMessagesBundles()) {
+ IMessagesBundle newBundle = newBundleGroup
+ .getMessagesBundle(oldBundle.getLocale());
+ if (newBundle == null) { // we have an old one
+ bundlesToRemove.add(oldBundle);
+ } else {
+ for (IMessage oldMsg : oldBundle.getMessages()) {
+ if (newBundle.getMessage(oldMsg.getKey()) == null) {
+ keysToRemove.add(oldMsg);
+ }
+ }
+ }
+ }
- for (IMessagesBundle bundle : bundlesToRemove) {
- oldBundleGroup.removeMessagesBundle(bundle);
- }
+ for (IMessagesBundle bundle : bundlesToRemove) {
+ oldBundleGroup.removeMessagesBundle(bundle);
+ }
- for (IMessage msg : keysToRemove) {
- IMessagesBundle mb = oldBundleGroup.getMessagesBundle(msg
- .getLocale());
- if (mb != null) {
- mb.removeMessage(msg.getKey());
- }
- }
+ for (IMessage msg : keysToRemove) {
+ IMessagesBundle mb = oldBundleGroup.getMessagesBundle(msg
+ .getLocale());
+ if (mb != null) {
+ mb.removeMessage(msg.getKey());
+ }
+ }
- DirtyHack.setFireEnabled(true);
+ DirtyHack.setFireEnabled(true);
}
@@ -353,14 +353,14 @@
* The resourceBundleId
*/
public void deleteMessagesBundleGroup(String resourceBundleId) {
- // TODO: Try to unify it some time
- if (resourceBundles.containsKey(resourceBundleId)) {
- resourceBundles.remove(resourceBundleId);
- } else {
- logger.log(Level.SEVERE,
- "deleteMessagesBundleGroup with non-existing Id: "
- + resourceBundleId);
- }
+ // TODO: Try to unify it some time
+ if (resourceBundles.containsKey(resourceBundleId)) {
+ resourceBundles.remove(resourceBundleId);
+ } else {
+ logger.log(Level.SEVERE,
+ "deleteMessagesBundleGroup with non-existing Id: "
+ + resourceBundleId);
+ }
}
/**
@@ -370,7 +370,7 @@
* {@link MessagesBundleGroup} with the id resourceBundleId
*/
public boolean containsMessagesBundleGroup(String resourceBundleId) {
- return resourceBundles.containsKey(resourceBundleId);
+ return resourceBundles.containsKey(resourceBundleId);
}
/**
@@ -379,21 +379,21 @@
* @return The corresponding {@link RBManager} to the project
*/
public static RBManager getInstance(IProject project) {
- // set host-project
- if (PDEUtils.isFragment(project)) {
- project = PDEUtils.getFragmentHost(project);
- }
+ // set host-project
+ if (PDEUtils.isFragment(project)) {
+ project = PDEUtils.getFragmentHost(project);
+ }
- INSTANCE = managerMap.get(project);
+ INSTANCE = managerMap.get(project);
- if (INSTANCE == null) {
- INSTANCE = new RBManager();
- INSTANCE.project = project;
- managerMap.put(project, INSTANCE);
- INSTANCE.detectResourceBundles();
- }
+ if (INSTANCE == null) {
+ INSTANCE = new RBManager();
+ INSTANCE.project = project;
+ managerMap.put(project, INSTANCE);
+ INSTANCE.detectResourceBundles();
+ }
- return INSTANCE;
+ return INSTANCE;
}
/**
@@ -403,18 +403,18 @@
* @return The corresponding {@link RBManager} to the project
*/
public static RBManager getInstance(String projectName) {
- for (IProject project : getAllWorkspaceProjects(true)) {
- if (project.getName().equals(projectName)) {
- // check if the projectName is a fragment and return the manager
- // for the host
- if (PDEUtils.isFragment(project)) {
- return getInstance(PDEUtils.getFragmentHost(project));
- } else {
- return getInstance(project);
- }
- }
- }
- return null;
+ for (IProject project : getAllWorkspaceProjects(true)) {
+ if (project.getName().equals(projectName)) {
+ // check if the projectName is a fragment and return the manager
+ // for the host
+ if (PDEUtils.isFragment(project)) {
+ return getInstance(PDEUtils.getFragmentHost(project));
+ } else {
+ return getInstance(project);
+ }
+ }
+ }
+ return null;
}
/**
@@ -425,28 +425,28 @@
* or not.
*/
public static Set<IProject> getAllWorkspaceProjects(boolean ignoreNature) {
- IProject[] projects = ResourcesPlugin.getWorkspace().getRoot()
- .getProjects();
- Set<IProject> projs = new HashSet<IProject>();
+ IProject[] projects = ResourcesPlugin.getWorkspace().getRoot()
+ .getProjects();
+ Set<IProject> projs = new HashSet<IProject>();
- for (IProject p : projects) {
- try {
- if (p.isOpen() && (ignoreNature || p.hasNature(TAPIJI_NATURE))) {
- projs.add(p);
- }
- } catch (CoreException e) {
- logger.log(Level.SEVERE,
- "getAllWorkspaceProjects(...): hasNature failed!", e);
- }
- }
- return projs;
+ for (IProject p : projects) {
+ try {
+ if (p.isOpen() && (ignoreNature || p.hasNature(TAPIJI_NATURE))) {
+ projs.add(p);
+ }
+ } catch (CoreException e) {
+ logger.log(Level.SEVERE,
+ "getAllWorkspaceProjects(...): hasNature failed!", e);
+ }
+ }
+ return projs;
}
/**
* @return All supported projects, those who have the correct nature.
*/
public static Set<IProject> getAllSupportedProjects() {
- return getAllWorkspaceProjects(false);
+ return getAllWorkspaceProjects(false);
}
/**
@@ -454,7 +454,7 @@
* {@link IMessagesEditorListener} to add
*/
public void addMessagesEditorListener(IMessagesEditorListener listener) {
- this.editorListeners.add(listener);
+ this.editorListeners.add(listener);
}
/**
@@ -462,7 +462,7 @@
* {@link IMessagesEditorListener} to remove
*/
public void removeMessagesEditorListener(IMessagesEditorListener listener) {
- this.editorListeners.remove(listener);
+ this.editorListeners.remove(listener);
}
/**
@@ -470,7 +470,7 @@
* {@link IResourceDeltaListener} to add
*/
public void addResourceDeltaListener(IResourceDeltaListener listener) {
- this.resourceListeners.add(listener);
+ this.resourceListeners.add(listener);
}
/**
@@ -478,57 +478,57 @@
* {@link IResourceDeltaListener} to remove
*/
public void removeResourceDeltaListener(IResourceDeltaListener listener) {
- this.resourceListeners.remove(listener);
+ this.resourceListeners.remove(listener);
}
/**
* Fire: MessagesEditor has been saved
*/
public void fireEditorSaved() {
- for (IMessagesEditorListener listener : this.editorListeners) {
- listener.onSave();
- }
- logger.log(Level.INFO, "fireEditorSaved");
+ for (IMessagesEditorListener listener : this.editorListeners) {
+ listener.onSave();
+ }
+ logger.log(Level.INFO, "fireEditorSaved");
}
/**
* Fire: MessagesEditor has been modified
*/
public void fireEditorChanged() {
- for (IMessagesEditorListener listener : this.editorListeners) {
- listener.onModify();
- }
- logger.log(Level.INFO, "fireEditorChanged");
+ for (IMessagesEditorListener listener : this.editorListeners) {
+ listener.onModify();
+ }
+ logger.log(Level.INFO, "fireEditorChanged");
}
/**
* Fire: {@link IMessagesBundle} has been edited
*/
public void fireResourceChanged(IMessagesBundle bundle) {
- for (IMessagesEditorListener listener : this.editorListeners) {
- listener.onResourceChanged(bundle);
- logger.log(Level.INFO, "fireResourceChanged"
- + bundle.getResource().getResourceLocationLabel());
- }
+ for (IMessagesEditorListener listener : this.editorListeners) {
+ listener.onResourceChanged(bundle);
+ logger.log(Level.INFO, "fireResourceChanged"
+ + bundle.getResource().getResourceLocationLabel());
+ }
}
/**
* Detects all resource bundles, which we want to work with.
*/
protected void detectResourceBundles() {
- try {
- project.accept(new ResourceBundleDetectionVisitor(this));
+ try {
+ project.accept(new ResourceBundleDetectionVisitor(this));
- IProject[] fragments = PDEUtils.lookupFragment(project);
- if (fragments != null) {
- for (IProject p : fragments) {
- p.accept(new ResourceBundleDetectionVisitor(this));
- }
+ IProject[] fragments = PDEUtils.lookupFragment(project);
+ if (fragments != null) {
+ for (IProject p : fragments) {
+ p.accept(new ResourceBundleDetectionVisitor(this));
+ }
- }
- } catch (CoreException e) {
- logger.log(Level.SEVERE, "detectResourceBundles: accept failed!", e);
- }
+ }
+ } catch (CoreException e) {
+ logger.log(Level.SEVERE, "detectResourceBundles: accept failed!", e);
+ }
}
// passive loading -> see detectResourceBundles
@@ -536,26 +536,26 @@
* Invoked by {@link #detectResourceBundles()}.
*/
public void addBundleResource(IResource resource) {
- // create it with MessagesBundleFactory or read from resource!
- // we can optimize that, now we create a bundle group for each bundle
- // we should create a bundle group only once!
+ // create it with MessagesBundleFactory or read from resource!
+ // we can optimize that, now we create a bundle group for each bundle
+ // we should create a bundle group only once!
- String resourceBundleId = NameUtils.getResourceBundleId(resource);
- if (!resourceBundles.containsKey(resourceBundleId)) {
- // if we do not have this condition, then you will be doomed with
- // resource out of syncs, because here we instantiate
- // PropertiesFileResources, which have an evil setText-Method
- MessagesBundleGroupFactory.createBundleGroup(resource);
+ String resourceBundleId = NameUtils.getResourceBundleId(resource);
+ if (!resourceBundles.containsKey(resourceBundleId)) {
+ // if we do not have this condition, then you will be doomed with
+ // resource out of syncs, because here we instantiate
+ // PropertiesFileResources, which have an evil setText-Method
+ MessagesBundleGroupFactory.createBundleGroup(resource);
- logger.log(Level.INFO, "addBundleResource (passive loading): "
- + resource.getName());
- }
+ logger.log(Level.INFO, "addBundleResource (passive loading): "
+ + resource.getName());
+ }
}
public void writeToFile(IMessagesBundleGroup bundleGroup) {
- for (IMessagesBundle bundle : bundleGroup.getMessagesBundles()) {
- FileUtils.writeToFile(bundle);
- fireResourceChanged(bundle);
- }
+ for (IMessagesBundle bundle : bundleGroup.getMessagesBundles()) {
+ FileUtils.writeToFile(bundle);
+ fireResourceChanged(bundle);
+ }
}
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java
index 125c34a..b64e684 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java
@@ -27,134 +27,134 @@
import org.eclipse.core.runtime.CoreException;
public class ResourceBundleDetectionVisitor implements IResourceVisitor,
- IResourceDeltaVisitor {
+ IResourceDeltaVisitor {
private RBManager manager = null;
public ResourceBundleDetectionVisitor(RBManager manager) {
- this.manager = manager;
+ this.manager = manager;
}
public boolean visit(IResource resource) throws CoreException {
- try {
- if (isResourceBundleFile(resource)) {
- manager.addBundleResource(resource);
- return false;
- } else
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
+ try {
+ if (isResourceBundleFile(resource)) {
+ manager.addBundleResource(resource);
+ return false;
+ } else
+ return true;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return false;
+ }
}
public boolean visit(IResourceDelta delta) throws CoreException {
- IResource resource = delta.getResource();
+ IResource resource = delta.getResource();
- if (isResourceBundleFile(resource)) {
- // ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
- return false;
- }
+ if (isResourceBundleFile(resource)) {
+ // ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
+ return false;
+ }
- return true;
+ return true;
}
private final String RB_MARKER_ID = "org.eclipse.babel.tapiji.tools.core.ResourceBundleAuditMarker";
private boolean isResourceBundleFile(IResource file) {
- boolean isValied = false;
+ boolean isValied = false;
- if (file != null && file instanceof IFile && !file.isDerived()
- && file.getFileExtension() != null
- && file.getFileExtension().equalsIgnoreCase("properties")) {
- isValied = true;
+ if (file != null && file instanceof IFile && !file.isDerived()
+ && file.getFileExtension() != null
+ && file.getFileExtension().equalsIgnoreCase("properties")) {
+ isValied = true;
- List<CheckItem> list = getBlacklistItems();
- for (CheckItem item : list) {
- if (item.getChecked()
- && file.getFullPath().toString()
- .matches(item.getName())) {
- isValied = false;
+ List<CheckItem> list = getBlacklistItems();
+ for (CheckItem item : list) {
+ if (item.getChecked()
+ && file.getFullPath().toString()
+ .matches(item.getName())) {
+ isValied = false;
- // if properties-file is not RB-file and has
- // ResouceBundleMarker, deletes all ResouceBundleMarker of
- // the file
- if (hasResourceBundleMarker(file))
- try {
- file.deleteMarkers(RB_MARKER_ID, true,
- IResource.DEPTH_INFINITE);
- } catch (CoreException e) {
- }
- }
- }
- }
+ // if properties-file is not RB-file and has
+ // ResouceBundleMarker, deletes all ResouceBundleMarker of
+ // the file
+ if (hasResourceBundleMarker(file))
+ try {
+ file.deleteMarkers(RB_MARKER_ID, true,
+ IResource.DEPTH_INFINITE);
+ } catch (CoreException e) {
+ }
+ }
+ }
+ }
- return isValied;
+ return isValied;
}
private List<CheckItem> getBlacklistItems() {
- IConfiguration configuration = ConfigurationManager.getInstance()
- .getConfiguration();
- if (configuration != null) {
- return convertStringToList(configuration.getNonRbPattern());
- } else {
- return new ArrayList<CheckItem>();
- }
+ IConfiguration configuration = ConfigurationManager.getInstance()
+ .getConfiguration();
+ if (configuration != null) {
+ return convertStringToList(configuration.getNonRbPattern());
+ } else {
+ return new ArrayList<CheckItem>();
+ }
}
private static final String DELIMITER = ";";
private static final String ATTRIBUTE_DELIMITER = ":";
private List<CheckItem> convertStringToList(String string) {
- StringTokenizer tokenizer = new StringTokenizer(string, DELIMITER);
- int tokenCount = tokenizer.countTokens();
- List<CheckItem> elements = new LinkedList<CheckItem>();
+ StringTokenizer tokenizer = new StringTokenizer(string, DELIMITER);
+ int tokenCount = tokenizer.countTokens();
+ List<CheckItem> elements = new LinkedList<CheckItem>();
- for (int i = 0; i < tokenCount; i++) {
- StringTokenizer attribute = new StringTokenizer(
- tokenizer.nextToken(), ATTRIBUTE_DELIMITER);
- String name = attribute.nextToken();
- boolean checked;
- if (attribute.nextToken().equals("true"))
- checked = true;
- else
- checked = false;
+ for (int i = 0; i < tokenCount; i++) {
+ StringTokenizer attribute = new StringTokenizer(
+ tokenizer.nextToken(), ATTRIBUTE_DELIMITER);
+ String name = attribute.nextToken();
+ boolean checked;
+ if (attribute.nextToken().equals("true"))
+ checked = true;
+ else
+ checked = false;
- elements.add(new CheckItem(name, checked));
- }
- return elements;
+ elements.add(new CheckItem(name, checked));
+ }
+ return elements;
}
/**
* Checks whether a RB-file has a problem-marker
*/
public boolean hasResourceBundleMarker(IResource r) {
- try {
- if (r.findMarkers(RB_MARKER_ID, true, IResource.DEPTH_INFINITE).length > 0)
- return true;
- else
- return false;
- } catch (CoreException e) {
- return false;
- }
+ try {
+ if (r.findMarkers(RB_MARKER_ID, true, IResource.DEPTH_INFINITE).length > 0)
+ return true;
+ else
+ return false;
+ } catch (CoreException e) {
+ return false;
+ }
}
private class CheckItem {
- boolean checked;
- String name;
+ boolean checked;
+ String name;
- public CheckItem(String item, boolean checked) {
- this.name = item;
- this.checked = checked;
- }
+ public CheckItem(String item, boolean checked) {
+ this.name = item;
+ this.checked = checked;
+ }
- public String getName() {
- return name;
- }
+ public String getName() {
+ return name;
+ }
- public boolean getChecked() {
- return checked;
- }
+ public boolean getChecked() {
+ return checked;
+ }
}
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/IMessagesResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/IMessagesResource.java
index ca16df4..fb839c4 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/IMessagesResource.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/IMessagesResource.java
@@ -24,63 +24,63 @@
*/
public interface IMessagesResource {
- /**
- * Gets the resource locale.
- *
- * @return locale
- */
- Locale getLocale();
+ /**
+ * Gets the resource locale.
+ *
+ * @return locale
+ */
+ Locale getLocale();
- /**
- * Gets the underlying object abstracted by this resource (e.g. a File).
- *
- * @return source object
- */
- Object getSource();
+ /**
+ * Gets the underlying object abstracted by this resource (e.g. a File).
+ *
+ * @return source object
+ */
+ Object getSource();
- /**
- * Serializes a {@link MessagesBundle} instance to its native format.
- *
- * @param messagesBundle
- * the MessagesBundle to serialize
- */
- void serialize(IMessagesBundle messagesBundle);
+ /**
+ * Serializes a {@link MessagesBundle} instance to its native format.
+ *
+ * @param messagesBundle
+ * the MessagesBundle to serialize
+ */
+ void serialize(IMessagesBundle messagesBundle);
- /**
- * Deserializes a {@link MessagesBundle} instance from its native format.
- *
- * @param messagesBundle
- * the MessagesBundle to deserialize
- */
- void deserialize(IMessagesBundle messagesBundle);
+ /**
+ * Deserializes a {@link MessagesBundle} instance from its native format.
+ *
+ * @param messagesBundle
+ * the MessagesBundle to deserialize
+ */
+ void deserialize(IMessagesBundle messagesBundle);
- /**
- * Adds a messages resource listener. Implementors are required to notify
- * listeners of changes within the native implementation.
- *
- * @param listener
- * the listener
- */
- void addMessagesResourceChangeListener(
- IMessagesResourceChangeListener listener);
+ /**
+ * Adds a messages resource listener. Implementors are required to notify
+ * listeners of changes within the native implementation.
+ *
+ * @param listener
+ * the listener
+ */
+ void addMessagesResourceChangeListener(
+ IMessagesResourceChangeListener listener);
- /**
- * Removes a messages resource listener.
- *
- * @param listener
- * the listener
- */
- void removeMessagesResourceChangeListener(
- IMessagesResourceChangeListener listener);
+ /**
+ * Removes a messages resource listener.
+ *
+ * @param listener
+ * the listener
+ */
+ void removeMessagesResourceChangeListener(
+ IMessagesResourceChangeListener listener);
- /**
- * @return The resource location label. or null if unknown.
- */
- String getResourceLocationLabel();
+ /**
+ * @return The resource location label. or null if unknown.
+ */
+ String getResourceLocationLabel();
- /**
- * Called when the group it belongs to is disposed.
- */
- void dispose();
+ /**
+ * Called when the group it belongs to is disposed.
+ */
+ void dispose();
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractMessagesResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractMessagesResource.java
index 3f18992..91225e4 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractMessagesResource.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractMessagesResource.java
@@ -18,19 +18,22 @@
import org.eclipse.babel.core.message.resource.IMessagesResource;
/**
- * Base implementation of a {@link IMessagesResource} bound to a locale
- * and providing ways to add and remove {@link IMessagesResourceChangeListener}
+ * Base implementation of a {@link IMessagesResource} bound to a locale and
+ * providing ways to add and remove {@link IMessagesResourceChangeListener}
* instances.
+ *
* @author Pascal Essiembre
*/
public abstract class AbstractMessagesResource implements IMessagesResource {
private Locale locale;
private List<IMessagesResourceChangeListener> listeners = new ArrayList<IMessagesResourceChangeListener>();
-
+
/**
* Constructor.
- * @param locale bound locale
+ *
+ * @param locale
+ * bound locale
*/
public AbstractMessagesResource(Locale locale) {
super();
@@ -46,18 +49,17 @@
/**
* @see org.eclipse.babel.core.message.internal.resource.IMessagesResource#
- * addMessagesResourceChangeListener(
- * org.eclipse.babel.core.message.resource
- * .IMessagesResourceChangeListener)
+ * addMessagesResourceChangeListener(org.eclipse.babel.core.message.resource
+ * .IMessagesResourceChangeListener)
*/
public void addMessagesResourceChangeListener(
IMessagesResourceChangeListener listener) {
listeners.add(0, listener);
}
+
/**
* @see org.eclipse.babel.core.message.internal.resource.IMessagesResource#
- * removeMessagesResourceChangeListener(
- * org.eclipse.babel.core.message.resource.IMessagesResourceChangeListener)
+ * removeMessagesResourceChangeListener(org.eclipse.babel.core.message.resource.IMessagesResourceChangeListener)
*/
public void removeMessagesResourceChangeListener(
IMessagesResourceChangeListener listener) {
@@ -66,9 +68,11 @@
/**
* Fires notification that a {@link IMessagesResource} changed.
- * @param resource {@link IMessagesResource}
+ *
+ * @param resource
+ * {@link IMessagesResource}
*/
- protected void fireResourceChange(IMessagesResource resource) {
+ protected void fireResourceChange(IMessagesResource resource) {
for (IMessagesResourceChangeListener listener : listeners) {
listener.resourceChanged(resource);
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractPropertiesResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractPropertiesResource.java
index ff90add..dddaa46 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractPropertiesResource.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractPropertiesResource.java
@@ -17,38 +17,39 @@
import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
-
/**
- * Based implementation of a text-based messages resource following
- * the conventions defined by the Java {@link Properties} class for
- * serialization and deserialization.
+ * Based implementation of a text-based messages resource following the
+ * conventions defined by the Java {@link Properties} class for serialization
+ * and deserialization.
+ *
* @author Pascal Essiembre
*/
-public abstract class AbstractPropertiesResource
- extends AbstractMessagesResource {
+public abstract class AbstractPropertiesResource extends
+ AbstractMessagesResource {
private PropertiesDeserializer deserializer;
private PropertiesSerializer serializer;
-
+
/**
* Constructor.
- * @param locale properties locale
- * @param serializer properties serializer
- * @param deserializer properties deserializer
+ *
+ * @param locale
+ * properties locale
+ * @param serializer
+ * properties serializer
+ * @param deserializer
+ * properties deserializer
*/
- public AbstractPropertiesResource(
- Locale locale,
- PropertiesSerializer serializer,
- PropertiesDeserializer deserializer) {
+ public AbstractPropertiesResource(Locale locale,
+ PropertiesSerializer serializer, PropertiesDeserializer deserializer) {
super(locale);
this.deserializer = deserializer;
this.serializer = serializer;
- //TODO initialises with configurations only...
+ // TODO initialises with configurations only...
}
/**
- * @see org.eclipse.babel.core.message.internal.resource.IMessagesResource#serialize(
- * org.eclipse.babel.core.message.internal.MessagesBundle)
+ * @see org.eclipse.babel.core.message.internal.resource.IMessagesResource#serialize(org.eclipse.babel.core.message.internal.MessagesBundle)
*/
public void serialize(IMessagesBundle messagesBundle) {
setText(serializer.serialize(messagesBundle));
@@ -56,7 +57,7 @@
/**
* @see org.eclipse.babel.core.message.internal.resource.IMessagesResource
- * #deserialize(org.eclipse.babel.core.message.internal.MessagesBundle)
+ * #deserialize(org.eclipse.babel.core.message.internal.MessagesBundle)
*/
public void deserialize(IMessagesBundle messagesBundle) {
deserializer.deserialize(messagesBundle, getText());
@@ -64,13 +65,17 @@
/**
* Gets the {@link Properties}-like formated text.
+ *
* @return formated text
*/
protected abstract String getText();
+
/**
* Sets the {@link Properties}-like formated text.
- * @param text formated text
+ *
+ * @param text
+ * formated text
*/
protected abstract void setText(String text);
-
+
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesFileResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesFileResource.java
index 6c3dd58..7b7d694 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesFileResource.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesFileResource.java
@@ -54,16 +54,16 @@
* @throws FileNotFoundException
*/
public PropertiesFileResource(Locale locale,
- PropertiesSerializer serializer,
- PropertiesDeserializer deserializer, File file)
- throws FileNotFoundException {
- super(locale, serializer, deserializer);
- this.file = file;
- this.fileChangeListener = new FileChangeListenerImpl();
+ PropertiesSerializer serializer,
+ PropertiesDeserializer deserializer, File file)
+ throws FileNotFoundException {
+ super(locale, serializer, deserializer);
+ this.file = file;
+ this.fileChangeListener = new FileChangeListenerImpl();
- FileMonitor.getInstance().addFileChangeListener(
- this.fileChangeListener, file, 2000); // TODO make file scan
- // delay configurable
+ FileMonitor.getInstance().addFileChangeListener(
+ this.fileChangeListener, file, 2000); // TODO make file scan
+ // delay configurable
}
/**
@@ -72,27 +72,27 @@
*/
@Override
public String getText() {
- FileReader inputStream = null;
- StringWriter outputStream = null;
- try {
- if (!file.exists()) {
- return "";
- }
- inputStream = new FileReader(file);
- outputStream = new StringWriter();
- int c;
- while ((c = inputStream.read()) != -1) {
- outputStream.write(c);
- }
- } catch (IOException e) {
- // TODO handle better.
- throw new RuntimeException(
- "Cannot get properties file text. Handle better.", e);
- } finally {
- closeReader(inputStream);
- closeWriter(outputStream);
- }
- return outputStream.toString();
+ FileReader inputStream = null;
+ StringWriter outputStream = null;
+ try {
+ if (!file.exists()) {
+ return "";
+ }
+ inputStream = new FileReader(file);
+ outputStream = new StringWriter();
+ int c;
+ while ((c = inputStream.read()) != -1) {
+ outputStream.write(c);
+ }
+ } catch (IOException e) {
+ // TODO handle better.
+ throw new RuntimeException(
+ "Cannot get properties file text. Handle better.", e);
+ } finally {
+ closeReader(inputStream);
+ closeWriter(outputStream);
+ }
+ return outputStream.toString();
}
/**
@@ -101,33 +101,33 @@
*/
@Override
public void setText(String content) {
- StringReader inputStream = null;
- FileWriter outputStream = null;
- try {
- inputStream = new StringReader(content);
- outputStream = new FileWriter(file);
- int c;
- while ((c = inputStream.read()) != -1) {
- outputStream.write(c);
- }
- } catch (IOException e) {
- // TODO handle better.
- throw new RuntimeException(
- "Cannot get properties file text. Handle better.", e);
- } finally {
- closeReader(inputStream);
- closeWriter(outputStream);
+ StringReader inputStream = null;
+ FileWriter outputStream = null;
+ try {
+ inputStream = new StringReader(content);
+ outputStream = new FileWriter(file);
+ int c;
+ while ((c = inputStream.read()) != -1) {
+ outputStream.write(c);
+ }
+ } catch (IOException e) {
+ // TODO handle better.
+ throw new RuntimeException(
+ "Cannot get properties file text. Handle better.", e);
+ } finally {
+ closeReader(inputStream);
+ closeWriter(outputStream);
- // IFile file =
- // ResourcesPlugin.getWorkspace().getRoot().getFileForLocation( new
- // Path(getResourceLocationLabel()));
- // try {
- // file.refreshLocal(IResource.DEPTH_ZERO, null);
- // } catch (CoreException e) {
- // // TODO Auto-generated catch block
- // e.printStackTrace();
- // }
- }
+ // IFile file =
+ // ResourcesPlugin.getWorkspace().getRoot().getFileForLocation( new
+ // Path(getResourceLocationLabel()));
+ // try {
+ // file.refreshLocal(IResource.DEPTH_ZERO, null);
+ // } catch (CoreException e) {
+ // // TODO Auto-generated catch block
+ // e.printStackTrace();
+ // }
+ }
}
/**
@@ -136,7 +136,7 @@
*/
@Override
public Object getSource() {
- return file;
+ return file;
}
/**
@@ -144,31 +144,31 @@
*/
@Override
public String getResourceLocationLabel() {
- return file.getAbsolutePath();
+ return file.getAbsolutePath();
}
// TODO move to util class for convinience???
private void closeWriter(Writer writer) {
- if (writer != null) {
- try {
- writer.close();
- } catch (IOException e) {
- // TODO handle better.
- throw new RuntimeException("Cannot close writer stream.", e);
- }
- }
+ if (writer != null) {
+ try {
+ writer.close();
+ } catch (IOException e) {
+ // TODO handle better.
+ throw new RuntimeException("Cannot close writer stream.", e);
+ }
+ }
}
// TODO move to util class for convinience???
public void closeReader(Reader reader) {
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException e) {
- // TODO handle better.
- throw new RuntimeException("Cannot close reader.", e);
- }
- }
+ if (reader != null) {
+ try {
+ reader.close();
+ } catch (IOException e) {
+ // TODO handle better.
+ throw new RuntimeException("Cannot close reader.", e);
+ }
+ }
}
/**
@@ -177,16 +177,16 @@
*/
@Override
public void dispose() {
- FileMonitor.getInstance().removeFileChangeListener(
- this.fileChangeListener, file);
+ FileMonitor.getInstance().removeFileChangeListener(
+ this.fileChangeListener, file);
}
private class FileChangeListenerImpl implements FileChangeListener {
- @Override
- public void fileChanged(final File changedFile) {
- fireResourceChange(PropertiesFileResource.this);
- }
+ @Override
+ public void fileChanged(final File changedFile) {
+ fireResourceChange(PropertiesFileResource.this);
+ }
}
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesIFileResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesIFileResource.java
index aec85ff..e8cf314 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesIFileResource.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesIFileResource.java
@@ -26,11 +26,10 @@
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.runtime.CoreException;
-
/**
- * Properties file, where the underlying storage is a {@link IFile}.
- * When dealing with {@link File} as opposed to {@link IFile},
- * implementors should use {@link PropertiesFileResource}.
+ * Properties file, where the underlying storage is a {@link IFile}. When
+ * dealing with {@link File} as opposed to {@link IFile}, implementors should
+ * use {@link PropertiesFileResource}.
*
* @author Pascal Essiembre
* @see PropertiesFileResource
@@ -38,57 +37,63 @@
public class PropertiesIFileResource extends AbstractPropertiesResource {
private final IFile file;
-
+
private final AbstractIFileChangeListener fileListener;
private final IFileChangeListenerRegistry listenerRegistry;
-
+
/**
* Constructor.
- * @param locale the resource locale
- * @param serializer resource serializer
- * @param deserializer resource deserializer
- * @param file the underlying {@link IFile}
- * @param listenerRegistry It is the MessageEditorPlugin.
- * Or null if we don't care for file changes.
- * We could replace it by an activator in this plugin.
+ *
+ * @param locale
+ * the resource locale
+ * @param serializer
+ * resource serializer
+ * @param deserializer
+ * resource deserializer
+ * @param file
+ * the underlying {@link IFile}
+ * @param listenerRegistry
+ * It is the MessageEditorPlugin. Or null if we don't care for
+ * file changes. We could replace it by an activator in this
+ * plugin.
*/
- public PropertiesIFileResource(
- Locale locale,
+ public PropertiesIFileResource(Locale locale,
PropertiesSerializer serializer,
- PropertiesDeserializer deserializer,
- IFile file, IFileChangeListenerRegistry listenerRegistry) {
+ PropertiesDeserializer deserializer, IFile file,
+ IFileChangeListenerRegistry listenerRegistry) {
super(locale, serializer, deserializer);
this.file = file;
this.listenerRegistry = listenerRegistry;
-
- //[hugues] FIXME: this object is built at the beginning
- //of a build (no message editor)
- //it is disposed of at the end of the build.
- //during a build files are not changed.
- //so it is I believe never called.
+
+ // [hugues] FIXME: this object is built at the beginning
+ // of a build (no message editor)
+ // it is disposed of at the end of the build.
+ // during a build files are not changed.
+ // so it is I believe never called.
if (this.listenerRegistry != null) {
- IResourceChangeListener rcl =
- new IResourceChangeListener() {
- public void resourceChanged(IResourceChangeEvent event) {
- //no need to check: it is always the case as this
- //is subscribed for a particular file.
-// if (event.getResource() != null
-// && PropertiesIFileResource.this.file.equals(event.getResource())) {
- fireResourceChange(PropertiesIFileResource.this);
-// }
- }
- };
- fileListener = AbstractIFileChangeListener
- .wrapResourceChangeListener(rcl, file);
- this.listenerRegistry.subscribe(fileListener);
+ IResourceChangeListener rcl = new IResourceChangeListener() {
+ public void resourceChanged(IResourceChangeEvent event) {
+ // no need to check: it is always the case as this
+ // is subscribed for a particular file.
+ // if (event.getResource() != null
+ // &&
+ // PropertiesIFileResource.this.file.equals(event.getResource()))
+ // {
+ fireResourceChange(PropertiesIFileResource.this);
+ // }
+ }
+ };
+ fileListener = AbstractIFileChangeListener
+ .wrapResourceChangeListener(rcl, file);
+ this.listenerRegistry.subscribe(fileListener);
} else {
- fileListener = null;
+ fileListener = null;
}
}
/**
* @see org.eclipse.babel.core.message.internal.resource.AbstractPropertiesResource
- * #getText()
+ * #getText()
*/
public String getText() {
try {
@@ -100,54 +105,52 @@
String content = new String(b, file.getCharset());
return content;
} catch (IOException e) {
- throw new RuntimeException(e); //TODO handle better
+ throw new RuntimeException(e); // TODO handle better
} catch (CoreException e) {
- throw new RuntimeException(e); //TODO handle better
+ throw new RuntimeException(e); // TODO handle better
}
}
/**
- * @see org.eclipse.babel.core.message.internal.resource.TextResource#setText(
- * java.lang.String)
+ * @see org.eclipse.babel.core.message.internal.resource.TextResource#setText(java.lang.String)
*/
public void setText(String text) {
try {
- String charset = file.getCharset();
- ByteArrayInputStream is = new ByteArrayInputStream(
- text.getBytes(charset));
+ String charset = file.getCharset();
+ ByteArrayInputStream is = new ByteArrayInputStream(
+ text.getBytes(charset));
file.setContents(is, IFile.KEEP_HISTORY, null);
file.refreshLocal(IResource.DEPTH_ZERO, null);
} catch (Exception e) {
- //TODO handle better
+ // TODO handle better
throw new RuntimeException(
"Cannot set content on properties file.", e); //$NON-NLS-1$
}
}
-
+
/**
* @see org.eclipse.babel.core.message.internal.resource.IMessagesResource
- * #getSource()
+ * #getSource()
*/
public Object getSource() {
return file;
- }
-
+ }
+
/**
* @return The resource location label. or null if unknown.
*/
public String getResourceLocationLabel() {
- return file.getFullPath().toString();
- }
-
- /**
- * Called before this object will be discarded.
- * If this object was listening to file changes: then unsubscribe it.
- */
- public void dispose() {
- if (this.listenerRegistry != null) {
- this.listenerRegistry.unsubscribe(this.fileListener);
- }
+ return file.getFullPath().toString();
}
-
+ /**
+ * Called before this object will be discarded. If this object was listening
+ * to file changes: then unsubscribe it.
+ */
+ public void dispose() {
+ if (this.listenerRegistry != null) {
+ this.listenerRegistry.unsubscribe(this.fileListener);
+ }
+ }
+
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesReadOnlyResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesReadOnlyResource.java
index beabf0e..da80116 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesReadOnlyResource.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesReadOnlyResource.java
@@ -15,36 +15,39 @@
import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
-
/**
- * Properties file, where the underlying storage is unknown and read-only.
- * This is the case when properties are located inside a jar or the target platform.
- * This resource is not suitable to build the editor itself.
- * It is used during the build only.
+ * Properties file, where the underlying storage is unknown and read-only. This
+ * is the case when properties are located inside a jar or the target platform.
+ * This resource is not suitable to build the editor itself. It is used during
+ * the build only.
*
* @author Pascal Essiembre
* @author Hugues Malphettes
* @see PropertiesFileResource
*/
-public class PropertiesReadOnlyResource extends AbstractPropertiesResource{
+public class PropertiesReadOnlyResource extends AbstractPropertiesResource {
private final String contents;
private final String resourceLocationLabel;
-
+
/**
* Constructor.
- * @param locale the resource locale
- * @param serializer resource serializer
- * @param deserializer resource deserializer
- * @param content The contents of the properties
- * @param resourceLocationLabel The label that explains to the user where
- * those properties are defined.
+ *
+ * @param locale
+ * the resource locale
+ * @param serializer
+ * resource serializer
+ * @param deserializer
+ * resource deserializer
+ * @param content
+ * The contents of the properties
+ * @param resourceLocationLabel
+ * The label that explains to the user where those properties are
+ * defined.
*/
- public PropertiesReadOnlyResource(
- Locale locale,
+ public PropertiesReadOnlyResource(Locale locale,
PropertiesSerializer serializer,
- PropertiesDeserializer deserializer,
- String contents,
+ PropertiesDeserializer deserializer, String contents,
String resourceLocationLabel) {
super(locale, serializer, deserializer);
this.contents = contents;
@@ -53,7 +56,7 @@
/**
* @see org.eclipse.babel.core.message.internal.resource.AbstractPropertiesResource
- * #getText()
+ * #getText()
*/
public String getText() {
return contents;
@@ -61,34 +64,34 @@
/**
* Unsupported here. This is read-only.
- * @see org.eclipse.babel.core.message.internal.resource.TextResource#setText(
- * java.lang.String)
+ *
+ * @see org.eclipse.babel.core.message.internal.resource.TextResource#setText(java.lang.String)
*/
public void setText(String text) {
throw new UnsupportedOperationException(getResourceLocationLabel()
- + " resource is read-only"); //$NON-NLS-1$ (just an error message)
+ + " resource is read-only"); //$NON-NLS-1$ (just an error message)
}
-
+
/**
* @see org.eclipse.babel.core.message.internal.resource.IMessagesResource
- * #getSource()
+ * #getSource()
*/
public Object getSource() {
return this;
- }
-
+ }
+
/**
* @return The resource location label. or null if unknown.
*/
public String getResourceLocationLabel() {
- return resourceLocationLabel;
+ return resourceLocationLabel;
}
-
+
/**
- * Called before this object will be discarded.
- * Nothing to do: we were not listening to changes to this object.
+ * Called before this object will be discarded. Nothing to do: we were not
+ * listening to changes to this object.
*/
public void dispose() {
- //nothing to do.
+ // nothing to do.
}
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesDeserializerConfig.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesDeserializerConfig.java
index f231509..7fed265 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesDeserializerConfig.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesDeserializerConfig.java
@@ -19,6 +19,7 @@
/**
* Defaults true.
+ *
* @return Returns the unicodeUnescapeEnabled.
*/
boolean isUnicodeUnescapeEnabled();
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesSerializerConfig.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesSerializerConfig.java
index 469e6ce..9811bba 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesSerializerConfig.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesSerializerConfig.java
@@ -28,42 +28,49 @@
/**
* Default true.
+ *
* @return Returns the unicodeEscapeEnabled.
*/
boolean isUnicodeEscapeEnabled();
/**
* Default to "NEW_LINE_DEFAULT".
+ *
* @return Returns the newLineStyle.
*/
int getNewLineStyle();
/**
* Default is 1.
+ *
* @return Returns the groupSepBlankLineCount.
*/
int getGroupSepBlankLineCount();
/**
* Defaults to true.
+ *
* @return Returns the showSupportEnabled.
*/
boolean isShowSupportEnabled();
/**
* Defaults to true.
+ *
* @return Returns the groupKeysEnabled.
*/
boolean isGroupKeysEnabled();
/**
* Defaults to true.
+ *
* @return Returns the unicodeEscapeUppercase.
*/
boolean isUnicodeEscapeUppercase();
/**
* Defaults to 80.
+ *
* @return Returns the wrapLineLength.
*/
int getWrapLineLength();
@@ -80,12 +87,14 @@
/**
* Defaults to 8.
+ *
* @return Returns the wrapIndentLength.
*/
int getWrapIndentLength();
/**
* Defaults to true.
+ *
* @return Returns the spacesAroundEqualsEnabled.
*/
boolean isSpacesAroundEqualsEnabled();
@@ -112,12 +121,14 @@
/**
* Defaults to true.
+ *
* @return Returns the groupAlignEqualsEnabled.
*/
boolean isGroupAlignEqualsEnabled();
-
+
/**
* Defaults to true.
+ *
* @return <code>true</code> if keys are to be sorted
*/
boolean isKeySortingEnabled();
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesDeserializer.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesDeserializer.java
index 2fe4273..6613a76 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesDeserializer.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesDeserializer.java
@@ -23,22 +23,23 @@
import org.eclipse.babel.core.util.BabelUtils;
/**
- * Class responsible for deserializing {@link Properties}-like text into
- * a {@link MessagesBundle}.
+ * Class responsible for deserializing {@link Properties}-like text into a
+ * {@link MessagesBundle}.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public class PropertiesDeserializer {
/** System line separator. */
- private static final String SYSTEM_LINE_SEPARATOR =
- System.getProperty("line.separator"); //$NON-NLS-1$
-
+ private static final String SYSTEM_LINE_SEPARATOR = System
+ .getProperty("line.separator"); //$NON-NLS-1$
+
/** Characters accepted as key value separators. */
private static final String KEY_VALUE_SEPARATORS = "=:"; //$NON-NLS-1$
/** MessagesBundle deserializer configuration. */
private IPropertiesDeserializerConfig config;
-
+
/**
* Constructor.
*/
@@ -48,21 +49,23 @@
}
/**
- * Parses a string and populates a <code>MessagesBundle</code>.
- * The string is expected to match the documented structure of a properties
- * file.
- * @param messagesBundle the target {@link MessagesBundle}
- * @param properties the string containing the properties to parse
+ * Parses a string and populates a <code>MessagesBundle</code>. The string
+ * is expected to match the documented structure of a properties file.
+ *
+ * @param messagesBundle
+ * the target {@link MessagesBundle}
+ * @param properties
+ * the string containing the properties to parse
*/
public void deserialize(IMessagesBundle messagesBundle, String properties) {
Locale locale = messagesBundle.getLocale();
-
- Collection<String> oldKeys =
- new ArrayList<String>(Arrays.asList(messagesBundle.getKeys()));
+
+ Collection<String> oldKeys = new ArrayList<String>(
+ Arrays.asList(messagesBundle.getKeys()));
Collection<String> newKeys = new ArrayList<String>();
-
+
String[] lines = properties.split("\r\n|\r|\n"); //$NON-NLS-1$
-
+
boolean doneWithFileComment = false;
StringBuffer fileComment = new StringBuffer();
StringBuffer lineComment = new StringBuffer();
@@ -71,12 +74,12 @@
String line = lines[i];
lineBuf.setLength(0);
lineBuf.append(line);
-
+
int equalPosition = findKeyValueSeparator(line);
boolean isRegularLine = line.matches("^[^#].*"); //$NON-NLS-1$
- boolean isCommentedLine = doneWithFileComment
+ boolean isCommentedLine = doneWithFileComment
&& line.matches("^##[^#].*"); //$NON-NLS-1$
-
+
// parse regular and commented lines
if (equalPosition >= 1 && (isRegularLine || isCommentedLine)) {
doneWithFileComment = true;
@@ -91,17 +94,14 @@
equalPosition -= 2;
}
String backslash = "\\"; //$NON-NLS-1$
- while (lineBuf.lastIndexOf(backslash) == lineBuf.length() -1) {
+ while (lineBuf.lastIndexOf(backslash) == lineBuf.length() - 1) {
int lineBreakPosition = lineBuf.lastIndexOf(backslash);
- lineBuf.replace(
- lineBreakPosition,
- lineBreakPosition + 1, ""); //$NON-NLS-1$
+ lineBuf.replace(lineBreakPosition, lineBreakPosition + 1,
+ ""); //$NON-NLS-1$
if (++i < lines.length) {
- String wrappedLine = lines[i].replaceFirst(
- "^\\s*", ""); //$NON-NLS-1$ //$NON-NLS-2$
+ String wrappedLine = lines[i].replaceFirst("^\\s*", ""); //$NON-NLS-1$ //$NON-NLS-2$
if (isCommentedLine) {
- lineBuf.append(wrappedLine.replaceFirst(
- "^##", "")); //$NON-NLS-1$ //$NON-NLS-2$
+ lineBuf.append(wrappedLine.replaceFirst("^##", "")); //$NON-NLS-1$ //$NON-NLS-2$
} else {
lineBuf.append(wrappedLine);
}
@@ -109,22 +109,20 @@
}
String key = lineBuf.substring(0, equalPosition).trim();
key = unescapeKey(key);
-
+
String value = lineBuf.substring(equalPosition + 1)
- .replaceFirst("^\\s*", ""); //$NON-NLS-1$//$NON-NLS-2$
+ .replaceFirst("^\\s*", ""); //$NON-NLS-1$//$NON-NLS-2$
// Unescape leading spaces
if (value.startsWith("\\ ")) { //$NON-NLS-1$
value = value.substring(1);
}
-
+
if (this.config != null && config.isUnicodeUnescapeEnabled()) {
key = convertEncodedToUnicode(key);
value = convertEncodedToUnicode(value);
} else {
- value = value.replaceAll(
- "\\\\r", "\r"); //$NON-NLS-1$ //$NON-NLS-2$
- value = value.replaceAll(
- "\\\\n", "\n"); //$NON-NLS-1$//$NON-NLS-2$
+ value = value.replaceAll("\\\\r", "\r"); //$NON-NLS-1$ //$NON-NLS-2$
+ value = value.replaceAll("\\\\n", "\n"); //$NON-NLS-1$//$NON-NLS-2$
}
IMessage entry = messagesBundle.getMessage(key);
if (entry == null) {
@@ -135,7 +133,7 @@
entry.setComment(comment);
entry.setText(value);
newKeys.add(key);
- // parse comment line
+ // parse comment line
} else if (lineBuf.indexOf("#") == 0) { //$NON-NLS-1$
if (!doneWithFileComment) {
fileComment.append(lineBuf);
@@ -144,22 +142,23 @@
lineComment.append(lineBuf);
lineComment.append(SYSTEM_LINE_SEPARATOR);
}
- // handle blank or unsupported line
+ // handle blank or unsupported line
} else {
doneWithFileComment = true;
}
}
oldKeys.removeAll(newKeys);
- messagesBundle.removeMessages(
- oldKeys.toArray(BabelUtils.EMPTY_STRINGS));
+ messagesBundle
+ .removeMessages(oldKeys.toArray(BabelUtils.EMPTY_STRINGS));
messagesBundle.setComment(fileComment.toString());
}
-
-
+
/**
- * Converts encoded \uxxxx to unicode chars
- * and changes special saved chars to their original forms
- * @param str the string to convert
+ * Converts encoded \uxxxx to unicode chars and changes special saved
+ * chars to their original forms
+ *
+ * @param str
+ * the string to convert
* @return converted string
* @see java.util.Properties
*/
@@ -178,25 +177,40 @@
for (int i = 0; i < 4; i++) {
aChar = str.charAt(x++);
switch (aChar) {
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
value = (value << 4) + aChar - '0';
break;
- case 'a': case 'b': case 'c':
- case 'd': case 'e': case 'f':
+ case 'a':
+ case 'b':
+ case 'c':
+ case 'd':
+ case 'e':
+ case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
- case 'A': case 'B': case 'C':
- case 'D': case 'E': case 'F':
+ case 'A':
+ case 'B':
+ case 'C':
+ case 'D':
+ case 'E':
+ case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
value = aChar;
- System.err.println(
- "PropertiesDeserializer: " //$NON-NLS-1$
- + "bad character " //$NON-NLS-1$
- + "encoding for string:" //$NON-NLS-1$
- + str);
+ System.err.println("PropertiesDeserializer: " //$NON-NLS-1$
+ + "bad character " //$NON-NLS-1$
+ + "encoding for string:" //$NON-NLS-1$
+ + str);
}
}
outBuffer.append((char) value);
@@ -220,10 +234,12 @@
}
return outBuffer.toString();
}
-
+
/**
* Finds the separator symbol that separates keys and values.
- * @param str the string on which to find seperator
+ *
+ * @param str
+ * the string on which to find seperator
* @return the separator index or -1 if no separator was found
*/
private int findKeyValueSeparator(String str) {
@@ -240,7 +256,7 @@
}
return index;
}
-
+
private String unescapeKey(String key) {
int length = key.length();
StringBuffer buf = new StringBuffer();
@@ -252,5 +268,5 @@
}
return buf.toString();
}
-
+
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesSerializer.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesSerializer.java
index 420c4ad..8cdddd1 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesSerializer.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesSerializer.java
@@ -20,44 +20,38 @@
/**
* Class responsible for serializing a {@link MessagesBundle} into
* {@link Properties}-like text.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public class PropertiesSerializer {
/** Generator header comment. */
- public static final String GENERATED_BY =
- "#Generated by Eclipse Messages Editor " //$NON-NLS-1$
- + "(Eclipse Babel)"; //$NON-NLS-1$
+ public static final String GENERATED_BY = "#Generated by Eclipse Messages Editor " //$NON-NLS-1$
+ + "(Eclipse Babel)"; //$NON-NLS-1$
/** A table of hex digits */
- private static final char[] HEX_DIGITS = {
- '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
- };
+ private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
+ '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
/** Special resource bundle characters when persisting any text. */
- private static final String SPECIAL_VALUE_SAVE_CHARS =
- "\t\f"; //$NON-NLS-1$
+ private static final String SPECIAL_VALUE_SAVE_CHARS = "\t\f"; //$NON-NLS-1$
/** Special resource bundle characters when persisting keys. */
- private static final String SPECIAL_KEY_SAVE_CHARS =
- "=\t\f#!: "; //$NON-NLS-1$
-
+ private static final String SPECIAL_KEY_SAVE_CHARS = "=\t\f#!: "; //$NON-NLS-1$
+
/** System line separator. */
- private static final String SYSTEM_LINE_SEP =
- System.getProperty("line.separator"); //$NON-NLS-1$
+ private static final String SYSTEM_LINE_SEP = System
+ .getProperty("line.separator"); //$NON-NLS-1$
/** Forced line separators. */
private static final String[] FORCED_LINE_SEP = new String[4];
static {
FORCED_LINE_SEP[IPropertiesSerializerConfig.NEW_LINE_DEFAULT] = null;
- FORCED_LINE_SEP[IPropertiesSerializerConfig.NEW_LINE_UNIX] =
- "\\\\n"; //$NON-NLS-1$
- FORCED_LINE_SEP[IPropertiesSerializerConfig.NEW_LINE_WIN] =
- "\\\\r\\\\n"; //$NON-NLS-1$
- FORCED_LINE_SEP[IPropertiesSerializerConfig.NEW_LINE_MAC] =
- "\\\\r"; //$NON-NLS-1$
+ FORCED_LINE_SEP[IPropertiesSerializerConfig.NEW_LINE_UNIX] = "\\\\n"; //$NON-NLS-1$
+ FORCED_LINE_SEP[IPropertiesSerializerConfig.NEW_LINE_WIN] = "\\\\r\\\\n"; //$NON-NLS-1$
+ FORCED_LINE_SEP[IPropertiesSerializerConfig.NEW_LINE_MAC] = "\\\\r"; //$NON-NLS-1$
}
private IPropertiesSerializerConfig config;
-
+
/**
* Constructor.
*/
@@ -69,7 +63,9 @@
/**
* Serializes a given <code>MessagesBundle</code> into a formatted string.
* The returned string will conform to documented properties file structure.
- * @param messagesBundle the bundle used to generate the string
+ *
+ * @param messagesBundle
+ * the bundle used to generate the string
* @return the generated string
*/
public String serialize(IMessagesBundle messagesBundle) {
@@ -79,7 +75,7 @@
// Header comment
String headComment = messagesBundle.getComment();
- if (config.isShowSupportEnabled()
+ if (config.isShowSupportEnabled()
&& !headComment.startsWith(GENERATED_BY)) {
text.append(GENERATED_BY);
text.append(SYSTEM_LINE_SEP);
@@ -87,7 +83,7 @@
if (headComment != null && headComment.length() > 0) {
text.append(headComment);
}
-
+
// Format
String group = null;
int equalIndex = -1;
@@ -96,36 +92,32 @@
Arrays.sort(keys);
}
for (int i = 0; i < keys.length; i++) {
- String key = keys[i];
+ String key = keys[i];
IMessage message = messagesBundle.getMessage(key);
- String value = message.getValue();
- String comment = message.getComment();
-
- if (value != null){
+ String value = message.getValue();
+ String comment = message.getComment();
+
+ if (value != null) {
// escape backslashes
if (config.isUnicodeEscapeEnabled()) {
- value = value.replaceAll(
- "\\\\", "\\\\\\\\");//$NON-NLS-1$ //$NON-NLS-2$
+ value = value.replaceAll("\\\\", "\\\\\\\\");//$NON-NLS-1$ //$NON-NLS-2$
}
-
+
// handle new lines in value
String lineStyleCh = FORCED_LINE_SEP[config.getNewLineStyle()];
if (lineStyleCh != null) {
- value = value.replaceAll(
- "\r\n|\r|\n", lineStyleCh); //$NON-NLS-1$
+ value = value.replaceAll("\r\n|\r|\n", lineStyleCh); //$NON-NLS-1$
} else {
- value = value.replaceAll(
- "\r", "\\\\r"); //$NON-NLS-1$ //$NON-NLS-2$
- value = value.replaceAll(
- "\n", "\\\\n"); //$NON-NLS-1$ //$NON-NLS-2$
+ value = value.replaceAll("\r", "\\\\r"); //$NON-NLS-1$ //$NON-NLS-2$
+ value = value.replaceAll("\n", "\\\\n"); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
value = ""; //$NON-NLS-1$
}
-
- //TODO Put check here and add to config: keep empty values?
- //default being false
-
+
+ // TODO Put check here and add to config: keep empty values?
+ // default being false
+
// handle group equal align and line break options
if (config.isGroupKeysEnabled()) {
String newGroup = getKeyGroup(key);
@@ -139,7 +131,7 @@
} else {
equalIndex = getEqualIndex(key, null, messagesBundle);
}
-
+
// Build line
if (config.isUnicodeEscapeEnabled()) {
key = convertUnicodeToEncoded(key);
@@ -154,10 +146,12 @@
}
return text.toString();
}
-
+
/**
* Converts unicodes to encoded \uxxxx.
- * @param str string to convert
+ *
+ * @param str
+ * string to convert
* @return converted string
* @see java.util.Properties
*/
@@ -180,10 +174,12 @@
}
return outBuffer.toString();
}
-
+
/**
* Converts a nibble to a hex character
- * @param nibble the nibble to convert.
+ *
+ * @param nibble
+ * the nibble to convert.
* @return a converted character
*/
private char toHex(int nibble) {
@@ -196,14 +192,18 @@
/**
* Appends a value to resource bundle content.
- * @param text the resource bundle content so far
- * @param value the value to add
- * @param equalIndex the equal sign position
- * @param active is the value active or not
+ *
+ * @param text
+ * the resource bundle content so far
+ * @param value
+ * the value to add
+ * @param equalIndex
+ * the equal sign position
+ * @param active
+ * is the value active or not
*/
- private void appendValue(
- StringBuffer text, String value,
- int equalIndex, boolean active) {
+ private void appendValue(StringBuffer text, String value, int equalIndex,
+ boolean active) {
if (value != null) {
// Escape potential leading spaces.
if (value.startsWith(" ")) { //$NON-NLS-1$
@@ -216,11 +216,10 @@
} else {
valueStartPos += 1;
}
-
+
// Break line after escaped new line
if (config.isNewLineNice()) {
- value = value.replaceAll(
- "(\\\\r\\\\n|\\\\r|\\\\n)", //$NON-NLS-1$
+ value = value.replaceAll("(\\\\r\\\\n|\\\\r|\\\\n)", //$NON-NLS-1$
"$1\\\\" + SYSTEM_LINE_SEP); //$NON-NLS-1$
}
// Wrap lines
@@ -228,20 +227,20 @@
StringBuffer valueBuf = new StringBuffer(value);
while (valueBuf.length() + valueStartPos > lineLength
|| valueBuf.indexOf("\n") != -1) { //$NON-NLS-1$
- int endPos = Math.min(
- valueBuf.length(), lineLength - valueStartPos);
+ int endPos = Math.min(valueBuf.length(), lineLength
+ - valueStartPos);
String line = valueBuf.substring(0, endPos);
int breakPos = line.indexOf(SYSTEM_LINE_SEP);
if (breakPos != -1) {
endPos = breakPos + SYSTEM_LINE_SEP.length();
saveValue(text, valueBuf.substring(0, endPos));
- //text.append(valueBuf.substring(0, endPos));
+ // text.append(valueBuf.substring(0, endPos));
} else {
breakPos = line.lastIndexOf(' ');
if (breakPos != -1) {
endPos = breakPos + 1;
saveValue(text, valueBuf.substring(0, endPos));
- //text.append(valueBuf.substring(0, endPos));
+ // text.append(valueBuf.substring(0, endPos));
text.append("\\"); //$NON-NLS-1$
text.append(SYSTEM_LINE_SEP);
}
@@ -263,28 +262,33 @@
text.append(valueBuf);
} else {
saveValue(text, value);
- //text.append(value);
+ // text.append(value);
}
}
}
/**
* Appends a key to resource bundle content.
- * @param text the resource bundle content so far
- * @param key the key to add
- * @param equalIndex the equal sign position
- * @param active is the key active or not
+ *
+ * @param text
+ * the resource bundle content so far
+ * @param key
+ * the key to add
+ * @param equalIndex
+ * the equal sign position
+ * @param active
+ * is the key active or not
*/
- private void appendKey(
- StringBuffer text, String key, int equalIndex, boolean active) {
+ private void appendKey(StringBuffer text, String key, int equalIndex,
+ boolean active) {
if (!active) {
text.append("##"); //$NON-NLS-1$
}
-
+
// Escape and persist the rest
saveKey(text, key);
-// text.append(key);
+ // text.append(key);
for (int i = 0; i < equalIndex - key.length(); i++) {
text.append(' ');
}
@@ -294,25 +298,28 @@
text.append("="); //$NON-NLS-1$
}
}
-
-
+
private void saveKey(StringBuffer buf, String str) {
saveText(buf, str, SPECIAL_KEY_SAVE_CHARS);
}
+
private void saveValue(StringBuffer buf, String str) {
saveText(buf, str, SPECIAL_VALUE_SAVE_CHARS);
}
-
+
/**
* Saves some text in a given buffer after converting special characters.
- * @param buf the buffer to store the text into
- * @param str the value to save
- * @param escapeChars characters to escape
+ *
+ * @param buf
+ * the buffer to store the text into
+ * @param str
+ * the value to save
+ * @param escapeChars
+ * characters to escape
*/
- private void saveText(
- StringBuffer buf, String str, String escapeChars) {
+ private void saveText(StringBuffer buf, String str, String escapeChars) {
int len = str.length();
- for(int x = 0; x < len; x++) {
+ for (int x = 0; x < len; x++) {
char aChar = str.charAt(x);
if (escapeChars.indexOf(aChar) != -1) {
buf.append('\\');
@@ -320,10 +327,12 @@
buf.append(aChar);
}
}
-
+
/**
* Gets the group from a resource bundle key.
- * @param key the key to get a group from
+ *
+ * @param key
+ * the key to get a group from
* @return key group
*/
private String getKeyGroup(String key) {
@@ -331,7 +340,7 @@
int depth = config.getGroupLevelDepth();
int endIndex = 0;
int levelFound = 0;
-
+
for (int i = 0; i < depth; i++) {
int sepIndex = key.indexOf(sep, endIndex);
if (sepIndex != -1) {
@@ -347,39 +356,43 @@
}
return null;
}
-
+
/**
- * Gets the position where the equal sign should be located for
- * the given group.
- * @param key resource bundle key
- * @param group resource bundle key group
- * @param messagesBundle resource bundle
+ * Gets the position where the equal sign should be located for the given
+ * group.
+ *
+ * @param key
+ * resource bundle key
+ * @param group
+ * resource bundle key group
+ * @param messagesBundle
+ * resource bundle
* @return position
*/
- private int getEqualIndex(
- String key, String group, IMessagesBundle messagesBundle) {
+ private int getEqualIndex(String key, String group,
+ IMessagesBundle messagesBundle) {
int equalIndex = -1;
boolean alignEquals = config.isAlignEqualsEnabled();
boolean groupKeys = config.isGroupKeysEnabled();
boolean groupAlignEquals = config.isGroupAlignEqualsEnabled();
// Exit now if we are not aligning equals
- if (!alignEquals || groupKeys && !groupAlignEquals
- || groupKeys && group == null) {
+ if (!alignEquals || groupKeys && !groupAlignEquals || groupKeys
+ && group == null) {
return key.length();
}
-
+
// Get equal index
String[] keys = messagesBundle.getKeys();
for (int i = 0; i < keys.length; i++) {
- String iterKey = keys[i];
+ String iterKey = keys[i];
if (!groupKeys || groupAlignEquals && iterKey.startsWith(group)) {
int index = iterKey.length();
if (index > equalIndex) {
equalIndex = index;
}
}
- }
+ }
return equalIndex;
}
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/IMessagesBundleGroupStrategy.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/IMessagesBundleGroupStrategy.java
index 57de739..5b1ed50 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/IMessagesBundleGroupStrategy.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/IMessagesBundleGroupStrategy.java
@@ -17,49 +17,54 @@
import org.eclipse.babel.core.message.internal.MessagesBundle;
import org.eclipse.babel.core.message.resource.IMessagesResource;
-
-
/**
- * This class holds the algorithms required to abstract the internal nature
- * of a <code>MessagesBundleGroup</code>.
+ * This class holds the algorithms required to abstract the internal nature of a
+ * <code>MessagesBundleGroup</code>.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
* @see IMessagesResource
*/
public interface IMessagesBundleGroupStrategy {
- //TODO think of a better name for this interface?
-
+ // TODO think of a better name for this interface?
+
/**
* Creates a name that attempts to uniquely identifies a messages bundle
- * group. It is not a strict requirement that the name be unique,
- * but doing facilitates users interaction with a message bundle group
- * in a given user-facing implementation.<P>
+ * group. It is not a strict requirement that the name be unique, but doing
+ * facilitates users interaction with a message bundle group in a given
+ * user-facing implementation.
+ * <P>
* This method is called at construction time of a
- * <code>MessagesBundleGroup</code>.
+ * <code>MessagesBundleGroup</code>.
+ *
* @return messages bundle group name
*/
String createMessagesBundleGroupName();
-
+
String createMessagesBundleId();
-
+
/**
* Load all bundles making up a messages bundle group from the underlying
- * source.
- * This method is called at construction time of a
- * <code>MessagesBundleGroup</code>.
+ * source. This method is called at construction time of a
+ * <code>MessagesBundleGroup</code>.
+ *
* @return all bundles making a bundle group
- * @throws MessageException problem loading bundles
+ * @throws MessageException
+ * problem loading bundles
*/
MessagesBundle[] loadMessagesBundles() throws MessageException;
-
+
/**
- * Creates a new bundle for the given <code>Locale</code>. If the
+ * Creates a new bundle for the given <code>Locale</code>. If the
* <code>Locale</code> is <code>null</code>, the default system
* <code>Locale</code> is assumed.
- * @param locale locale for which to create the messages bundle
+ *
+ * @param locale
+ * locale for which to create the messages bundle
* @return a new messages bundle
- * @throws MessageException problem creating a new messages bundle
+ * @throws MessageException
+ * problem creating a new messages bundle
*/
MessagesBundle createMessagesBundle(Locale locale) throws MessageException;
-
+
String getProjectName();
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/PropertiesFileGroupStrategy.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/PropertiesFileGroupStrategy.java
index 04f6723..5905295 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/PropertiesFileGroupStrategy.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/PropertiesFileGroupStrategy.java
@@ -39,7 +39,7 @@
* @author Pascal Essiembre
*/
public class PropertiesFileGroupStrategy implements
- IMessagesBundleGroupStrategy {
+ IMessagesBundleGroupStrategy {
/** Empty bundle array. */
private static final MessagesBundle[] EMPTY_MESSAGES = new MessagesBundle[] {};
@@ -64,24 +64,24 @@
* file from which to derive the group
*/
public PropertiesFileGroupStrategy(File file,
- IPropertiesSerializerConfig serializerConfig,
- IPropertiesDeserializerConfig deserializerConfig) {
- super();
- this.serializerConfig = serializerConfig;
- this.deserializerConfig = deserializerConfig;
- this.file = file;
- this.fileExtension = file.getName().replaceFirst("(.*\\.)(.*)", "$2"); //$NON-NLS-1$ //$NON-NLS-2$
+ IPropertiesSerializerConfig serializerConfig,
+ IPropertiesDeserializerConfig deserializerConfig) {
+ super();
+ this.serializerConfig = serializerConfig;
+ this.deserializerConfig = deserializerConfig;
+ this.file = file;
+ this.fileExtension = file.getName().replaceFirst("(.*\\.)(.*)", "$2"); //$NON-NLS-1$ //$NON-NLS-2$
- String patternCore = "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
- + fileExtension + ")$"; //$NON-NLS-1$
+ String patternCore = "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
+ + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
+ + fileExtension + ")$"; //$NON-NLS-1$
- // Compute and cache name
- String namePattern = "^(.*?)" + patternCore; //$NON-NLS-1$
- this.baseName = file.getName().replaceFirst(namePattern, "$1"); //$NON-NLS-1$
+ // Compute and cache name
+ String namePattern = "^(.*?)" + patternCore; //$NON-NLS-1$
+ this.baseName = file.getName().replaceFirst(namePattern, "$1"); //$NON-NLS-1$
- // File matching pattern
- this.fileMatchPattern = "^(" + baseName + ")" + patternCore; //$NON-NLS-1$//$NON-NLS-2$
+ // File matching pattern
+ this.fileMatchPattern = "^(" + baseName + ")" + patternCore; //$NON-NLS-1$//$NON-NLS-2$
}
/**
@@ -89,7 +89,7 @@
* #getMessagesBundleGroupName()
*/
public String createMessagesBundleGroupName() {
- return baseName + "[...]." + fileExtension; //$NON-NLS-1$
+ return baseName + "[...]." + fileExtension; //$NON-NLS-1$
}
/**
@@ -97,26 +97,26 @@
* #loadMessagesBundles()
*/
public MessagesBundle[] loadMessagesBundles() throws MessageException {
- File[] resources = null;
- File parentDir = file.getParentFile();
- if (parentDir != null) {
- resources = parentDir.listFiles();
- }
- Collection<MessagesBundle> bundles = new ArrayList<MessagesBundle>();
- if (resources != null) {
- for (int i = 0; i < resources.length; i++) {
- File resource = resources[i];
- String resourceName = resource.getName();
- if (resource.isFile() && resourceName.matches(fileMatchPattern)) {
- // Build local title
- String localeText = resourceName.replaceFirst(
- fileMatchPattern, "$2"); //$NON-NLS-1$
- Locale locale = BabelUtils.parseLocale(localeText);
- bundles.add(createBundle(locale, resource));
- }
- }
- }
- return bundles.toArray(EMPTY_MESSAGES);
+ File[] resources = null;
+ File parentDir = file.getParentFile();
+ if (parentDir != null) {
+ resources = parentDir.listFiles();
+ }
+ Collection<MessagesBundle> bundles = new ArrayList<MessagesBundle>();
+ if (resources != null) {
+ for (int i = 0; i < resources.length; i++) {
+ File resource = resources[i];
+ String resourceName = resource.getName();
+ if (resource.isFile() && resourceName.matches(fileMatchPattern)) {
+ // Build local title
+ String localeText = resourceName.replaceFirst(
+ fileMatchPattern, "$2"); //$NON-NLS-1$
+ Locale locale = BabelUtils.parseLocale(localeText);
+ bundles.add(createBundle(locale, resource));
+ }
+ }
+ }
+ return bundles.toArray(EMPTY_MESSAGES);
}
/**
@@ -124,8 +124,8 @@
* #createBundle(java.util.Locale)
*/
public MessagesBundle createMessagesBundle(Locale locale) {
- // TODO Implement me (code exists in SourceForge version)
- return null;
+ // TODO Implement me (code exists in SourceForge version)
+ return null;
}
/**
@@ -138,52 +138,52 @@
* @return an initialized bundle
*/
protected MessagesBundle createBundle(Locale locale, File resource)
- throws MessageException {
- try {
- // TODO have the text de/serializer tied to Eclipse preferences,
- // singleton per project, and listening for changes
- return new MessagesBundle(new PropertiesFileResource(locale,
- new PropertiesSerializer(serializerConfig),
- new PropertiesDeserializer(deserializerConfig), resource));
- } catch (FileNotFoundException e) {
- throw new MessageException("Cannot create bundle for locale " //$NON-NLS-1$
- + locale + " and resource " + resource, e); //$NON-NLS-1$
- }
+ throws MessageException {
+ try {
+ // TODO have the text de/serializer tied to Eclipse preferences,
+ // singleton per project, and listening for changes
+ return new MessagesBundle(new PropertiesFileResource(locale,
+ new PropertiesSerializer(serializerConfig),
+ new PropertiesDeserializer(deserializerConfig), resource));
+ } catch (FileNotFoundException e) {
+ throw new MessageException("Cannot create bundle for locale " //$NON-NLS-1$
+ + locale + " and resource " + resource, e); //$NON-NLS-1$
+ }
}
public String createMessagesBundleId() {
- String path = file.getAbsolutePath();
- int index = path.indexOf("src");
- String pathBeforeSrc = path.substring(0, index - 1);
- int lastIndexOf = pathBeforeSrc.lastIndexOf(File.separatorChar);
- String projectName = path.substring(lastIndexOf + 1, index - 1);
- String relativeFilePath = path.substring(index, path.length());
+ String path = file.getAbsolutePath();
+ int index = path.indexOf("src");
+ String pathBeforeSrc = path.substring(0, index - 1);
+ int lastIndexOf = pathBeforeSrc.lastIndexOf(File.separatorChar);
+ String projectName = path.substring(lastIndexOf + 1, index - 1);
+ String relativeFilePath = path.substring(index, path.length());
- IFile f = ResourcesPlugin.getWorkspace().getRoot()
- .getProject(projectName).getFile(relativeFilePath);
+ IFile f = ResourcesPlugin.getWorkspace().getRoot()
+ .getProject(projectName).getFile(relativeFilePath);
- return NameUtils.getResourceBundleId(f);
+ return NameUtils.getResourceBundleId(f);
}
public String getProjectName() {
- IPath path = ResourcesPlugin.getWorkspace().getRoot().getLocation();
- IPath fullPath = null;
- if (this.file.getAbsolutePath().contains(path.toOSString())) {
- fullPath = new Path(this.file.getAbsolutePath());
- } else {
- fullPath = new Path(path.toOSString() + this.file.getAbsolutePath());
- }
+ IPath path = ResourcesPlugin.getWorkspace().getRoot().getLocation();
+ IPath fullPath = null;
+ if (this.file.getAbsolutePath().contains(path.toOSString())) {
+ fullPath = new Path(this.file.getAbsolutePath());
+ } else {
+ fullPath = new Path(path.toOSString() + this.file.getAbsolutePath());
+ }
- IFile file = ResourcesPlugin.getWorkspace().getRoot()
- .getFileForLocation(fullPath);
+ IFile file = ResourcesPlugin.getWorkspace().getRoot()
+ .getFileForLocation(fullPath);
- if (file != null) {
- return ResourcesPlugin.getWorkspace().getRoot()
- .getProject(file.getFullPath().segments()[0]).getName();
- } else {
- return null;
- }
-
+ if (file != null) {
+ return ResourcesPlugin.getWorkspace().getRoot()
+ .getProject(file.getFullPath().segments()[0]).getName();
+ } else {
+ return null;
+ }
+
}
// public static String getResourceBundleId (IResource resource) {
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IAbstractKeyTreeModel.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IAbstractKeyTreeModel.java
index 632184f..3b0cbb3 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IAbstractKeyTreeModel.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IAbstractKeyTreeModel.java
@@ -10,19 +10,18 @@
******************************************************************************/
package org.eclipse.babel.core.message.tree;
-
public interface IAbstractKeyTreeModel {
- IKeyTreeNode[] getChildren(IKeyTreeNode node);
+ IKeyTreeNode[] getChildren(IKeyTreeNode node);
- IKeyTreeNode getChild(String key);
+ IKeyTreeNode getChild(String key);
- IKeyTreeNode[] getRootNodes();
+ IKeyTreeNode[] getRootNodes();
- IKeyTreeNode getRootNode();
+ IKeyTreeNode getRootNode();
- IKeyTreeNode getParent(IKeyTreeNode node);
+ IKeyTreeNode getParent(IKeyTreeNode node);
- void accept(IKeyTreeVisitor visitor, IKeyTreeNode node);
+ void accept(IKeyTreeVisitor visitor, IKeyTreeNode node);
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeNode.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeNode.java
index b7b8585..552774d 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeNode.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeNode.java
@@ -14,66 +14,66 @@
public interface IKeyTreeNode {
- /**
- * Returns the key of the corresponding Resource-Bundle entry.
- *
- * @return The key of the Resource-Bundle entry
- */
- String getMessageKey();
+ /**
+ * Returns the key of the corresponding Resource-Bundle entry.
+ *
+ * @return The key of the Resource-Bundle entry
+ */
+ String getMessageKey();
- /**
- * Returns the set of Resource-Bundle entries of the next deeper hierarchy
- * level that share the represented entry as their common parent.
- *
- * @return The direct child Resource-Bundle entries
- */
- IKeyTreeNode[] getChildren();
+ /**
+ * Returns the set of Resource-Bundle entries of the next deeper hierarchy
+ * level that share the represented entry as their common parent.
+ *
+ * @return The direct child Resource-Bundle entries
+ */
+ IKeyTreeNode[] getChildren();
- /**
- * The represented Resource-Bundle entry's id without the prefix defined by
- * the entry's parent.
- *
- * @return The Resource-Bundle entry's display name.
- */
- String getName();
+ /**
+ * The represented Resource-Bundle entry's id without the prefix defined by
+ * the entry's parent.
+ *
+ * @return The Resource-Bundle entry's display name.
+ */
+ String getName();
- /**
- * Returns the set of Resource-Bundle entries from all deeper hierarchy
- * levels that share the represented entry as their common parent.
- *
- * @return All child Resource-Bundle entries
- */
- // Collection<? extends IKeyTreeItem> getNestedChildren();
+ /**
+ * Returns the set of Resource-Bundle entries from all deeper hierarchy
+ * levels that share the represented entry as their common parent.
+ *
+ * @return All child Resource-Bundle entries
+ */
+ // Collection<? extends IKeyTreeItem> getNestedChildren();
- /**
- * Returns whether this Resource-Bundle entry is visible under the given
- * filter expression.
- *
- * @param filter
- * The filter expression
- * @return True if the filter expression matches the represented
- * Resource-Bundle entry
- */
- // boolean applyFilter(String filter);
+ /**
+ * Returns whether this Resource-Bundle entry is visible under the given
+ * filter expression.
+ *
+ * @param filter
+ * The filter expression
+ * @return True if the filter expression matches the represented
+ * Resource-Bundle entry
+ */
+ // boolean applyFilter(String filter);
- /**
- * The Resource-Bundle entries parent.
- *
- * @return The parent Resource-Bundle entry
- */
- IKeyTreeNode getParent();
+ /**
+ * The Resource-Bundle entries parent.
+ *
+ * @return The parent Resource-Bundle entry
+ */
+ IKeyTreeNode getParent();
- /**
- * The Resource-Bundles key representation.
- *
- * @return The Resource-Bundle reference, if known
- */
- IMessagesBundleGroup getMessagesBundleGroup();
+ /**
+ * The Resource-Bundles key representation.
+ *
+ * @return The Resource-Bundle reference, if known
+ */
+ IMessagesBundleGroup getMessagesBundleGroup();
- boolean isUsedAsKey();
+ boolean isUsedAsKey();
- void setParent(IKeyTreeNode parentNode);
+ void setParent(IKeyTreeNode parentNode);
- void addChild(IKeyTreeNode childNode);
+ void addChild(IKeyTreeNode childNode);
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeVisitor.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeVisitor.java
index ac7a535..5bdd808 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeVisitor.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeVisitor.java
@@ -10,7 +10,6 @@
******************************************************************************/
package org.eclipse.babel.core.message.tree;
-
/**
* Objects implementing this interface can act as a visitor to a
* <code>IKeyTreeModel</code>.
@@ -18,11 +17,11 @@
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public interface IKeyTreeVisitor {
- /**
- * Visits a key tree node.
- *
- * @param item
- * key tree node to visit
- */
- void visitKeyTreeNode(IKeyTreeNode node);
+ /**
+ * Visits a key tree node.
+ *
+ * @param item
+ * key tree node to visit
+ */
+ void visitKeyTreeNode(IKeyTreeNode node);
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/TreeType.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/TreeType.java
index bf833e9..c2e771c 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/TreeType.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/TreeType.java
@@ -11,18 +11,20 @@
package org.eclipse.babel.core.message.tree;
/**
- * Enum for two tree types. If a tree has the type {@link #Tree}, then it
- * is displayed as tree. E.g. following key is given: parent.child.grandchild
- * result:
+ * Enum for two tree types. If a tree has the type {@link #Tree}, then it is
+ * displayed as tree. E.g. following key is given: parent.child.grandchild
+ * result:
+ *
* <pre>
* parent
* child
* grandchild
* </pre>
+ *
* If it is {@link #Flat}, it will be displayed as parent.child.grandchild.
*
* @author Alexej Strelzow
*/
public enum TreeType {
- Tree, Flat
+ Tree, Flat
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/AbstractKeyTreeModel.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/AbstractKeyTreeModel.java
index 74be09b..33836a1 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/AbstractKeyTreeModel.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/AbstractKeyTreeModel.java
@@ -23,15 +23,18 @@
import org.eclipse.babel.core.message.tree.IKeyTreeNode;
import org.eclipse.babel.core.message.tree.IKeyTreeVisitor;
-
/**
- * Hierarchical representation of all keys making up a
+ * Hierarchical representation of all keys making up a
* {@link MessagesBundleGroup}.
- *
- * Key tree model, using a delimiter to separate key sections
- * into nodes. For instance, a dot (.) delimiter on the following key...<p>
- * <code>person.address.street</code><P>
- * ... will result in the following node hierarchy:<p>
+ *
+ * Key tree model, using a delimiter to separate key sections into nodes. For
+ * instance, a dot (.) delimiter on the following key...
+ * <p>
+ * <code>person.address.street</code>
+ * <P>
+ * ... will result in the following node hierarchy:
+ * <p>
+ *
* <pre>
* person
* address
@@ -44,13 +47,13 @@
private List<IKeyTreeModelListener> listeners = new ArrayList<IKeyTreeModelListener>();
private Comparator<IKeyTreeNode> comparator;
-
+
private KeyTreeNode rootNode = new KeyTreeNode(null, null, null, null);
-
+
private String delimiter;
private MessagesBundleGroup messagesBundleGroup;
-
- protected static final KeyTreeNode[] EMPTY_NODES = new KeyTreeNode[]{};
+
+ protected static final KeyTreeNode[] EMPTY_NODES = new KeyTreeNode[] {};
/**
* Defaults to ".".
@@ -61,30 +64,36 @@
/**
* Constructor.
- * @param messagesBundleGroup {@link MessagesBundleGroup} instance
- * @param delimiter key section delimiter
+ *
+ * @param messagesBundleGroup
+ * {@link MessagesBundleGroup} instance
+ * @param delimiter
+ * key section delimiter
*/
- public AbstractKeyTreeModel(
- MessagesBundleGroup messagesBundleGroup, String delimiter) {
+ public AbstractKeyTreeModel(MessagesBundleGroup messagesBundleGroup,
+ String delimiter) {
super();
this.messagesBundleGroup = messagesBundleGroup;
this.delimiter = delimiter;
createTree();
-
- messagesBundleGroup.addMessagesBundleGroupListener(
- new MessagesBundleGroupAdapter() {
- public void keyAdded(String key) {
- createTreeNodes(key);
- }
- public void keyRemoved(String key) {
- removeTreeNodes(key);
- }
- });
+
+ messagesBundleGroup
+ .addMessagesBundleGroupListener(new MessagesBundleGroupAdapter() {
+ public void keyAdded(String key) {
+ createTreeNodes(key);
+ }
+
+ public void keyRemoved(String key) {
+ removeTreeNodes(key);
+ }
+ });
}
/**
* Adds a key tree model listener.
- * @param listener key tree model listener
+ *
+ * @param listener
+ * key tree model listener
*/
public void addKeyTreeModelListener(IKeyTreeModelListener listener) {
listeners.add(0, listener);
@@ -92,27 +101,34 @@
/**
* Removes a key tree model listener.
- * @param listener key tree model listener
+ *
+ * @param listener
+ * key tree model listener
*/
public void removeKeyTreeModelListener(IKeyTreeModelListener listener) {
listeners.remove(listener);
}
-
+
/**
* Notify all listeners that a node was added.
- * @param node added node
+ *
+ * @param node
+ * added node
*/
- protected void fireNodeAdded(KeyTreeNode node) {
+ protected void fireNodeAdded(KeyTreeNode node) {
for (IKeyTreeModelListener listener : listeners) {
listener.nodeAdded(node);
}
}
+
/**
* Notify all listeners that a node was removed.
- * @param node removed node
+ *
+ * @param node
+ * removed node
*/
- protected void fireNodeRemoved(KeyTreeNode node) {
- for (IKeyTreeModelListener listener : listeners) {
+ protected void fireNodeRemoved(KeyTreeNode node) {
+ for (IKeyTreeModelListener listener : listeners) {
listener.nodeRemoved(node);
}
}
@@ -121,26 +137,30 @@
* Gets all nodes on a branch, starting (and including) with parent node.
* This has the same effect of calling <code>getChildren(KeyTreeNode)</code>
* recursively on all children.
- * @param parentNode root of a branch
+ *
+ * @param parentNode
+ * root of a branch
* @return all nodes on a branch
*/
// TODO inline and remove this method.
public KeyTreeNode[] getBranch(KeyTreeNode parentNode) {
- return parentNode.getBranch().toArray(new KeyTreeNode[]{});
+ return parentNode.getBranch().toArray(new KeyTreeNode[] {});
}
/**
- * Accepts the visitor, visiting the given node argument, along with all
- * its children. Passing a <code>null</code> node will
- * walk the entire tree.
- * @param visitor the object to visit
- * @param node the starting key tree node
+ * Accepts the visitor, visiting the given node argument, along with all its
+ * children. Passing a <code>null</code> node will walk the entire tree.
+ *
+ * @param visitor
+ * the object to visit
+ * @param node
+ * the starting key tree node
*/
public void accept(IKeyTreeVisitor visitor, IKeyTreeNode node) {
if (node == null) {
return;
}
-
+
if (node != null) {
visitor.visitKeyTreeNode(node);
}
@@ -152,14 +172,16 @@
/**
* Gets the child nodes of a given key tree node.
- * @param node the node from which to get children
+ *
+ * @param node
+ * the node from which to get children
* @return child nodes
*/
public IKeyTreeNode[] getChildren(IKeyTreeNode node) {
if (node == null) {
return null;
}
-
+
IKeyTreeNode[] nodes = node.getChildren();
if (getComparator() != null) {
Arrays.sort(nodes, getComparator());
@@ -167,8 +189,9 @@
return nodes;
}
- /**
+ /**
* Gets the comparator.
+ *
* @return the comparator
*/
public Comparator<IKeyTreeNode> getComparator() {
@@ -177,76 +200,90 @@
/**
* Sets the node comparator for sorting sibling nodes.
- * @param comparator node comparator
+ *
+ * @param comparator
+ * node comparator
*/
public void setComparator(Comparator<IKeyTreeNode> comparator) {
this.comparator = comparator;
}
-
+
/**
- * Depth first for the first leaf node that is not filtered.
- * It makes the entire branch not not filtered
+ * Depth first for the first leaf node that is not filtered. It makes the
+ * entire branch not not filtered
*
- * @param filter The leaf filter.
+ * @param filter
+ * The leaf filter.
* @param node
- * @return true if this node or one of its descendant is in the filter (ie is displayed)
+ * @return true if this node or one of its descendant is in the filter (ie
+ * is displayed)
*/
- public boolean isBranchFiltered(IKeyTreeNodeLeafFilter filter, IKeyTreeNode node) {
- if (!((KeyTreeNode)node).hasChildren()) {
- return filter.isFilteredLeaf(node);
- } else {
- //depth first:
- for (IKeyTreeNode childNode : ((KeyTreeNode)node).getChildrenInternal()) {
- if (isBranchFiltered(filter, childNode)) {
- return true;
- }
- }
- }
- return false;
+ public boolean isBranchFiltered(IKeyTreeNodeLeafFilter filter,
+ IKeyTreeNode node) {
+ if (!((KeyTreeNode) node).hasChildren()) {
+ return filter.isFilteredLeaf(node);
+ } else {
+ // depth first:
+ for (IKeyTreeNode childNode : ((KeyTreeNode) node)
+ .getChildrenInternal()) {
+ if (isBranchFiltered(filter, childNode)) {
+ return true;
+ }
+ }
+ }
+ return false;
}
-
+
/**
* Gets the delimiter.
+ *
* @return delimiter
*/
public String getDelimiter() {
return delimiter;
}
+
/**
* Sets the delimiter.
- * @param delimiter delimiter
+ *
+ * @param delimiter
+ * delimiter
*/
public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}
-
- /**
- * Gets the key tree root nodes.
- * @return key tree root nodes
- */
+
+ /**
+ * Gets the key tree root nodes.
+ *
+ * @return key tree root nodes
+ */
public IKeyTreeNode[] getRootNodes() {
return getChildren(rootNode);
}
public IKeyTreeNode getRootNode() {
- return rootNode;
+ return rootNode;
}
-
+
/**
* Gets the parent node of the given node.
- * @param node node from which to get parent
+ *
+ * @param node
+ * node from which to get parent
* @return parent node
*/
public IKeyTreeNode getParent(IKeyTreeNode node) {
return node.getParent();
}
-
+
/**
* Gets the messages bundle group that this key tree represents.
+ *
* @return messages bundle group
*/
public MessagesBundleGroup getMessagesBundleGroup() {
- //TODO consider moving this method (and part of constructor) to super
+ // TODO consider moving this method (and part of constructor) to super
return messagesBundleGroup;
}
@@ -254,11 +291,11 @@
rootNode = new KeyTreeNode(null, null, null, messagesBundleGroup);
String[] keys = messagesBundleGroup.getMessageKeys();
for (int i = 0; i < keys.length; i++) {
- String key = keys[i];
+ String key = keys[i];
createTreeNodes(key);
}
}
-
+
private void createTreeNodes(String bundleKey) {
StringTokenizer tokens = new StringTokenizer(bundleKey, delimiter);
KeyTreeNode node = rootNode;
@@ -268,7 +305,8 @@
bundleKeyPart += name;
KeyTreeNode child = (KeyTreeNode) node.getChild(name);
if (child == null) {
- child = new KeyTreeNode(node, name, bundleKeyPart, messagesBundleGroup);
+ child = new KeyTreeNode(node, name, bundleKeyPart,
+ messagesBundleGroup);
fireNodeAdded(child);
}
bundleKeyPart += delimiter;
@@ -276,6 +314,7 @@
}
node.setUsedAsKey();
}
+
private void removeTreeNodes(String bundleKey) {
if (bundleKey == null) {
return;
@@ -286,8 +325,8 @@
String name = tokens.nextToken();
node = (KeyTreeNode) node.getChild(name);
if (node == null) {
- System.err.println(
- "No RegEx node matching bundleKey to remove"); //$NON-NLS-1$
+ System.err
+ .println("No RegEx node matching bundleKey to remove"); //$NON-NLS-1$
return;
}
}
@@ -295,34 +334,35 @@
parentNode.removeChild(node);
fireNodeRemoved(node);
while (parentNode != rootNode) {
- if (!parentNode.hasChildren() && !messagesBundleGroup.isMessageKey(
- parentNode.getMessageKey())) {
- ((KeyTreeNode)parentNode.getParent()).removeChild(parentNode);
+ if (!parentNode.hasChildren()
+ && !messagesBundleGroup.isMessageKey(parentNode
+ .getMessageKey())) {
+ ((KeyTreeNode) parentNode.getParent()).removeChild(parentNode);
fireNodeRemoved(parentNode);
}
- parentNode = (KeyTreeNode)parentNode.getParent();
+ parentNode = (KeyTreeNode) parentNode.getParent();
}
}
-
-
+
public interface IKeyTreeNodeLeafFilter {
- /**
- * @param leafNode A leaf node. Must not be called if the node has children
- * @return true if this node should be filtered.
- */
- boolean isFilteredLeaf(IKeyTreeNode leafNode);
+ /**
+ * @param leafNode
+ * A leaf node. Must not be called if the node has children
+ * @return true if this node should be filtered.
+ */
+ boolean isFilteredLeaf(IKeyTreeNode leafNode);
}
public IKeyTreeNode getChild(String key) {
return returnNodeWithKey(key, rootNode);
}
-
+
private IKeyTreeNode returnNodeWithKey(String key, IKeyTreeNode node) {
-
- if (!key.equals(node.getMessageKey())) {
+
+ if (!key.equals(node.getMessageKey())) {
for (IKeyTreeNode n : node.getChildren()) {
IKeyTreeNode returnNode = returnNodeWithKey(key, n);
- if (returnNode == null) {
+ if (returnNode == null) {
continue;
} else {
return returnNode;
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/IKeyTreeModelListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/IKeyTreeModelListener.java
index 98bece0..71f42a1 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/IKeyTreeModelListener.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/IKeyTreeModelListener.java
@@ -12,18 +12,24 @@
/**
* Listener notified of changes to a {@link IKeyTreeModel}.
+ *
* @author Pascal Essiembre
*/
public interface IKeyTreeModelListener {
- /**
- * Invoked when a key tree node is added.
- * @param node key tree node
- */
+ /**
+ * Invoked when a key tree node is added.
+ *
+ * @param node
+ * key tree node
+ */
void nodeAdded(KeyTreeNode node);
- /**
- * Invoked when a key tree node is remove.
- * @param node key tree node
- */
+
+ /**
+ * Invoked when a key tree node is remove.
+ *
+ * @param node
+ * key tree node
+ */
void nodeRemoved(KeyTreeNode node);
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/KeyTreeNode.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/KeyTreeNode.java
index 6b0fd94..62dd06b 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/KeyTreeNode.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/KeyTreeNode.java
@@ -22,47 +22,50 @@
/**
* Class representing a node in the tree of keys.
- *
+ *
* @author Pascal Essiembre
*/
public class KeyTreeNode implements Comparable<KeyTreeNode>, IKeyTreeNode {
- public static final KeyTreeNode[] EMPTY_KEY_TREE_NODES =
- new KeyTreeNode[] {};
-
+ public static final KeyTreeNode[] EMPTY_KEY_TREE_NODES = new KeyTreeNode[] {};
+
/**
* the parent node, if any, which will have a <code>messageKey</code> field
- * the same as this object but with the last component (following the
- * last period) removed
+ * the same as this object but with the last component (following the last
+ * period) removed
*/
private IKeyTreeNode parent;
-
+
/**
* the name, being the part of the full key that follows the last period
*/
private final String name;
-
+
/**
* the full key, being a sequence of names separated by periods with the
* last name being the name given by the <code>name</code> field of this
- * object
+ * object
*/
private String messageKey;
-
+
private final Map<String, IKeyTreeNode> children = new TreeMap<String, IKeyTreeNode>();
- private boolean usedAsKey = false;
-
- private IMessagesBundleGroup messagesBundleGroup;
-
+ private boolean usedAsKey = false;
+
+ private IMessagesBundleGroup messagesBundleGroup;
+
/**
* Constructor.
- * @param parent parent node
- * @param name node name
- * @param messageKey messages bundle key
+ *
+ * @param parent
+ * parent node
+ * @param name
+ * node name
+ * @param messageKey
+ * messages bundle key
*/
- public KeyTreeNode(
- IKeyTreeNode parent, String name, String messageKey, IMessagesBundleGroup messagesBundleGroup) {
+ public KeyTreeNode(IKeyTreeNode parent, String name, String messageKey,
+ IMessagesBundleGroup messagesBundleGroup) {
super();
this.parent = parent;
this.name = name;
@@ -74,35 +77,37 @@
}
/**
- * @return the name, being the part of the full key that follows the last period
+ * @return the name, being the part of the full key that follows the last
+ * period
*/
public String getName() {
return name;
}
/**
- * @return the parent node, if any, which will have a <code>messageKey</code> field
- * the same as this object but with the last component (following the
- * last period) removed
+ * @return the parent node, if any, which will have a
+ * <code>messageKey</code> field the same as this object but with
+ * the last component (following the last period) removed
*/
public IKeyTreeNode getParent() {
return parent;
}
/**
- * @return the full key, being a sequence of names separated by periods with the
- * last name being the name given by the <code>name</code> field of this
- * object
+ * @return the full key, being a sequence of names separated by periods with
+ * the last name being the name given by the <code>name</code> field
+ * of this object
*/
public String getMessageKey() {
return messageKey;
}
-
+
/**
* Gets all notes from root to this node.
+ *
* @return all notes from root to this node
*/
- /*default*/ IKeyTreeNode[] getPath() {
+ /* default */IKeyTreeNode[] getPath() {
List<IKeyTreeNode> nodes = new ArrayList<IKeyTreeNode>();
IKeyTreeNode node = this;
while (node != null && node.getName() != null) {
@@ -115,26 +120,29 @@
public IKeyTreeNode[] getChildren() {
return children.values().toArray(EMPTY_KEY_TREE_NODES);
}
- /*default*/ boolean hasChildren() {
+
+ /* default */boolean hasChildren() {
return !children.isEmpty();
}
+
public IKeyTreeNode getChild(String childName) {
return children.get(childName);
}
-
+
/**
* @return the children without creating a new object
*/
Collection<IKeyTreeNode> getChildrenInternal() {
- return children.values();
+ return children.values();
}
-
+
/**
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(KeyTreeNode node) {
- // TODO this is wrong. For example, menu.label and textbox.label are indicated as equal,
- // which means they overwrite each other in the tree set!!!
+ // TODO this is wrong. For example, menu.label and textbox.label are
+ // indicated as equal,
+ // which means they overwrite each other in the tree set!!!
if (parent == null && node.parent != null) {
return -1;
}
@@ -150,7 +158,7 @@
public boolean equals(Object obj) {
if (!(obj instanceof KeyTreeNode)) {
return false;
- }
+ }
KeyTreeNode node = (KeyTreeNode) obj;
return BabelUtils.equals(name, node.name)
&& BabelUtils.equals(parent, node.parent);
@@ -160,66 +168,67 @@
* @see java.lang.Object#toString()
*/
public String toString() {
- return messageKey;
-// return "KeyTreeNode=[[parent=" + parent //$NON-NLS-1$
-// + "][name=" + name //$NON-NLS-1$
-// + "][messageKey=" + messageKey + "]]"; //$NON-NLS-1$ //$NON-NLS-2$
+ return messageKey;
+ // return "KeyTreeNode=[[parent=" + parent //$NON-NLS-1$
+ // + "][name=" + name //$NON-NLS-1$
+ // + "][messageKey=" + messageKey + "]]"; //$NON-NLS-1$ //$NON-NLS-2$
}
public void addChild(IKeyTreeNode childNode) {
children.put(childNode.getName(), childNode);
}
+
public void removeChild(KeyTreeNode childNode) {
children.remove(childNode.getName());
- //TODO remove parent on child node?
+ // TODO remove parent on child node?
}
// TODO: remove this, or simplify it using method getDescendants
- public Collection<KeyTreeNode> getBranch() {
+ public Collection<KeyTreeNode> getBranch() {
Collection<KeyTreeNode> childNodes = new ArrayList<KeyTreeNode>();
childNodes.add(this);
for (IKeyTreeNode childNode : this.getChildren()) {
- childNodes.addAll(((KeyTreeNode)childNode).getBranch());
+ childNodes.addAll(((KeyTreeNode) childNode).getBranch());
}
return childNodes;
- }
+ }
- public Collection<IKeyTreeNode> getDescendants() {
- Collection<IKeyTreeNode> descendants = new ArrayList<IKeyTreeNode>();
- for (IKeyTreeNode child : children.values()) {
- descendants.add(child);
- descendants.addAll(((KeyTreeNode)child).getDescendants());
- }
- return descendants;
- }
+ public Collection<IKeyTreeNode> getDescendants() {
+ Collection<IKeyTreeNode> descendants = new ArrayList<IKeyTreeNode>();
+ for (IKeyTreeNode child : children.values()) {
+ descendants.add(child);
+ descendants.addAll(((KeyTreeNode) child).getDescendants());
+ }
+ return descendants;
+ }
- /**
- * Marks this node as representing an actual key.
- * <P>
- * For example, if the bundle contains two keys:
- * <UL>
- * <LI>foo.bar</LI>
- * <LI>foo.bar.tooltip</LI>
- * </UL>
- * This will create three nodes, foo, which has a child
- * node called bar, which has a child node called tooltip.
- * However foo is not an actual key but is only a parent node.
- * foo.bar is an actual key even though it is also a parent node.
- */
- public void setUsedAsKey() {
- usedAsKey = true;
- }
+ /**
+ * Marks this node as representing an actual key.
+ * <P>
+ * For example, if the bundle contains two keys:
+ * <UL>
+ * <LI>foo.bar</LI>
+ * <LI>foo.bar.tooltip</LI>
+ * </UL>
+ * This will create three nodes, foo, which has a child node called bar,
+ * which has a child node called tooltip. However foo is not an actual key
+ * but is only a parent node. foo.bar is an actual key even though it is
+ * also a parent node.
+ */
+ public void setUsedAsKey() {
+ usedAsKey = true;
+ }
- public boolean isUsedAsKey() {
- return usedAsKey;
- }
-
- public IMessagesBundleGroup getMessagesBundleGroup() {
- return this.messagesBundleGroup;
- }
-
- public void setParent(IKeyTreeNode parentNode) {
+ public boolean isUsedAsKey() {
+ return usedAsKey;
+ }
+
+ public IMessagesBundleGroup getMessagesBundleGroup() {
+ return this.messagesBundleGroup;
+ }
+
+ public void setParent(IKeyTreeNode parentNode) {
this.parent = parentNode;
}
-
+
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/IKeyCheck.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/IKeyCheck.java
index 5a3847e..3e5fb9a 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/IKeyCheck.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/IKeyCheck.java
@@ -13,18 +13,22 @@
import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
/**
- * All purpose key testing. Use this interface to establish whether
- * a message key within a {@link MessagesBundleGroup} is answering
- * successfully to any condition.
+ * All purpose key testing. Use this interface to establish whether a message
+ * key within a {@link MessagesBundleGroup} is answering successfully to any
+ * condition.
+ *
* @author Pascal Essiembre
*/
public interface IKeyCheck {
- /**
- * Checks whether a key meets the implemented condition.
- * @param messagesBundleGroup messages bundle group
- * @param key message key to test
- * @return <code>true</code> if condition is successfully tested
- */
+ /**
+ * Checks whether a key meets the implemented condition.
+ *
+ * @param messagesBundleGroup
+ * messages bundle group
+ * @param key
+ * message key to test
+ * @return <code>true</code> if condition is successfully tested
+ */
boolean checkKey(MessagesBundleGroup messagesBundleGroup, String key);
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/KeyCheckVisitor.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/KeyCheckVisitor.java
index 6f92041..657f912 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/KeyCheckVisitor.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/KeyCheckVisitor.java
@@ -18,31 +18,32 @@
import org.eclipse.babel.core.message.tree.IKeyTreeVisitor;
import org.eclipse.babel.core.message.tree.internal.KeyTreeNode;
-
/**
* Visitor for going to a tree (or tree branch), and aggregating information
* about executed checks.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public class KeyCheckVisitor implements IKeyTreeVisitor {
private static final KeyTreeNode[] EMPTY_NODES = new KeyTreeNode[] {};
-
+
private IKeyCheck keyCheck;
private final MessagesBundleGroup messagesBundleGroup;
-
+
private final Collection<IKeyTreeNode> passedNodes = new ArrayList<IKeyTreeNode>();
private final Collection<IKeyTreeNode> failedNodes = new ArrayList<IKeyTreeNode>();
-
+
/**
* Constructor.
*/
- public KeyCheckVisitor(
- MessagesBundleGroup messagesBundleGroup, IKeyCheck keyCheck) {
+ public KeyCheckVisitor(MessagesBundleGroup messagesBundleGroup,
+ IKeyCheck keyCheck) {
super();
this.keyCheck = keyCheck;
this.messagesBundleGroup = messagesBundleGroup;
}
+
/**
* Constructor.
*/
@@ -50,11 +51,10 @@
super();
this.messagesBundleGroup = messagesBundleGroup;
}
-
+
/**
* @see org.eclipse.babel.core.message.internal.tree.visitor.IKeyTreeVisitor
- * #visitKeyTreeNode(
- * org.eclipse.babel.core.message.internal.tree.internal.KeyTreeNode)
+ * #visitKeyTreeNode(org.eclipse.babel.core.message.internal.tree.internal.KeyTreeNode)
*/
public void visitKeyTreeNode(IKeyTreeNode node) {
if (keyCheck == null) {
@@ -69,19 +69,22 @@
/**
* Gets all nodes that returned true upon invoking a {@link IKeyCheck}.
+ *
* @return all successful nodes
*/
public KeyTreeNode[] getPassedNodes() {
return passedNodes.toArray(EMPTY_NODES);
}
+
/**
* Gets all nodes that returned false upon invoking a {@link IKeyCheck}.
+ *
* @return all failing nodes
*/
public KeyTreeNode[] getFailedNodes() {
return failedNodes.toArray(EMPTY_NODES);
}
-
+
/**
* Resets all passed and failed nodes.
*/
@@ -92,8 +95,11 @@
/**
* Sets the key check for this visitor.
- * @param newKeyCheck new key check
- * @param reset whether to reset the passed and failed nodes.
+ *
+ * @param newKeyCheck
+ * new key check
+ * @param reset
+ * whether to reset the passed and failed nodes.
*/
public void setKeyCheck(IKeyCheck newKeyCheck, boolean reset) {
if (reset) {
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/NodePathRegexVisitor.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/NodePathRegexVisitor.java
index 9035243..a68c400 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/NodePathRegexVisitor.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/NodePathRegexVisitor.java
@@ -18,6 +18,7 @@
/**
* Visitor for finding keys matching the given regular expression.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public class NodePathRegexVisitor implements IKeyTreeVisitor {
@@ -25,7 +26,7 @@
/** Holder for matching keys. */
private List<IKeyTreeNode> nodes = new ArrayList<IKeyTreeNode>();
private final String regex;
-
+
/**
* Constructor.
*/
@@ -46,6 +47,7 @@
/**
* Gets matching key tree nodes.
+ *
* @return matching key tree nodes
*/
public List<IKeyTreeNode> getKeyTreeNodes() {
@@ -54,6 +56,7 @@
/**
* Gets matching key tree node paths.
+ *
* @return matching key tree node paths
*/
public List<String> getKeyTreeNodePaths() {
@@ -64,9 +67,9 @@
return paths;
}
-
/**
* Gets the first item matched.
+ *
* @return first item matched, or <code>null</code> if none was found
*/
public IKeyTreeNode getKeyTreeNode() {
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/BabelUtils.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/BabelUtils.java
index 76811a0..7c90fe3 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/BabelUtils.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/BabelUtils.java
@@ -16,15 +16,16 @@
import java.util.StringTokenizer;
/**
- * Utility methods of all kinds used across the Babel API.
+ * Utility methods of all kinds used across the Babel API.
+ *
* @author Pascal Essiembre
*/
public final class BabelUtils {
- //TODO find a better sport for these methods?
-
+ // TODO find a better sport for these methods?
+
public static final String[] EMPTY_STRINGS = new String[] {};
-
+
/**
* Constructor.
*/
@@ -34,10 +35,13 @@
/**
* Null-safe testing of two objects for equality.
- * @param o1 object 1
- * @param o2 object 2
+ *
+ * @param o1
+ * object 1
+ * @param o2
+ * object 2
* @return <code>true</code> if to objects are equal or if they are both
- * <code>null</code>.
+ * <code>null</code>.
*/
public static boolean equals(Object o1, Object o2) {
return (o1 == null && o2 == null || o1 != null && o1.equals(o2));
@@ -45,8 +49,11 @@
/**
* Joins an array by the given separator.
- * @param array the array to join
- * @param separator the joining separator
+ *
+ * @param array
+ * the array to join
+ * @param separator
+ * the joining separator
* @return joined string
*/
public static String join(Object[] array, String separator) {
@@ -63,19 +70,19 @@
return buf.toString();
}
-
/**
- * Parses a string into a locale. The string is expected to be of the
- * same format of the string obtained by calling Locale.toString().
- * @param localeString string representation of a locale
+ * Parses a string into a locale. The string is expected to be of the same
+ * format of the string obtained by calling Locale.toString().
+ *
+ * @param localeString
+ * string representation of a locale
* @return a locale or <code>null</code> if string is empty or null
*/
public static Locale parseLocale(String localeString) {
if (localeString == null || localeString.trim().length() == 0) {
return null;
}
- StringTokenizer tokens =
- new StringTokenizer(localeString, "_"); //$NON-NLS-1$
+ StringTokenizer tokens = new StringTokenizer(localeString, "_"); //$NON-NLS-1$
List<String> localeSections = new ArrayList<String>();
while (tokens.hasMoreTokens()) {
localeSections.add(tokens.nextToken());
@@ -86,14 +93,10 @@
locale = new Locale(localeSections.get(0));
break;
case 2:
- locale = new Locale(
- localeSections.get(0),
- localeSections.get(1));
+ locale = new Locale(localeSections.get(0), localeSections.get(1));
break;
case 3:
- locale = new Locale(
- localeSections.get(0),
- localeSections.get(1),
+ locale = new Locale(localeSections.get(0), localeSections.get(1),
localeSections.get(2));
break;
default:
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileChangeListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileChangeListener.java
index d645701..de30ccc 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileChangeListener.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileChangeListener.java
@@ -14,12 +14,15 @@
/**
* Listener interested in {@link File} changes.
+ *
* @author Pascal Essiembre
*/
public interface FileChangeListener {
/**
- * Invoked when a file changes.
- * @param fileName name of changed file.
+ * Invoked when a file changes.
+ *
+ * @param fileName
+ * name of changed file.
*/
public void fileChanged(File file);
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileMonitor.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileMonitor.java
index ea55982..4dbf18b 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileMonitor.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileMonitor.java
@@ -17,9 +17,9 @@
import java.util.Timer;
import java.util.TimerTask;
-
/**
* Class monitoring a {@link File} for changes.
+ *
* @author Pascal Essiembre
*/
public class FileMonitor {
@@ -27,10 +27,11 @@
private static final FileMonitor instance = new FileMonitor();
private Timer timer;
- private Hashtable<String,FileMonitorTask> timerEntries;
+ private Hashtable<String, FileMonitorTask> timerEntries;
/**
* Gets the file monitor instance.
+ *
* @return file monitor instance
*/
public static FileMonitor getInstance() {
@@ -40,69 +41,80 @@
/**
* Constructor.
*/
- private FileMonitor() {
+ private FileMonitor() {
// Create timer, run timer thread as daemon.
- timer = new Timer(true);
- timerEntries = new Hashtable<String,FileMonitorTask>();
+ timer = new Timer(true);
+ timerEntries = new Hashtable<String, FileMonitorTask>();
}
-
+
/**
* Adds a monitored file with a {@link FileChangeListener}.
- * @param listener listener to notify when the file changed.
- * @param fileName name of the file to monitor.
- * @param period polling period in milliseconds.
+ *
+ * @param listener
+ * listener to notify when the file changed.
+ * @param fileName
+ * name of the file to monitor.
+ * @param period
+ * polling period in milliseconds.
*/
- public void addFileChangeListener(
- FileChangeListener listener, String fileName, long period)
- throws FileNotFoundException {
+ public void addFileChangeListener(FileChangeListener listener,
+ String fileName, long period) throws FileNotFoundException {
addFileChangeListener(listener, new File(fileName), period);
}
/**
* Adds a monitored file with a FileChangeListener.
- * @param listener listener to notify when the file changed.
- * @param fileName name of the file to monitor.
- * @param period polling period in milliseconds.
+ *
+ * @param listener
+ * listener to notify when the file changed.
+ * @param fileName
+ * name of the file to monitor.
+ * @param period
+ * polling period in milliseconds.
*/
- public void addFileChangeListener(
- FileChangeListener listener, File file, long period)
- throws FileNotFoundException {
- removeFileChangeListener(listener, file);
- FileMonitorTask task = new FileMonitorTask(listener, file);
- timerEntries.put(file.toString() + listener.hashCode(), task);
- timer.schedule(task, period, period);
+ public void addFileChangeListener(FileChangeListener listener, File file,
+ long period) throws FileNotFoundException {
+ removeFileChangeListener(listener, file);
+ FileMonitorTask task = new FileMonitorTask(listener, file);
+ timerEntries.put(file.toString() + listener.hashCode(), task);
+ timer.schedule(task, period, period);
}
-
+
/**
* Remove the listener from the notification list.
- * @param listener the listener to be removed.
+ *
+ * @param listener
+ * the listener to be removed.
*/
- public void removeFileChangeListener(FileChangeListener listener,
- String fileName) {
+ public void removeFileChangeListener(FileChangeListener listener,
+ String fileName) {
removeFileChangeListener(listener, new File(fileName));
}
/**
* Remove the listener from the notification list.
- * @param listener the listener to be removed.
+ *
+ * @param listener
+ * the listener to be removed.
*/
- public void removeFileChangeListener(
- FileChangeListener listener, File file) {
- FileMonitorTask task = timerEntries.remove(
- file.toString() + listener.hashCode());
- if (task != null) {
- task.cancel();
- }
+ public void removeFileChangeListener(FileChangeListener listener, File file) {
+ FileMonitorTask task = timerEntries.remove(file.toString()
+ + listener.hashCode());
+ if (task != null) {
+ task.cancel();
+ }
}
/**
* Fires notification that a file changed.
- * @param listener file change listener
- * @param file the file that changed
+ *
+ * @param listener
+ * file change listener
+ * @param file
+ * the file that changed
*/
- protected void fireFileChangeEvent(
- FileChangeListener listener, File file) {
- listener.fileChanged(file);
+ protected void fireFileChangeEvent(FileChangeListener listener, File file) {
+ listener.fileChanged(file);
}
/**
@@ -113,30 +125,29 @@
File monitoredFile;
long lastModified;
- public FileMonitorTask(FileChangeListener listener, File file)
- throws FileNotFoundException {
- this.listener = listener;
- this.lastModified = 0;
- monitoredFile = file;
- if (!monitoredFile.exists()) { // but is it on CLASSPATH?
- URL fileURL =
- listener.getClass().getClassLoader().getResource(
- file.toString());
- if (fileURL != null) {
- monitoredFile = new File(fileURL.getFile());
- } else {
- throw new FileNotFoundException("File Not Found: " + file);
- }
- }
- this.lastModified = monitoredFile.lastModified();
- }
-
+ public FileMonitorTask(FileChangeListener listener, File file)
+ throws FileNotFoundException {
+ this.listener = listener;
+ this.lastModified = 0;
+ monitoredFile = file;
+ if (!monitoredFile.exists()) { // but is it on CLASSPATH?
+ URL fileURL = listener.getClass().getClassLoader()
+ .getResource(file.toString());
+ if (fileURL != null) {
+ monitoredFile = new File(fileURL.getFile());
+ } else {
+ throw new FileNotFoundException("File Not Found: " + file);
+ }
+ }
+ this.lastModified = monitoredFile.lastModified();
+ }
+
public void run() {
- long lastModified = monitoredFile.lastModified();
- if (lastModified != this.lastModified) {
- this.lastModified = lastModified;
- fireFileChangeEvent(this.listener, monitoredFile);
- }
- }
+ long lastModified = monitoredFile.lastModified();
+ if (lastModified != this.lastModified) {
+ this.lastModified = lastModified;
+ fireFileChangeEvent(this.listener, monitoredFile);
+ }
+ }
}
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileUtils.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileUtils.java
index e70a4ab..6dd8468 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileUtils.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileUtils.java
@@ -28,47 +28,48 @@
* @author Alexej Strelzow
*/
public class FileUtils {
-
- public static void writeToFile(IMessagesBundle bundle) {
- DirtyHack.setEditorModificationEnabled(false);
- PropertiesSerializer ps = new PropertiesSerializer(ConfigurationManager
- .getInstance().getSerializerConfig());
- String editorContent = ps.serialize(bundle);
- IFile file = getFile(bundle);
- try {
- file.refreshLocal(IResource.DEPTH_ZERO, null);
- file.setContents(
- new ByteArrayInputStream(editorContent.getBytes()), false,
- true, null);
- file.refreshLocal(IResource.DEPTH_ZERO, null);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- DirtyHack.setEditorModificationEnabled(true);
- }
- }
-
- public static IFile getFile(IMessagesBundle bundle) {
- if (bundle.getResource() instanceof PropertiesFileResource) { // different
- // ResourceLocationLabel
- String path = bundle.getResource().getResourceLocationLabel(); // P:\Workspace\AST\TEST\src\messages\Messages_de.properties
- int index = path.indexOf("src");
- String pathBeforeSrc = path.substring(0, index - 1);
- int lastIndexOf = pathBeforeSrc.lastIndexOf(File.separatorChar);
- String projectName = path.substring(lastIndexOf + 1, index - 1);
- String relativeFilePath = path.substring(index, path.length());
+ public static void writeToFile(IMessagesBundle bundle) {
+ DirtyHack.setEditorModificationEnabled(false);
- return ResourcesPlugin.getWorkspace().getRoot()
- .getProject(projectName).getFile(relativeFilePath);
- } else {
- String location = bundle.getResource().getResourceLocationLabel(); // /TEST/src/messages/Messages_en_IN.properties
- String projectName = location.substring(1, location.indexOf("/", 1));
- location = location.substring(projectName.length() + 1,
- location.length());
- return ResourcesPlugin.getWorkspace().getRoot()
- .getProject(projectName).getFile(location);
- }
- }
-
+ PropertiesSerializer ps = new PropertiesSerializer(ConfigurationManager
+ .getInstance().getSerializerConfig());
+ String editorContent = ps.serialize(bundle);
+ IFile file = getFile(bundle);
+ try {
+ file.refreshLocal(IResource.DEPTH_ZERO, null);
+ file.setContents(
+ new ByteArrayInputStream(editorContent.getBytes()), false,
+ true, null);
+ file.refreshLocal(IResource.DEPTH_ZERO, null);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ DirtyHack.setEditorModificationEnabled(true);
+ }
+ }
+
+ public static IFile getFile(IMessagesBundle bundle) {
+ if (bundle.getResource() instanceof PropertiesFileResource) { // different
+ // ResourceLocationLabel
+ String path = bundle.getResource().getResourceLocationLabel(); // P:\Workspace\AST\TEST\src\messages\Messages_de.properties
+ int index = path.indexOf("src");
+ String pathBeforeSrc = path.substring(0, index - 1);
+ int lastIndexOf = pathBeforeSrc.lastIndexOf(File.separatorChar);
+ String projectName = path.substring(lastIndexOf + 1, index - 1);
+ String relativeFilePath = path.substring(index, path.length());
+
+ return ResourcesPlugin.getWorkspace().getRoot()
+ .getProject(projectName).getFile(relativeFilePath);
+ } else {
+ String location = bundle.getResource().getResourceLocationLabel(); // /TEST/src/messages/Messages_en_IN.properties
+ String projectName = location
+ .substring(1, location.indexOf("/", 1));
+ location = location.substring(projectName.length() + 1,
+ location.length());
+ return ResourcesPlugin.getWorkspace().getRoot()
+ .getProject(projectName).getFile(location);
+ }
+ }
+
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/NameUtils.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/NameUtils.java
index e277f54..b1beb90 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/NameUtils.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/NameUtils.java
@@ -24,63 +24,63 @@
*/
public class NameUtils {
-
- public static String getResourceBundleId(IResource resource) {
- String packageFragment = "";
+ public static String getResourceBundleId(IResource resource) {
+ String packageFragment = "";
- IJavaElement propertyFile = JavaCore.create(resource.getParent());
- if (propertyFile != null && propertyFile instanceof IPackageFragment)
- packageFragment = ((IPackageFragment) propertyFile)
- .getElementName();
+ IJavaElement propertyFile = JavaCore.create(resource.getParent());
+ if (propertyFile != null && propertyFile instanceof IPackageFragment)
+ packageFragment = ((IPackageFragment) propertyFile)
+ .getElementName();
- return (packageFragment.length() > 0 ? packageFragment + "." : "")
- + getResourceBundleName(resource);
- }
+ return (packageFragment.length() > 0 ? packageFragment + "." : "")
+ + getResourceBundleName(resource);
+ }
- public static String getResourceBundleName(IResource res) {
- String name = res.getName();
- String regex = "^(.*?)" //$NON-NLS-1$
- + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
- + res.getFileExtension() + ")$"; //$NON-NLS-1$
- return name.replaceFirst(regex, "$1"); //$NON-NLS-1$
- }
-
- public static Locale getLocaleByName(String bundleName, String localeID) {
- String theBundleName = bundleName;
- if (theBundleName.contains(".")) {
- // we entered this method with the rbID and not the name!
- theBundleName = theBundleName.substring(theBundleName.indexOf(".") + 1);
- }
-
- // Check locale
- Locale locale = null;
- localeID = localeID.substring(0,
- localeID.length() - "properties".length() - 1);
- if (localeID.length() == theBundleName.length()) {
- // default locale
- return null;
- } else {
- localeID = localeID.substring(theBundleName.length() + 1);
- String[] localeTokens = localeID.split("_");
+ public static String getResourceBundleName(IResource res) {
+ String name = res.getName();
+ String regex = "^(.*?)" //$NON-NLS-1$
+ + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
+ + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
+ + res.getFileExtension() + ")$"; //$NON-NLS-1$
+ return name.replaceFirst(regex, "$1"); //$NON-NLS-1$
+ }
- switch (localeTokens.length) {
- case 1:
- locale = new Locale(localeTokens[0]);
- break;
- case 2:
- locale = new Locale(localeTokens[0], localeTokens[1]);
- break;
- case 3:
- locale = new Locale(localeTokens[0], localeTokens[1],
- localeTokens[2]);
- break;
- default:
- locale = null;
- break;
- }
- }
+ public static Locale getLocaleByName(String bundleName, String localeID) {
+ String theBundleName = bundleName;
+ if (theBundleName.contains(".")) {
+ // we entered this method with the rbID and not the name!
+ theBundleName = theBundleName
+ .substring(theBundleName.indexOf(".") + 1);
+ }
- return locale;
- }
+ // Check locale
+ Locale locale = null;
+ localeID = localeID.substring(0,
+ localeID.length() - "properties".length() - 1);
+ if (localeID.length() == theBundleName.length()) {
+ // default locale
+ return null;
+ } else {
+ localeID = localeID.substring(theBundleName.length() + 1);
+ String[] localeTokens = localeID.split("_");
+
+ switch (localeTokens.length) {
+ case 1:
+ locale = new Locale(localeTokens[0]);
+ break;
+ case 2:
+ locale = new Locale(localeTokens[0], localeTokens[1]);
+ break;
+ case 3:
+ locale = new Locale(localeTokens[0], localeTokens[1],
+ localeTokens[2]);
+ break;
+ default:
+ locale = null;
+ break;
+ }
+ }
+
+ return locale;
+ }
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java
index 40eeb48..7114b39 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java
@@ -27,219 +27,239 @@
public class PDEUtils {
- // The same as PDE.PLUGIN_NATURE, because the PDE provided constant is not accessible (internal class)
- private static final String PLUGIN_NATURE = "org.eclipse.pde.PluginNature";
+ // The same as PDE.PLUGIN_NATURE, because the PDE provided constant is not
+ // accessible (internal class)
+ private static final String PLUGIN_NATURE = "org.eclipse.pde.PluginNature";
- /**
- * Get the project's plug-in Id if the given project is an eclipse plug-in.
- *
- * @param project the workspace project.
- * @return the project's plug-in Id. Null if the project is no plug-in project.
- */
- public static String getPluginId(IProject project) {
+ /**
+ * Get the project's plug-in Id if the given project is an eclipse plug-in.
+ *
+ * @param project
+ * the workspace project.
+ * @return the project's plug-in Id. Null if the project is no plug-in
+ * project.
+ */
+ public static String getPluginId(IProject project) {
- if (project == null || !isPluginProject(project)) {
- return null;
- }
+ if (project == null || !isPluginProject(project)) {
+ return null;
+ }
- IPluginModelBase pluginModelBase = PluginRegistry.findModel(project);
-
- if (pluginModelBase == null) {
- // plugin not found in registry
- return null;
- }
-
- IPluginBase pluginBase = pluginModelBase.getPluginBase();
+ IPluginModelBase pluginModelBase = PluginRegistry.findModel(project);
- return pluginBase.getId();
- }
+ if (pluginModelBase == null) {
+ // plugin not found in registry
+ return null;
+ }
- /**
- * Returns all project containing plugin/fragment of the specified project.
- * If the specified project itself is a fragment, then only this is
- * returned.
- *
- * @param pluginProject
- * the plugin project
- * @return the all project containing a fragment or null if none
- */
- public static IProject[] lookupFragment(IProject pluginProject) {
- if (isFragment(pluginProject) && pluginProject.isOpen()) {
- return new IProject[] {pluginProject};
- }
-
- IProject[] workspaceProjects = pluginProject.getWorkspace().getRoot().getProjects();
- String hostPluginId = getPluginId(pluginProject);
-
- if (hostPluginId == null) {
- // project is not a plugin project
- return null;
- }
-
- List<IProject> fragmentProjects = new ArrayList<IProject>();
- for (IProject project : workspaceProjects) {
- if (!project.isOpen() || getFragmentId(project, hostPluginId) == null) {
- // project is not open or it is no fragment where given project is the host project.
- continue;
- }
- fragmentProjects.add(project);
- }
+ IPluginBase pluginBase = pluginModelBase.getPluginBase();
- if (fragmentProjects.isEmpty()) {
- return null;
- }
-
- return fragmentProjects.toArray(new IProject[0]);
- }
+ return pluginBase.getId();
+ }
- /**
- * Check if the given plug-in project is a fragment.
- *
- * @param pluginProject the plug-in project in the workspace.
- * @return true if it is a fragment, otherwise false.
- */
- public static boolean isFragment(IProject pluginProject) {
- if (pluginProject == null) {
- return false;
- }
-
- IPluginModelBase pModel = PluginRegistry.findModel(pluginProject);
-
- if (pModel == null) {
- // this project is not a plugin/fragment
- return false;
- }
-
- return pModel.isFragmentModel();
- }
+ /**
+ * Returns all project containing plugin/fragment of the specified project.
+ * If the specified project itself is a fragment, then only this is
+ * returned.
+ *
+ * @param pluginProject
+ * the plugin project
+ * @return the all project containing a fragment or null if none
+ */
+ public static IProject[] lookupFragment(IProject pluginProject) {
+ if (isFragment(pluginProject) && pluginProject.isOpen()) {
+ return new IProject[] { pluginProject };
+ }
- /**
- * Get all fragments for the given host project.
- *
- * @param hostProject the host plug-in project in the workspace.
- * @return a list of all fragment projects for the given host project which are in the same workspace as the host project.
- */
- public static List<IProject> getFragments(IProject hostProject) {
- // Check preconditions
- String hostId = getPluginId(hostProject);
- if (hostProject == null || hostId == null) {
- // no valid host project given.
- return Collections.emptyList();
- }
+ IProject[] workspaceProjects = pluginProject.getWorkspace().getRoot()
+ .getProjects();
+ String hostPluginId = getPluginId(pluginProject);
- // Get the fragments of the host project
- IPluginModelBase pModelBase = PluginRegistry.findModel(hostProject);
- BundleDescription desc = pModelBase.getBundleDescription();
+ if (hostPluginId == null) {
+ // project is not a plugin project
+ return null;
+ }
- ArrayList<IPluginModelBase> fragmentModels = new ArrayList<IPluginModelBase>();
- if (desc == null) {
- // There is no bundle description for the host project
- return Collections.emptyList();
- }
-
- BundleDescription[] f = desc.getFragments();
- for (BundleDescription candidateDesc : f) {
- IPluginModelBase candidate = PluginRegistry.findModel(candidateDesc);
- if (candidate instanceof IFragmentModel) {
- fragmentModels.add(candidate);
- }
- }
-
- // Get the fragment project which is in the current workspace
- ArrayList<IProject> fragments = getFragmentsAsWorkspaceProjects(hostProject, fragmentModels);
-
- return fragments;
- }
+ List<IProject> fragmentProjects = new ArrayList<IProject>();
+ for (IProject project : workspaceProjects) {
+ if (!project.isOpen()
+ || getFragmentId(project, hostPluginId) == null) {
+ // project is not open or it is no fragment where given project
+ // is the host project.
+ continue;
+ }
+ fragmentProjects.add(project);
+ }
- /**
- * Returns the fragment-id of the project if it is a fragment project with
- * the specified host plugin id as host. Else null is returned.
- *
- * @param project
- * the project
- * @param hostPluginId
- * the host plugin id
- * @return the plugin-id or null
- */
- public static String getFragmentId(IProject project, String hostPluginId) {
- if (!isFragment(project) || hostPluginId == null) {
- return null;
- }
-
- IPluginModelBase pluginModelBase = PluginRegistry.findModel(project);
- if (pluginModelBase instanceof IFragmentModel) {
- IFragmentModel fragmentModel = (IFragmentModel) pluginModelBase;
- BundleDescription description = fragmentModel.getBundleDescription();
- HostSpecification hostSpecification = description.getHost();
+ if (fragmentProjects.isEmpty()) {
+ return null;
+ }
- if (hostPluginId.equals(hostSpecification.getName())) {
- return getPluginId(project);
- }
- }
- return null;
- }
+ return fragmentProjects.toArray(new IProject[0]);
+ }
- /**
- * Returns the host plugin project of the specified project if it contains a
- * fragment.
- *
- * @param fragment
- * the fragment project
- * @return the host plugin project or null
- */
- public static IProject getFragmentHost(IProject fragment) {
- if (!isFragment(fragment)) {
- return null;
- }
-
- IPluginModelBase pluginModelBase = PluginRegistry.findModel(fragment);
- if (pluginModelBase instanceof IFragmentModel) {
- IFragmentModel fragmentModel = (IFragmentModel) pluginModelBase;
- BundleDescription description = fragmentModel.getBundleDescription();
- HostSpecification hostSpecification = description.getHost();
-
- IPluginModelBase hostProject = PluginRegistry.findModel(hostSpecification.getName());
- IProject[] projects = fragment.getWorkspace().getRoot().getProjects();
- ArrayList<IProject> hostProjects = getPluginProjects(Arrays.asList(hostProject), projects);
-
- if (hostProjects.size() != 1) {
- // hostproject not in workspace
- return null;
- } else {
- return hostProjects.get(0);
- }
- }
-
- return null;
- }
+ /**
+ * Check if the given plug-in project is a fragment.
+ *
+ * @param pluginProject
+ * the plug-in project in the workspace.
+ * @return true if it is a fragment, otherwise false.
+ */
+ public static boolean isFragment(IProject pluginProject) {
+ if (pluginProject == null) {
+ return false;
+ }
- private static ArrayList<IProject> getFragmentsAsWorkspaceProjects(IProject hostProject, ArrayList<IPluginModelBase> fragmentModels) {
- IProject[] projects = hostProject.getWorkspace().getRoot().getProjects();
-
- ArrayList<IProject> fragments = getPluginProjects(fragmentModels, projects);
-
- return fragments;
- }
+ IPluginModelBase pModel = PluginRegistry.findModel(pluginProject);
- private static ArrayList<IProject> getPluginProjects(List<IPluginModelBase> fragmentModels, IProject[] projects) {
- ArrayList<IProject> fragments = new ArrayList<IProject>();
- for (IProject project : projects) {
- IPluginModelBase pModel = PluginRegistry.findModel(project);
-
- if (fragmentModels.contains(pModel)) {
- fragments.add(project);
- }
- }
-
- return fragments;
- }
-
- private static boolean isPluginProject(IProject project) {
- try {
- return project.hasNature(PLUGIN_NATURE);
- } catch (CoreException ce) {
- //Logger.logError(ce);
- }
- return false;
- }
+ if (pModel == null) {
+ // this project is not a plugin/fragment
+ return false;
+ }
+
+ return pModel.isFragmentModel();
+ }
+
+ /**
+ * Get all fragments for the given host project.
+ *
+ * @param hostProject
+ * the host plug-in project in the workspace.
+ * @return a list of all fragment projects for the given host project which
+ * are in the same workspace as the host project.
+ */
+ public static List<IProject> getFragments(IProject hostProject) {
+ // Check preconditions
+ String hostId = getPluginId(hostProject);
+ if (hostProject == null || hostId == null) {
+ // no valid host project given.
+ return Collections.emptyList();
+ }
+
+ // Get the fragments of the host project
+ IPluginModelBase pModelBase = PluginRegistry.findModel(hostProject);
+ BundleDescription desc = pModelBase.getBundleDescription();
+
+ ArrayList<IPluginModelBase> fragmentModels = new ArrayList<IPluginModelBase>();
+ if (desc == null) {
+ // There is no bundle description for the host project
+ return Collections.emptyList();
+ }
+
+ BundleDescription[] f = desc.getFragments();
+ for (BundleDescription candidateDesc : f) {
+ IPluginModelBase candidate = PluginRegistry
+ .findModel(candidateDesc);
+ if (candidate instanceof IFragmentModel) {
+ fragmentModels.add(candidate);
+ }
+ }
+
+ // Get the fragment project which is in the current workspace
+ ArrayList<IProject> fragments = getFragmentsAsWorkspaceProjects(
+ hostProject, fragmentModels);
+
+ return fragments;
+ }
+
+ /**
+ * Returns the fragment-id of the project if it is a fragment project with
+ * the specified host plugin id as host. Else null is returned.
+ *
+ * @param project
+ * the project
+ * @param hostPluginId
+ * the host plugin id
+ * @return the plugin-id or null
+ */
+ public static String getFragmentId(IProject project, String hostPluginId) {
+ if (!isFragment(project) || hostPluginId == null) {
+ return null;
+ }
+
+ IPluginModelBase pluginModelBase = PluginRegistry.findModel(project);
+ if (pluginModelBase instanceof IFragmentModel) {
+ IFragmentModel fragmentModel = (IFragmentModel) pluginModelBase;
+ BundleDescription description = fragmentModel
+ .getBundleDescription();
+ HostSpecification hostSpecification = description.getHost();
+
+ if (hostPluginId.equals(hostSpecification.getName())) {
+ return getPluginId(project);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns the host plugin project of the specified project if it contains a
+ * fragment.
+ *
+ * @param fragment
+ * the fragment project
+ * @return the host plugin project or null
+ */
+ public static IProject getFragmentHost(IProject fragment) {
+ if (!isFragment(fragment)) {
+ return null;
+ }
+
+ IPluginModelBase pluginModelBase = PluginRegistry.findModel(fragment);
+ if (pluginModelBase instanceof IFragmentModel) {
+ IFragmentModel fragmentModel = (IFragmentModel) pluginModelBase;
+ BundleDescription description = fragmentModel
+ .getBundleDescription();
+ HostSpecification hostSpecification = description.getHost();
+
+ IPluginModelBase hostProject = PluginRegistry
+ .findModel(hostSpecification.getName());
+ IProject[] projects = fragment.getWorkspace().getRoot()
+ .getProjects();
+ ArrayList<IProject> hostProjects = getPluginProjects(
+ Arrays.asList(hostProject), projects);
+
+ if (hostProjects.size() != 1) {
+ // hostproject not in workspace
+ return null;
+ } else {
+ return hostProjects.get(0);
+ }
+ }
+
+ return null;
+ }
+
+ private static ArrayList<IProject> getFragmentsAsWorkspaceProjects(
+ IProject hostProject, ArrayList<IPluginModelBase> fragmentModels) {
+ IProject[] projects = hostProject.getWorkspace().getRoot()
+ .getProjects();
+
+ ArrayList<IProject> fragments = getPluginProjects(fragmentModels,
+ projects);
+
+ return fragments;
+ }
+
+ private static ArrayList<IProject> getPluginProjects(
+ List<IPluginModelBase> fragmentModels, IProject[] projects) {
+ ArrayList<IProject> fragments = new ArrayList<IProject>();
+ for (IProject project : projects) {
+ IPluginModelBase pModel = PluginRegistry.findModel(project);
+
+ if (fragmentModels.contains(pModel)) {
+ fragments.add(project);
+ }
+ }
+
+ return fragments;
+ }
+
+ private static boolean isPluginProject(IProject project) {
+ try {
+ return project.hasNature(PLUGIN_NATURE);
+ } catch (CoreException ce) {
+ // Logger.logError(ce);
+ }
+ return false;
+ }
}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditor.java
index 8774bc5..2286d30 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditor.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditor.java
@@ -11,7 +11,7 @@
package org.eclipse.babel.editor;
public interface IMessagesEditor {
- String getSelectedKey();
+ String getSelectedKey();
- void setSelectedKey(String key);
+ void setSelectedKey(String key);
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditorChangeListener.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditorChangeListener.java
index d41a0f3..81e8b1f 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditorChangeListener.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditorChangeListener.java
@@ -12,11 +12,9 @@
import org.eclipse.babel.core.message.tree.internal.AbstractKeyTreeModel;
-
-
/**
* @author Pascal Essiembre
- *
+ *
*/
public interface IMessagesEditorChangeListener {
@@ -24,14 +22,15 @@
public static int SHOW_ONLY_MISSING_AND_UNUSED = 1;
public static int SHOW_ONLY_MISSING = 2;
public static int SHOW_ONLY_UNUSED = 3;
-
+
void keyTreeVisibleChanged(boolean visible);
-
+
void showOnlyUnusedAndMissingChanged(int showFlag);
-
+
void selectedKeyChanged(String oldKey, String newKey);
-
- void keyTreeModelChanged(AbstractKeyTreeModel oldModel, AbstractKeyTreeModel newModel);
-
+
+ void keyTreeModelChanged(AbstractKeyTreeModel oldModel,
+ AbstractKeyTreeModel newModel);
+
void editorDisposed();
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/FilterKeysAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/FilterKeysAction.java
index 2125e32..1d1fc41 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/FilterKeysAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/FilterKeysAction.java
@@ -27,10 +27,12 @@
public class FilterKeysAction extends Action {
private MessagesEditor editor;
- private final int flagToSet;
- private ChangeListener listener;
+ private final int flagToSet;
+ private ChangeListener listener;
+
/**
- * @param flagToSet The flag that will be set on unset
+ * @param flagToSet
+ * The flag that will be set on unset
*/
public FilterKeysAction(int flagToSet) {
super("", IAction.AS_CHECK_BOX);
@@ -38,120 +40,121 @@
listener = new ChangeListener();
update();
}
-
+
private class ChangeListener extends MessagesEditorChangeAdapter {
public void showOnlyUnusedAndMissingChanged(int hideEverythingElse) {
- MessagesEditorContributor.FILTERS.updateActionBars();
+ MessagesEditorContributor.FILTERS.updateActionBars();
}
}
-
-
- /* (non-Javadoc)
+
+ /*
+ * (non-Javadoc)
+ *
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
- if (editor != null) {
- if (editor.isShowOnlyUnusedAndMissingKeys() != flagToSet) {
- editor.setShowOnlyUnusedMissingKeys(flagToSet);
- //listener.showOnlyUnusedAndMissingChanged(flagToSet)
- } else {
- editor.setShowOnlyUnusedMissingKeys(IMessagesEditorChangeListener.SHOW_ALL);
- //listener.showOnlyUnusedAndMissingChanged(IMessagesEditorChangeListener.SHOW_ALL)
- }
- }
+ if (editor != null) {
+ if (editor.isShowOnlyUnusedAndMissingKeys() != flagToSet) {
+ editor.setShowOnlyUnusedMissingKeys(flagToSet);
+ // listener.showOnlyUnusedAndMissingChanged(flagToSet)
+ } else {
+ editor.setShowOnlyUnusedMissingKeys(IMessagesEditorChangeListener.SHOW_ALL);
+ // listener.showOnlyUnusedAndMissingChanged(IMessagesEditorChangeListener.SHOW_ALL)
+ }
+ }
}
-
- public void update() {
- if (editor == null) {
- super.setEnabled(false);
- } else {
- super.setEnabled(true);
- }
- if (editor != null && editor.isShowOnlyUnusedAndMissingKeys() == flagToSet) {
- setChecked(true);
- } else {
- setChecked(false);
- }
- setText(getTextInternal());
- setToolTipText(getTooltipInternal());
+ public void update() {
+ if (editor == null) {
+ super.setEnabled(false);
+ } else {
+ super.setEnabled(true);
+ }
+
+ if (editor != null
+ && editor.isShowOnlyUnusedAndMissingKeys() == flagToSet) {
+ setChecked(true);
+ } else {
+ setChecked(false);
+ }
+ setText(getTextInternal());
+ setToolTipText(getTooltipInternal());
setImageDescriptor(ImageDescriptor.createFromImage(getImage()));
}
-
+
public Image getImage() {
- switch (flagToSet) {
- case IMessagesEditorChangeListener.SHOW_ONLY_MISSING:
- //return UIUtils.IMAGE_MISSING_TRANSLATION;
- return UIUtils.getMissingTranslationImage();
- case IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED:
- //return UIUtils.IMAGE_UNUSED_AND_MISSING_TRANSLATIONS;
- return UIUtils.getMissingAndUnusedTranslationsImage();
- case IMessagesEditorChangeListener.SHOW_ONLY_UNUSED:
- //return UIUtils.IMAGE_UNUSED_TRANSLATION;
- return UIUtils.getUnusedTranslationsImage();
- case IMessagesEditorChangeListener.SHOW_ALL:
- default:
- return UIUtils.getImage(UIUtils.IMAGE_KEY);
- }
+ switch (flagToSet) {
+ case IMessagesEditorChangeListener.SHOW_ONLY_MISSING:
+ // return UIUtils.IMAGE_MISSING_TRANSLATION;
+ return UIUtils.getMissingTranslationImage();
+ case IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED:
+ // return UIUtils.IMAGE_UNUSED_AND_MISSING_TRANSLATIONS;
+ return UIUtils.getMissingAndUnusedTranslationsImage();
+ case IMessagesEditorChangeListener.SHOW_ONLY_UNUSED:
+ // return UIUtils.IMAGE_UNUSED_TRANSLATION;
+ return UIUtils.getUnusedTranslationsImage();
+ case IMessagesEditorChangeListener.SHOW_ALL:
+ default:
+ return UIUtils.getImage(UIUtils.IMAGE_KEY);
+ }
}
- /*public String getImageKey() {
- switch (flagToSet) {
- case IMessagesEditorChangeListener.SHOW_ONLY_MISSING:
- return UIUtils.IMAGE_MISSING_TRANSLATION;
- case IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED:
- return UIUtils.IMAGE_UNUSED_AND_MISSING_TRANSLATIONS;
- case IMessagesEditorChangeListener.SHOW_ONLY_UNUSED:
- return UIUtils.IMAGE_UNUSED_TRANSLATION;
- case IMessagesEditorChangeListener.SHOW_ALL:
- default:
- return UIUtils.IMAGE_KEY;
- }
- }*/
-
+
+ /*
+ * public String getImageKey() { switch (flagToSet) { case
+ * IMessagesEditorChangeListener.SHOW_ONLY_MISSING: return
+ * UIUtils.IMAGE_MISSING_TRANSLATION; case
+ * IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED: return
+ * UIUtils.IMAGE_UNUSED_AND_MISSING_TRANSLATIONS; case
+ * IMessagesEditorChangeListener.SHOW_ONLY_UNUSED: return
+ * UIUtils.IMAGE_UNUSED_TRANSLATION; case
+ * IMessagesEditorChangeListener.SHOW_ALL: default: return
+ * UIUtils.IMAGE_KEY; } }
+ */
+
public String getTextInternal() {
- switch (flagToSet) {
- case IMessagesEditorChangeListener.SHOW_ONLY_MISSING:
- return "Show only missing translations";
- case IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED:
- return "Show only missing or unused translations";
- case IMessagesEditorChangeListener.SHOW_ONLY_UNUSED:
- return "Show only unused translations";
- case IMessagesEditorChangeListener.SHOW_ALL:
- default:
- return "Show all";
- }
+ switch (flagToSet) {
+ case IMessagesEditorChangeListener.SHOW_ONLY_MISSING:
+ return "Show only missing translations";
+ case IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED:
+ return "Show only missing or unused translations";
+ case IMessagesEditorChangeListener.SHOW_ONLY_UNUSED:
+ return "Show only unused translations";
+ case IMessagesEditorChangeListener.SHOW_ALL:
+ default:
+ return "Show all";
+ }
}
-
+
private String getTooltipInternal() {
- return getTextInternal();
-// if (editor == null) {
-// return "no active editor";
-// }
-// switch (editor.isShowOnlyUnusedAndMissingKeys()) {
-// case IMessagesEditorChangeListener.SHOW_ONLY_MISSING:
-// return "Showing only keys with missing translation";
-// case IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED:
-// return "Showing only keys with missing or unused translation";
-// case IMessagesEditorChangeListener.SHOW_ONLY_UNUSED:
-// return "Showing only keys with missing translation";
-// case IMessagesEditorChangeListener.SHOW_ALL:
-// default:
-// return "Showing all keys";
-// }
+ return getTextInternal();
+ // if (editor == null) {
+ // return "no active editor";
+ // }
+ // switch (editor.isShowOnlyUnusedAndMissingKeys()) {
+ // case IMessagesEditorChangeListener.SHOW_ONLY_MISSING:
+ // return "Showing only keys with missing translation";
+ // case IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED:
+ // return "Showing only keys with missing or unused translation";
+ // case IMessagesEditorChangeListener.SHOW_ONLY_UNUSED:
+ // return "Showing only keys with missing translation";
+ // case IMessagesEditorChangeListener.SHOW_ALL:
+ // default:
+ // return "Showing all keys";
+ // }
}
-
+
public void setEditor(MessagesEditor editor) {
- if (editor == this.editor) {
- return;//no change
- }
+ if (editor == this.editor) {
+ return;// no change
+ }
if (this.editor != null) {
- this.editor.removeChangeListener(listener);
+ this.editor.removeChangeListener(listener);
}
this.editor = editor;
update();
if (editor != null) {
- editor.addChangeListener(listener);
+ editor.addChangeListener(listener);
}
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/KeyTreeVisibleAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/KeyTreeVisibleAction.java
index 8853a80..ed8eff7 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/KeyTreeVisibleAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/KeyTreeVisibleAction.java
@@ -18,23 +18,24 @@
/**
* @author Pascal Essiembre
- *
+ *
*/
public class KeyTreeVisibleAction extends Action {
private MessagesEditor editor;
-
+
/**
*
*/
public KeyTreeVisibleAction() {
super("Show/Hide Key Tree", IAction.AS_CHECK_BOX);
-// setText();
+ // setText();
setToolTipText("Show/hide the key tree");
setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_VIEW_LEFT));
}
- //TODO RBEditor hold such an action registry. Then move this method to constructor
+ // TODO RBEditor hold such an action registry. Then move this method to
+ // constructor
public void setEditor(MessagesEditor editor) {
this.editor = editor;
editor.addChangeListener(new MessagesEditorChangeAdapter() {
@@ -45,13 +46,14 @@
setChecked(editor.getI18NPage().isKeyTreeVisible());
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
editor.getI18NPage().setKeyTreeVisible(
!editor.getI18NPage().isKeyTreeVisible());
}
-
-
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/NewLocaleAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/NewLocaleAction.java
index a935550..bc4ff39 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/NewLocaleAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/NewLocaleAction.java
@@ -25,75 +25,79 @@
/**
* @author Pascal Essiembre
- *
+ *
*/
public class NewLocaleAction extends Action {
private MessagesEditor editor;
-
+
/**
*
*/
public NewLocaleAction() {
super("New &Locale...");
setToolTipText("Add a new locale to the resource bundle.");
- setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_NEW_PROPERTIES_FILE));
+ setImageDescriptor(UIUtils
+ .getImageDescriptor(UIUtils.IMAGE_NEW_PROPERTIES_FILE));
}
- //TODO RBEditor hold such an action registry. Then move this method to constructor
+ // TODO RBEditor hold such an action registry. Then move this method to
+ // constructor
public void setEditor(MessagesEditor editor) {
this.editor = editor;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
- // created choose locale dialog
- Dialog localeDialog = new Dialog(editor.getSite().getShell()) {
- LocaleSelector selector;
-
- @Override
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Add new local");
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite comp = (Composite) super.createDialogArea(parent);
- selector = new LocaleSelector(comp);
- return comp;
- }
-
- @Override
- protected void okPressed() {
- // add local to bundleGroup
- MessagesBundleGroup bundleGroup = editor.getBundleGroup();
- Locale newLocal = selector.getSelectedLocale();
-
- // exists local already?
- boolean existsLocal = false;
- Locale[] locales = bundleGroup.getLocales();
- for (Locale locale : locales) {
- if (locale == null) {
- if (newLocal == null) {
- existsLocal = true;
- break;
- }
- } else if (locale.equals(newLocal)) {
- existsLocal = true;
- break;
- }
- }
-
- if (! existsLocal)
- bundleGroup.addMessagesBundle(newLocal);
-
- super.okPressed();
- }
- };
- // open dialog
- localeDialog.open();
+ // created choose locale dialog
+ Dialog localeDialog = new Dialog(editor.getSite().getShell()) {
+ LocaleSelector selector;
+
+ @Override
+ protected void configureShell(Shell newShell) {
+ super.configureShell(newShell);
+ newShell.setText("Add new local");
+ }
+
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite comp = (Composite) super.createDialogArea(parent);
+ selector = new LocaleSelector(comp);
+ return comp;
+ }
+
+ @Override
+ protected void okPressed() {
+ // add local to bundleGroup
+ MessagesBundleGroup bundleGroup = editor.getBundleGroup();
+ Locale newLocal = selector.getSelectedLocale();
+
+ // exists local already?
+ boolean existsLocal = false;
+ Locale[] locales = bundleGroup.getLocales();
+ for (Locale locale : locales) {
+ if (locale == null) {
+ if (newLocal == null) {
+ existsLocal = true;
+ break;
+ }
+ } else if (locale.equals(newLocal)) {
+ existsLocal = true;
+ break;
+ }
+ }
+
+ if (!existsLocal)
+ bundleGroup.addMessagesBundle(newLocal);
+
+ super.okPressed();
+ }
+ };
+ // open dialog
+ localeDialog.open();
}
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/AnalyzerFactory.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/AnalyzerFactory.java
index 8804d6d..0650f55 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/AnalyzerFactory.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/AnalyzerFactory.java
@@ -14,17 +14,17 @@
import org.eclipse.babel.core.message.checks.proximity.LevenshteinDistanceAnalyzer;
/**
- * Provides the {@link IProximityAnalyzer}
- * <br><br>
+ * Provides the {@link IProximityAnalyzer} <br>
+ * <br>
*
* @author Alexej Strelzow
*/
public class AnalyzerFactory {
- /**
- * @return An instance of the {@link LevenshteinDistanceAnalyzer}
- */
- public static IProximityAnalyzer getLevenshteinDistanceAnalyzer () {
- return (IProximityAnalyzer) LevenshteinDistanceAnalyzer.getInstance();
- }
+ /**
+ * @return An instance of the {@link LevenshteinDistanceAnalyzer}
+ */
+ public static IProximityAnalyzer getLevenshteinDistanceAnalyzer() {
+ return (IProximityAnalyzer) LevenshteinDistanceAnalyzer.getInstance();
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/EditorUtil.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/EditorUtil.java
index b00f4b2..88ed83f 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/EditorUtil.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/EditorUtil.java
@@ -8,24 +8,27 @@
import org.eclipse.ui.IWorkbenchPage;
/**
- * Util class for editor operations.
- * <br><br>
+ * Util class for editor operations. <br>
+ * <br>
*
* @author Alexej Strelzow
*/
public class EditorUtil {
-
- /**
- * @param page The {@link IWorkbenchPage}
- * @return The selected {@link IKeyTreeNode} of the page.
- */
- public static IKeyTreeNode getSelectedKeyTreeNode (IWorkbenchPage page) {
- MessagesEditor editor = (MessagesEditor)page.getActiveEditor();
+
+ /**
+ * @param page
+ * The {@link IWorkbenchPage}
+ * @return The selected {@link IKeyTreeNode} of the page.
+ */
+ public static IKeyTreeNode getSelectedKeyTreeNode(IWorkbenchPage page) {
+ MessagesEditor editor = (MessagesEditor) page.getActiveEditor();
if (editor.getSelectedPage() instanceof I18NPage) {
I18NPage p = (I18NPage) editor.getSelectedPage();
ISelection selection = p.getSelection();
- if (!selection.isEmpty() && selection instanceof IStructuredSelection) {
- return (IKeyTreeNode) ((IStructuredSelection) selection).getFirstElement();
+ if (!selection.isEmpty()
+ && selection instanceof IStructuredSelection) {
+ return (IKeyTreeNode) ((IStructuredSelection) selection)
+ .getFirstElement();
}
}
return null;
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/IValuedKeyTreeNode.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/IValuedKeyTreeNode.java
index 88e53f9..f2e6173 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/IValuedKeyTreeNode.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/IValuedKeyTreeNode.java
@@ -18,20 +18,20 @@
public interface IValuedKeyTreeNode extends IKeyTreeNode {
- public void initValues(Map<Locale, String> values);
+ public void initValues(Map<Locale, String> values);
- public void addValue(Locale locale, String value);
+ public void addValue(Locale locale, String value);
- public void setValue(Locale locale, String newValue);
+ public void setValue(Locale locale, String newValue);
- public String getValue(Locale locale);
+ public String getValue(Locale locale);
- public Collection<String> getValues();
+ public Collection<String> getValues();
- public void setInfo(Object info);
+ public void setInfo(Object info);
- public Object getInfo();
+ public Object getInfo();
- public Collection<Locale> getLocales();
+ public Collection<Locale> getLocales();
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/KeyTreeFactory.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/KeyTreeFactory.java
index ddc9983..6137408 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/KeyTreeFactory.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/KeyTreeFactory.java
@@ -16,35 +16,42 @@
import org.eclipse.babel.core.message.tree.IKeyTreeNode;
import org.eclipse.babel.core.message.tree.internal.AbstractKeyTreeModel;
-
/**
* Factory class for the tree or nodes of the tree.
+ *
* @see IAbstractKeyTreeModel
- * @see IValuedKeyTreeNode
- * <br><br>
+ * @see IValuedKeyTreeNode <br>
+ * <br>
*
* @author Alexej Strelzow
*/
public class KeyTreeFactory {
- /**
- * @param messagesBundleGroup Input of the key tree model
- * @return The {@link IAbstractKeyTreeModel}
- */
- public static IAbstractKeyTreeModel createModel(IMessagesBundleGroup messagesBundleGroup) {
- return new AbstractKeyTreeModel((MessagesBundleGroup)messagesBundleGroup);
- }
-
/**
- * @param parent The parent node
- * @param name The name of the node
- * @param id The id of the node (messages key)
- * @param bundleGroup The {@link IMessagesBundleGroup}
+ * @param messagesBundleGroup
+ * Input of the key tree model
+ * @return The {@link IAbstractKeyTreeModel}
+ */
+ public static IAbstractKeyTreeModel createModel(
+ IMessagesBundleGroup messagesBundleGroup) {
+ return new AbstractKeyTreeModel(
+ (MessagesBundleGroup) messagesBundleGroup);
+ }
+
+ /**
+ * @param parent
+ * The parent node
+ * @param name
+ * The name of the node
+ * @param id
+ * The id of the node (messages key)
+ * @param bundleGroup
+ * The {@link IMessagesBundleGroup}
* @return A new instance of {@link IValuedKeyTreeNode}
*/
- public static IValuedKeyTreeNode createKeyTree(IKeyTreeNode parent, String name, String id,
- IMessagesBundleGroup bundleGroup) {
+ public static IValuedKeyTreeNode createKeyTree(IKeyTreeNode parent,
+ String name, String id, IMessagesBundleGroup bundleGroup) {
return new ValuedKeyTreeNode(parent, name, id, bundleGroup);
}
-
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ValuedKeyTreeNode.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ValuedKeyTreeNode.java
index 9571db1..db2eb21 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ValuedKeyTreeNode.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ValuedKeyTreeNode.java
@@ -21,36 +21,36 @@
import org.eclipse.babel.core.message.tree.IKeyTreeNode;
import org.eclipse.babel.core.message.tree.internal.KeyTreeNode;
+public class ValuedKeyTreeNode extends KeyTreeNode implements
+ IValuedKeyTreeNode {
-public class ValuedKeyTreeNode extends KeyTreeNode implements IValuedKeyTreeNode {
-
- public ValuedKeyTreeNode(IKeyTreeNode parent, String name, String messageKey,
- IMessagesBundleGroup messagesBundleGroup) {
+ public ValuedKeyTreeNode(IKeyTreeNode parent, String name,
+ String messageKey, IMessagesBundleGroup messagesBundleGroup) {
super(parent, name, messageKey, messagesBundleGroup);
}
private Map<Locale, String> values = new HashMap<Locale, String>();
private Object info;
- public void initValues (Map<Locale, String> values) {
+ public void initValues(Map<Locale, String> values) {
this.values = values;
}
- public void addValue (Locale locale, String value) {
+ public void addValue(Locale locale, String value) {
values.put(locale, value);
}
-
- public String getValue (Locale locale) {
+
+ public String getValue(Locale locale) {
return values.get(locale);
}
-
+
public void setValue(Locale locale, String newValue) {
- if (values.containsKey(locale))
- values.remove(locale);
- addValue(locale, newValue);
+ if (values.containsKey(locale))
+ values.remove(locale);
+ addValue(locale, newValue);
}
-
- public Collection<String> getValues () {
+
+ public Collection<String> getValues() {
return values.values();
}
@@ -61,13 +61,13 @@
public Object getInfo() {
return info;
}
-
- public Collection<Locale> getLocales () {
- List<Locale> locs = new ArrayList<Locale> ();
+
+ public Collection<Locale> getLocales() {
+ List<Locale> locs = new ArrayList<Locale>();
for (Locale loc : values.keySet()) {
locs.add(loc);
}
return locs;
}
-
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Builder.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Builder.java
index 0b081bf..eae906d 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Builder.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Builder.java
@@ -41,254 +41,279 @@
/**
* @author Pascal Essiembre
- *
+ *
*/
public class Builder extends IncrementalProjectBuilder {
- public static final String BUILDER_ID =
- "org.eclipse.babel.editor.rbeBuilder"; //$NON-NLS-1$
-
+ public static final String BUILDER_ID = "org.eclipse.babel.editor.rbeBuilder"; //$NON-NLS-1$
+
private IValidationMarkerStrategy markerStrategy = new FileMarkerStrategy();
-
- class SampleDeltaVisitor implements IResourceDeltaVisitor {
- /**
- * @see org.eclipse.core.resources.IResourceDeltaVisitor#visit(org.eclipse.core.resources.IResourceDelta)
- */
- public boolean visit(IResourceDelta delta) throws CoreException {
- IResource resource = delta.getResource();
- switch (delta.getKind()) {
- case IResourceDelta.ADDED:
- // handle added resource
+
+ class SampleDeltaVisitor implements IResourceDeltaVisitor {
+ /**
+ * @see org.eclipse.core.resources.IResourceDeltaVisitor#visit(org.eclipse.core.resources.IResourceDelta)
+ */
+ public boolean visit(IResourceDelta delta) throws CoreException {
+ IResource resource = delta.getResource();
+ switch (delta.getKind()) {
+ case IResourceDelta.ADDED:
+ // handle added resource
System.out.println("RBE DELTA added");
- checkBundleResource(resource);
- break;
- case IResourceDelta.REMOVED:
+ checkBundleResource(resource);
+ break;
+ case IResourceDelta.REMOVED:
System.out.println("RBE DELTA Removed"); //$NON-NLS-1$
- RBManager.getInstance(delta.getResource().getProject()).notifyResourceRemoved(delta.getResource());
- // handle removed resource
- break;
- case IResourceDelta.CHANGED:
+ RBManager.getInstance(delta.getResource().getProject())
+ .notifyResourceRemoved(delta.getResource());
+ // handle removed resource
+ break;
+ case IResourceDelta.CHANGED:
System.out.println("RBE DELTA changed");
- // handle changed resource
- checkBundleResource(resource);
- break;
- }
- //return true to continue visiting children.
- return true;
- }
- }
+ // handle changed resource
+ checkBundleResource(resource);
+ break;
+ }
+ // return true to continue visiting children.
+ return true;
+ }
+ }
- class SampleResourceVisitor implements IResourceVisitor {
- public boolean visit(IResource resource) {
- checkBundleResource(resource);
- //return true to continue visiting children.
- return true;
- }
- }
+ class SampleResourceVisitor implements IResourceVisitor {
+ public boolean visit(IResource resource) {
+ checkBundleResource(resource);
+ // return true to continue visiting children.
+ return true;
+ }
+ }
- /** list built during a single build of the properties files.
- * Contains the list of files that must be validated.
- * The validation is done only at the end of the visitor.
- * This way the visitor can add extra files to be visited.
- * For example: if the default properties file is
- * changed, it is a good idea to rebuild all
- * localized files in the same MessageBundleGroup even if themselves
- * were not changed. */
+ /**
+ * list built during a single build of the properties files. Contains the
+ * list of files that must be validated. The validation is done only at the
+ * end of the visitor. This way the visitor can add extra files to be
+ * visited. For example: if the default properties file is changed, it is a
+ * good idea to rebuild all localized files in the same MessageBundleGroup
+ * even if themselves were not changed.
+ */
private Set _resourcesToValidate;
/**
* Index built during a single build.
* <p>
- * The values of that map are message bundles.
- * The key is a resource that belongs to that message bundle.
+ * The values of that map are message bundles. The key is a resource that
+ * belongs to that message bundle.
* </p>
*/
- private Map<IFile,MessagesBundleGroup> _alreadBuiltMessageBundle;
-
-// /** one indexer per project we open and close it at the beginning and the end of each build. */
-// private Indexer _indexer = new Indexer();
-
- /**
- * @see org.eclipse.core.resources.IncrementalProjectBuilder#build(
- * int, java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
- */
- protected IProject[] build(int kind, Map args, IProgressMonitor monitor)
- throws CoreException {
- try {
- _alreadBuiltMessageBundle = null;
- _resourcesToValidate = null;
- if (kind == FULL_BUILD) {
- fullBuild(monitor);
- } else {
- IResourceDelta delta = getDelta(getProject());
- if (delta == null) {
- fullBuild(monitor);
- } else {
- incrementalBuild(delta, monitor);
- }
- }
- } finally {
- try {
- finishBuild();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- //must dispose the message bundles:
- if (_alreadBuiltMessageBundle != null) {
- for (MessagesBundleGroup msgGrp : _alreadBuiltMessageBundle.values()) {
- try {
-// msgGrp.dispose(); // TODO: [alst] do we need this really?
- } catch (Throwable t) {
- //FIXME: remove this debugging:
- System.err.println(
- "error disposing message-bundle-group "
- + msgGrp.getName());
- //disregard crashes: we are doing our best effort to dispose things.
- }
- }
- _alreadBuiltMessageBundle = null;
- _resourcesToValidate = null;
- }
-// if (_indexer != null) {
-// try {
-// _indexer.close(true);
-// _indexer.clear();
-// } catch (CorruptIndexException e) {
-// e.printStackTrace();
-// } catch (IOException e) {
-// e.printStackTrace();
-// }
-// }
- }
- }
- return null;
- }
+ private Map<IFile, MessagesBundleGroup> _alreadBuiltMessageBundle;
- /**
- * Collect the resource bundles to validate and
- * index the corresponding MessageBundleGroup(s).
- * @param resource The resource currently validated.
- */
- void checkBundleResource(IResource resource) {
- if (true)
- return; // TODO [alst]
- if (resource instanceof IFile && resource.getName().endsWith(
- ".properties")) { //$NON-NLS-1$ //TODO have customized?
+ // /** one indexer per project we open and close it at the beginning and the
+ // end of each build. */
+ // private Indexer _indexer = new Indexer();
+
+ /**
+ * @see org.eclipse.core.resources.IncrementalProjectBuilder#build(int,
+ * java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
+ */
+ protected IProject[] build(int kind, Map args, IProgressMonitor monitor)
+ throws CoreException {
+ try {
+ _alreadBuiltMessageBundle = null;
+ _resourcesToValidate = null;
+ if (kind == FULL_BUILD) {
+ fullBuild(monitor);
+ } else {
+ IResourceDelta delta = getDelta(getProject());
+ if (delta == null) {
+ fullBuild(monitor);
+ } else {
+ incrementalBuild(delta, monitor);
+ }
+ }
+ } finally {
+ try {
+ finishBuild();
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ // must dispose the message bundles:
+ if (_alreadBuiltMessageBundle != null) {
+ for (MessagesBundleGroup msgGrp : _alreadBuiltMessageBundle
+ .values()) {
+ try {
+ // msgGrp.dispose(); // TODO: [alst] do we need this
+ // really?
+ } catch (Throwable t) {
+ // FIXME: remove this debugging:
+ System.err
+ .println("error disposing message-bundle-group "
+ + msgGrp.getName());
+ // disregard crashes: we are doing our best effort
+ // to dispose things.
+ }
+ }
+ _alreadBuiltMessageBundle = null;
+ _resourcesToValidate = null;
+ }
+ // if (_indexer != null) {
+ // try {
+ // _indexer.close(true);
+ // _indexer.clear();
+ // } catch (CorruptIndexException e) {
+ // e.printStackTrace();
+ // } catch (IOException e) {
+ // e.printStackTrace();
+ // }
+ // }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Collect the resource bundles to validate and index the corresponding
+ * MessageBundleGroup(s).
+ *
+ * @param resource
+ * The resource currently validated.
+ */
+ void checkBundleResource(IResource resource) {
+ if (true)
+ return; // TODO [alst]
+ if (resource instanceof IFile
+ && resource.getName().endsWith(".properties")) { //$NON-NLS-1$ //TODO have customized?
IFile file = (IFile) resource;
if (file.isDerived()) {
- return;
+ return;
}
- //System.err.println("Looking at " + file.getFullPath());
+ // System.err.println("Looking at " + file.getFullPath());
deleteMarkers(file);
MessagesBundleGroup msgBundleGrp = null;
if (_alreadBuiltMessageBundle == null) {
- _alreadBuiltMessageBundle = new HashMap<IFile,MessagesBundleGroup>();
- _resourcesToValidate = new HashSet();
+ _alreadBuiltMessageBundle = new HashMap<IFile, MessagesBundleGroup>();
+ _resourcesToValidate = new HashSet();
} else {
- msgBundleGrp = _alreadBuiltMessageBundle.get(file);
+ msgBundleGrp = _alreadBuiltMessageBundle.get(file);
}
if (msgBundleGrp == null) {
- msgBundleGrp = MessagesBundleGroupFactory.createBundleGroup(null, file);
- if (msgBundleGrp != null) {
- //index the files for which this MessagesBundleGroup
- //should be used for the validation.
- //cheaper than creating a group for each on of those
- //files.
- boolean validateEntireGroup = false;
- for (IMessagesBundle msgBundle : msgBundleGrp.getMessagesBundles()) {
- Object src = ((MessagesBundle)msgBundle).getResource().getSource();
- //System.err.println(src + " -> " + msgBundleGrp);
- if (src instanceof IFile) {//when it is a read-only thing we don't index it.
- _alreadBuiltMessageBundle.put((IFile)src, msgBundleGrp);
- if (!validateEntireGroup && src == resource) {
- if (((MessagesBundle)msgBundle).getLocale() == null
- || ((MessagesBundle)msgBundle).getLocale().equals(UIUtils.ROOT_LOCALE)) {
- //ok the default properties have been changed.
- //make sure that all resources in this bundle group
- //are validated too:
- validateEntireGroup = true;
-
- //TODO: eventually something similar.
- //with foo_en.properties changed.
- //then foo_en_US.properties must be revalidated
- //and foo_en_CA.properties as well.
-
- }
- }
- }
- }
- if (validateEntireGroup) {
- for (IMessagesBundle msgBundle : msgBundleGrp.getMessagesBundles()) {
- Object src = ((MessagesBundle)msgBundle).getResource().getSource();
- _resourcesToValidate.add(src);
- }
- }
- }
+ msgBundleGrp = MessagesBundleGroupFactory.createBundleGroup(
+ null, file);
+ if (msgBundleGrp != null) {
+ // index the files for which this MessagesBundleGroup
+ // should be used for the validation.
+ // cheaper than creating a group for each on of those
+ // files.
+ boolean validateEntireGroup = false;
+ for (IMessagesBundle msgBundle : msgBundleGrp
+ .getMessagesBundles()) {
+ Object src = ((MessagesBundle) msgBundle).getResource()
+ .getSource();
+ // System.err.println(src + " -> " + msgBundleGrp);
+ if (src instanceof IFile) {// when it is a read-only
+ // thing we don't index it.
+ _alreadBuiltMessageBundle.put((IFile) src,
+ msgBundleGrp);
+ if (!validateEntireGroup && src == resource) {
+ if (((MessagesBundle) msgBundle).getLocale() == null
+ || ((MessagesBundle) msgBundle)
+ .getLocale().equals(
+ UIUtils.ROOT_LOCALE)) {
+ // ok the default properties have been
+ // changed.
+ // make sure that all resources in this
+ // bundle group
+ // are validated too:
+ validateEntireGroup = true;
+
+ // TODO: eventually something similar.
+ // with foo_en.properties changed.
+ // then foo_en_US.properties must be
+ // revalidated
+ // and foo_en_CA.properties as well.
+
+ }
+ }
+ }
+ }
+ if (validateEntireGroup) {
+ for (IMessagesBundle msgBundle : msgBundleGrp
+ .getMessagesBundles()) {
+ Object src = ((MessagesBundle) msgBundle)
+ .getResource().getSource();
+ _resourcesToValidate.add(src);
+ }
+ }
+ }
}
-
+
_resourcesToValidate.add(resource);
-
+
}
- }
-
- /**
- * Validates the message bundles collected by the visitor.
- * Makes sure we validate only once each message bundle and build only once each
- * MessageBundleGroup it belongs to.
- */
- private void finishBuild() {
- if (_resourcesToValidate != null) {
- for (Iterator it = _resourcesToValidate.iterator(); it.hasNext();) {
- IFile resource = (IFile)it.next();
- MessagesBundleGroup msgBundleGrp =
- _alreadBuiltMessageBundle.get(resource);
-
- if (msgBundleGrp != null) {
- //when null it is probably because it was skipped from
- //the group because the locale was filtered.
- try {
- // System.out.println("Validate " + resource); //$NON-NLS-1$
- //TODO check if there is a matching EclipsePropertiesEditorResource already open.
- //else, create MessagesBundle from PropertiesIFileResource
- MessagesBundle messagesBundle = msgBundleGrp.getMessagesBundle(resource);
- if (messagesBundle != null) {
- Locale locale = messagesBundle.getLocale();
- MessagesBundleGroupValidator.validate(msgBundleGrp, locale, markerStrategy);
- }//, _indexer);
- } catch (Exception e) {
- e.printStackTrace();
- }
- } else {
- // System.out.println("Not validating " + resource); //$NON-NLS-1$
- }
- }
- }
- }
+ }
- private void deleteMarkers(IFile file) {
- try {
-// System.out.println("Builder: deleteMarkers"); //$NON-NLS-1$
- file.deleteMarkers(MessagesEditorPlugin.MARKER_TYPE, false, IResource.DEPTH_ZERO);
- } catch (CoreException ce) {
- }
- }
+ /**
+ * Validates the message bundles collected by the visitor. Makes sure we
+ * validate only once each message bundle and build only once each
+ * MessageBundleGroup it belongs to.
+ */
+ private void finishBuild() {
+ if (_resourcesToValidate != null) {
+ for (Iterator it = _resourcesToValidate.iterator(); it.hasNext();) {
+ IFile resource = (IFile) it.next();
+ MessagesBundleGroup msgBundleGrp = _alreadBuiltMessageBundle
+ .get(resource);
- protected void fullBuild(final IProgressMonitor monitor)
- throws CoreException {
-// System.out.println("Builder: fullBuild"); //$NON-NLS-1$
+ if (msgBundleGrp != null) {
+ // when null it is probably because it was skipped from
+ // the group because the locale was filtered.
+ try {
+ // System.out.println("Validate " + resource); //$NON-NLS-1$
+ // TODO check if there is a matching
+ // EclipsePropertiesEditorResource already open.
+ // else, create MessagesBundle from
+ // PropertiesIFileResource
+ MessagesBundle messagesBundle = msgBundleGrp
+ .getMessagesBundle(resource);
+ if (messagesBundle != null) {
+ Locale locale = messagesBundle.getLocale();
+ MessagesBundleGroupValidator.validate(msgBundleGrp,
+ locale, markerStrategy);
+ }// , _indexer);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ } else {
+ // System.out.println("Not validating " + resource); //$NON-NLS-1$
+ }
+ }
+ }
+ }
+
+ private void deleteMarkers(IFile file) {
+ try {
+ // System.out.println("Builder: deleteMarkers"); //$NON-NLS-1$
+ file.deleteMarkers(MessagesEditorPlugin.MARKER_TYPE, false,
+ IResource.DEPTH_ZERO);
+ } catch (CoreException ce) {
+ }
+ }
+
+ protected void fullBuild(final IProgressMonitor monitor)
+ throws CoreException {
+ // System.out.println("Builder: fullBuild"); //$NON-NLS-1$
getProject().accept(new SampleResourceVisitor());
- }
+ }
- protected void incrementalBuild(IResourceDelta delta,
- IProgressMonitor monitor) throws CoreException {
-// System.out.println("Builder: incrementalBuild"); //$NON-NLS-1$
+ protected void incrementalBuild(IResourceDelta delta,
+ IProgressMonitor monitor) throws CoreException {
+ // System.out.println("Builder: incrementalBuild"); //$NON-NLS-1$
delta.accept(new SampleDeltaVisitor());
- }
-
- protected void clean(IProgressMonitor monitor) throws CoreException {
- ResourcesPlugin.getWorkspace().getRoot()
- .deleteMarkers(MessagesEditorPlugin.MARKER_TYPE, false, IResource.DEPTH_INFINITE);
- }
-
-
+ }
+
+ protected void clean(IProgressMonitor monitor) throws CoreException {
+ ResourcesPlugin
+ .getWorkspace()
+ .getRoot()
+ .deleteMarkers(MessagesEditorPlugin.MARKER_TYPE, false,
+ IResource.DEPTH_INFINITE);
+ }
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Nature.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Nature.java
index 1920a4c..9c0cd3a 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Nature.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Nature.java
@@ -18,73 +18,75 @@
public class Nature implements IProjectNature {
- /**
- * ID of this project nature
- */
- public static final String NATURE_ID = "org.eclipse.babel.editor.rbeNature";
+ /**
+ * ID of this project nature
+ */
+ public static final String NATURE_ID = "org.eclipse.babel.editor.rbeNature";
- private IProject project;
+ private IProject project;
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.core.resources.IProjectNature#configure()
- */
- public void configure() throws CoreException {
- IProjectDescription desc = project.getDescription();
- ICommand[] commands = desc.getBuildSpec();
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.core.resources.IProjectNature#configure()
+ */
+ public void configure() throws CoreException {
+ IProjectDescription desc = project.getDescription();
+ ICommand[] commands = desc.getBuildSpec();
- for (int i = 0; i < commands.length; ++i) {
- if (commands[i].getBuilderName().equals(Builder.BUILDER_ID)) {
- return;
- }
- }
+ for (int i = 0; i < commands.length; ++i) {
+ if (commands[i].getBuilderName().equals(Builder.BUILDER_ID)) {
+ return;
+ }
+ }
- ICommand[] newCommands = new ICommand[commands.length + 1];
- System.arraycopy(commands, 0, newCommands, 0, commands.length);
- ICommand command = desc.newCommand();
- command.setBuilderName(Builder.BUILDER_ID);
- newCommands[newCommands.length - 1] = command;
- desc.setBuildSpec(newCommands);
- project.setDescription(desc, null);
- }
+ ICommand[] newCommands = new ICommand[commands.length + 1];
+ System.arraycopy(commands, 0, newCommands, 0, commands.length);
+ ICommand command = desc.newCommand();
+ command.setBuilderName(Builder.BUILDER_ID);
+ newCommands[newCommands.length - 1] = command;
+ desc.setBuildSpec(newCommands);
+ project.setDescription(desc, null);
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.core.resources.IProjectNature#deconfigure()
- */
- public void deconfigure() throws CoreException {
- IProjectDescription description = getProject().getDescription();
- ICommand[] commands = description.getBuildSpec();
- for (int i = 0; i < commands.length; ++i) {
- if (commands[i].getBuilderName().equals(Builder.BUILDER_ID)) {
- ICommand[] newCommands = new ICommand[commands.length - 1];
- System.arraycopy(commands, 0, newCommands, 0, i);
- System.arraycopy(commands, i + 1, newCommands, i,
- commands.length - i - 1);
- description.setBuildSpec(newCommands);
- return;
- }
- }
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.core.resources.IProjectNature#deconfigure()
+ */
+ public void deconfigure() throws CoreException {
+ IProjectDescription description = getProject().getDescription();
+ ICommand[] commands = description.getBuildSpec();
+ for (int i = 0; i < commands.length; ++i) {
+ if (commands[i].getBuilderName().equals(Builder.BUILDER_ID)) {
+ ICommand[] newCommands = new ICommand[commands.length - 1];
+ System.arraycopy(commands, 0, newCommands, 0, i);
+ System.arraycopy(commands, i + 1, newCommands, i,
+ commands.length - i - 1);
+ description.setBuildSpec(newCommands);
+ return;
+ }
+ }
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.core.resources.IProjectNature#getProject()
- */
- public IProject getProject() {
- return project;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.core.resources.IProjectNature#getProject()
+ */
+ public IProject getProject() {
+ return project;
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.core.resources.IProjectNature#setProject(org.eclipse.core.resources.IProject)
- */
- public void setProject(IProject project) {
- this.project = project;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.core.resources.IProjectNature#setProject(org.eclipse.core
+ * .resources.IProject)
+ */
+ public void setProject(IProject project) {
+ this.project = project;
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureAction.java
index 3f6ae43..a8be8b6 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureAction.java
@@ -24,126 +24,133 @@
import org.eclipse.ui.IWorkbenchPart;
public class ToggleNatureAction implements IObjectActionDelegate {
-
- /**
- * Method call during the start up of the plugin or during
- * a change of the preference MsgEditorPreferences#ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS.
- * <p>
- * Goes through the list of opened projects and either remove all the
- * natures or add them all for each opened java project if the nature was not there.
- * </p>
- */
- public static void addOrRemoveNatureOnAllJavaProjects(boolean doAdd) {
- IProject[] projs = ResourcesPlugin.getWorkspace().getRoot().getProjects();
- for (int i = 0; i < projs.length; i++) {
- IProject project = projs[i];
- addOrRemoveNatureOnProject(project, doAdd, true);
- }
- }
-
- /**
- *
- * @param project The project to setup if necessary
- * @param doAdd true to add, false to remove.
- * @param onlyJavaProject when true the nature will be added or removed
- * if and only if the project has a jdt-java nature
- */
- public static void addOrRemoveNatureOnProject(IProject project,
- boolean doAdd, boolean onlyJavaProject) {
- try {
- if (project.isAccessible() && (!onlyJavaProject ||
- UIUtils.hasNature(project, UIUtils.JDT_JAVA_NATURE))) {
- if (doAdd) {
- if (project.getNature(Nature.NATURE_ID) == null) {
- toggleNature(project);
- }
- } else {
- if (project.getNature(Nature.NATURE_ID) != null) {
- toggleNature(project);
- }
- }
- }
- } catch (CoreException ce) {
- ce.printStackTrace();//REMOVEME
- }
- }
-
+ /**
+ * Method call during the start up of the plugin or during a change of the
+ * preference MsgEditorPreferences#ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS.
+ * <p>
+ * Goes through the list of opened projects and either remove all the
+ * natures or add them all for each opened java project if the nature was
+ * not there.
+ * </p>
+ */
+ public static void addOrRemoveNatureOnAllJavaProjects(boolean doAdd) {
+ IProject[] projs = ResourcesPlugin.getWorkspace().getRoot()
+ .getProjects();
+ for (int i = 0; i < projs.length; i++) {
+ IProject project = projs[i];
+ addOrRemoveNatureOnProject(project, doAdd, true);
+ }
+ }
- private ISelection selection;
+ /**
+ *
+ * @param project
+ * The project to setup if necessary
+ * @param doAdd
+ * true to add, false to remove.
+ * @param onlyJavaProject
+ * when true the nature will be added or removed if and only if
+ * the project has a jdt-java nature
+ */
+ public static void addOrRemoveNatureOnProject(IProject project,
+ boolean doAdd, boolean onlyJavaProject) {
+ try {
+ if (project.isAccessible()
+ && (!onlyJavaProject || UIUtils.hasNature(project,
+ UIUtils.JDT_JAVA_NATURE))) {
+ if (doAdd) {
+ if (project.getNature(Nature.NATURE_ID) == null) {
+ toggleNature(project);
+ }
+ } else {
+ if (project.getNature(Nature.NATURE_ID) != null) {
+ toggleNature(project);
+ }
+ }
+ }
+ } catch (CoreException ce) {
+ ce.printStackTrace();// REMOVEME
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
- */
- public void run(IAction action) {
- if (selection instanceof IStructuredSelection) {
- for (Object element : ((IStructuredSelection) selection).toList()) {
- IProject project = null;
- if (element instanceof IProject) {
- project = (IProject) element;
- } else if (element instanceof IAdaptable) {
- project = (IProject) ((IAdaptable) element)
- .getAdapter(IProject.class);
- }
- if (project != null) {
- toggleNature(project);
- }
- }
- }
- }
+ }
- /**
- * Called when the selection is changed.
- * Update the state of the action (enabled/disabled) and its label.
- */
- public void selectionChanged(IAction action, ISelection selection) {
- this.selection = selection;
- }
+ private ISelection selection;
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.action.IAction,
- * org.eclipse.ui.IWorkbenchPart)
- */
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
+ */
+ public void run(IAction action) {
+ if (selection instanceof IStructuredSelection) {
+ for (Object element : ((IStructuredSelection) selection).toList()) {
+ IProject project = null;
+ if (element instanceof IProject) {
+ project = (IProject) element;
+ } else if (element instanceof IAdaptable) {
+ project = (IProject) ((IAdaptable) element)
+ .getAdapter(IProject.class);
+ }
+ if (project != null) {
+ toggleNature(project);
+ }
+ }
+ }
+ }
- /**
- * Toggles sample nature on a project
- *
- * @param project
- * to have sample nature added or removed
- */
- private static void toggleNature(IProject project) {
- try {
- IProjectDescription description = project.getDescription();
- String[] natures = description.getNatureIds();
+ /**
+ * Called when the selection is changed. Update the state of the action
+ * (enabled/disabled) and its label.
+ */
+ public void selectionChanged(IAction action, ISelection selection) {
+ this.selection = selection;
+ }
- for (int i = 0; i < natures.length; ++i) {
- if (Nature.NATURE_ID.equals(natures[i])) {
- // Remove the nature
- String[] newNatures = new String[natures.length - 1];
- System.arraycopy(natures, 0, newNatures, 0, i);
- System.arraycopy(natures, i + 1, newNatures, i,
- natures.length - i - 1);
- description.setNatureIds(newNatures);
- project.setDescription(description, null);
- return;
- }
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.
+ * action.IAction, org.eclipse.ui.IWorkbenchPart)
+ */
+ public void setActivePart(IAction action, IWorkbenchPart targetPart) {
+ }
- // Add the nature
- String[] newNatures = new String[natures.length + 1];
- System.arraycopy(natures, 0, newNatures, 0, natures.length);
- newNatures[natures.length] = Nature.NATURE_ID;
- System.out.println("New natures: " + BabelUtils.join(newNatures, ", "));
- description.setNatureIds(newNatures);
- project.setDescription(description, null);
- } catch (CoreException e) {
- }
- }
+ /**
+ * Toggles sample nature on a project
+ *
+ * @param project
+ * to have sample nature added or removed
+ */
+ private static void toggleNature(IProject project) {
+ try {
+ IProjectDescription description = project.getDescription();
+ String[] natures = description.getNatureIds();
+
+ for (int i = 0; i < natures.length; ++i) {
+ if (Nature.NATURE_ID.equals(natures[i])) {
+ // Remove the nature
+ String[] newNatures = new String[natures.length - 1];
+ System.arraycopy(natures, 0, newNatures, 0, i);
+ System.arraycopy(natures, i + 1, newNatures, i,
+ natures.length - i - 1);
+ description.setNatureIds(newNatures);
+ project.setDescription(description, null);
+ return;
+ }
+ }
+
+ // Add the nature
+ String[] newNatures = new String[natures.length + 1];
+ System.arraycopy(natures, 0, newNatures, 0, natures.length);
+ newNatures[natures.length] = Nature.NATURE_ID;
+ System.out.println("New natures: "
+ + BabelUtils.join(newNatures, ", "));
+ description.setNatureIds(newNatures);
+ project.setDescription(description, null);
+ } catch (CoreException e) {
+ }
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionAdd.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionAdd.java
index 091f8e3..09c82ec 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionAdd.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionAdd.java
@@ -10,7 +10,6 @@
******************************************************************************/
package org.eclipse.babel.editor.builder;
-
/**
* @author hmalphettes
*/
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionRemove.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionRemove.java
index 5a83270..6d93993 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionRemove.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionRemove.java
@@ -10,7 +10,6 @@
******************************************************************************/
package org.eclipse.babel.editor.builder;
-
/**
* @author hmalphettes
*/
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/BundleGroupRegistry.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/BundleGroupRegistry.java
index 2672d15..f592274 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/BundleGroupRegistry.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/BundleGroupRegistry.java
@@ -13,16 +13,14 @@
import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
import org.eclipse.core.resources.IResource;
-
/**
* @author Pascal Essiembre
- *
+ *
*/
public class BundleGroupRegistry {
-
public static MessagesBundleGroup getBundleGroup(IResource resource) {
- return null;//MessagesBundleGroupFactory.
+ return null;// MessagesBundleGroupFactory.
}
-
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/DefaultBundleGroupStrategy.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/DefaultBundleGroupStrategy.java
index cb8ae2f..8bf0259 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/DefaultBundleGroupStrategy.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/DefaultBundleGroupStrategy.java
@@ -43,22 +43,21 @@
import org.eclipse.ui.editors.text.TextEditor;
import org.eclipse.ui.part.FileEditorInput;
-
/**
- * MessagesBundle group strategy for standard properties file structure. That is,
- * all *.properties files of the same base name within the same directory.
+ * MessagesBundle group strategy for standard properties file structure. That
+ * is, all *.properties files of the same base name within the same directory.
+ *
* @author Pascal Essiembre
*/
public class DefaultBundleGroupStrategy implements IMessagesBundleGroupStrategy {
/** Class name of Properties file editor (Eclipse 3.1). */
- protected static final String PROPERTIES_EDITOR_CLASS_NAME =
- "org.eclipse.jdt.internal.ui.propertiesfileeditor." //$NON-NLS-1$
- + "PropertiesFileEditor"; //$NON-NLS-1$
+ protected static final String PROPERTIES_EDITOR_CLASS_NAME = "org.eclipse.jdt.internal.ui.propertiesfileeditor." //$NON-NLS-1$
+ + "PropertiesFileEditor"; //$NON-NLS-1$
/** Empty bundle array. */
protected static final MessagesBundle[] EMPTY_BUNDLES = new MessagesBundle[] {};
-
+
/** Eclipse editor site. */
protected IEditorSite site;
/** File being open, triggering the creation of a bundle group. */
@@ -67,58 +66,59 @@
private final String baseName;
/** Pattern used to match files in this strategy. */
private final String fileMatchPattern;
-
+
/**
* Constructor.
- * @param site editor site
- * @param file file opened
+ *
+ * @param site
+ * editor site
+ * @param file
+ * file opened
*/
public DefaultBundleGroupStrategy(IEditorSite site, IFile file) {
super();
this.file = file;
this.site = site;
- String patternCore =
- "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
- + file.getFileExtension() + ")$"; //$NON-NLS-1$
+ String patternCore = "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
+ + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
+ + file.getFileExtension() + ")$"; //$NON-NLS-1$
// Compute and cache name
String namePattern = "^(.*?)" + patternCore; //$NON-NLS-1$
- this.baseName = file.getName().replaceFirst(
- namePattern, "$1"); //$NON-NLS-1$
-
+ this.baseName = file.getName().replaceFirst(namePattern, "$1"); //$NON-NLS-1$
+
// File matching pattern
- this.fileMatchPattern =
- "^(" + baseName + ")" + patternCore; //$NON-NLS-1$//$NON-NLS-2$
+ this.fileMatchPattern = "^(" + baseName + ")" + patternCore; //$NON-NLS-1$//$NON-NLS-2$
}
/**
* @see org.eclipse.babel.core.message.internal.strategy.IMessagesBundleGroupStrategy
- * #createMessagesBundleGroupName()
+ * #createMessagesBundleGroupName()
*/
public String createMessagesBundleGroupName() {
- return getProjectName()+"*.properties";
+ return getProjectName() + "*.properties";
}
-
- public String createMessagesBundleId() {
- return getResourceBundleId(file);
- }
-
- public static String getResourceBundleId (IResource resource) {
- String packageFragment = "";
- IJavaElement propertyFile = JavaCore.create(resource.getParent());
- if (propertyFile != null && propertyFile instanceof IPackageFragment)
- packageFragment = ((IPackageFragment) propertyFile).getElementName();
-
- return (packageFragment.length() > 0 ? packageFragment + "." : "") +
- getResourceBundleName(resource);
- }
-
+ public String createMessagesBundleId() {
+ return getResourceBundleId(file);
+ }
+
+ public static String getResourceBundleId(IResource resource) {
+ String packageFragment = "";
+
+ IJavaElement propertyFile = JavaCore.create(resource.getParent());
+ if (propertyFile != null && propertyFile instanceof IPackageFragment)
+ packageFragment = ((IPackageFragment) propertyFile)
+ .getElementName();
+
+ return (packageFragment.length() > 0 ? packageFragment + "." : "")
+ + getResourceBundleName(resource);
+ }
+
public static String getResourceBundleName(IResource res) {
String name = res.getName();
- String regex = "^(.*?)" //$NON-NLS-1$
+ String regex = "^(.*?)" //$NON-NLS-1$
+ "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
+ "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
+ res.getFileExtension() + ")$"; //$NON-NLS-1$
@@ -127,25 +127,25 @@
/**
* @see org.eclipse.babel.core.bundle.IMessagesBundleGroupStrategy
- * #loadMessagesBundles()
+ * #loadMessagesBundles()
*/
public MessagesBundle[] loadMessagesBundles() throws MessageException {
Collection<MessagesBundle> bundles = new ArrayList<MessagesBundle>();
collectBundlesInContainer(file.getParent(), bundles);
return bundles.toArray(EMPTY_BUNDLES);
}
-
+
protected void collectBundlesInContainer(IContainer container,
- Collection<MessagesBundle> bundlesCollector) throws MessageException {
- if (!container.exists()) {
- return;
- }
+ Collection<MessagesBundle> bundlesCollector)
+ throws MessageException {
+ if (!container.exists()) {
+ return;
+ }
IResource[] resources = null;
try {
resources = container.members();
} catch (CoreException e) {
- throw new MessageException(
- "Can't load resource bundles.", e); //$NON-NLS-1$
+ throw new MessageException("Can't load resource bundles.", e); //$NON-NLS-1$
}
for (int i = 0; i < resources.length; i++) {
@@ -154,78 +154,90 @@
if (resource instanceof IFile
&& resourceName.matches(fileMatchPattern)) {
// Build local title
- String localeText = resourceName.replaceFirst(
- fileMatchPattern, "$2"); //$NON-NLS-1$
+ String localeText = resourceName.replaceFirst(fileMatchPattern,
+ "$2"); //$NON-NLS-1$
Locale locale = BabelUtils.parseLocale(localeText);
if (UIUtils.isDisplayed(locale)) {
- bundlesCollector.add(createBundle(locale, resource));
+ bundlesCollector.add(createBundle(locale, resource));
}
}
}
-
+
}
- /* (non-Javadoc)
- * @see org.eclipse.babel.core.bundle.IBundleGroupStrategy#createBundle(java.util.Locale)
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.babel.core.bundle.IBundleGroupStrategy#createBundle(java.
+ * util.Locale)
*/
public MessagesBundle createMessagesBundle(Locale locale) {
- // create new empty locale file
- IFile openedFile = getOpenedFile();
- IPath path = openedFile.getProjectRelativePath();
- String localeStr = locale != null ? "_" + locale.toString() : "";
- String newFilename = getBaseName()+localeStr+"."+openedFile.getFileExtension();
- IFile newFile = openedFile.getProject().getFile(path.removeLastSegments(1).addTrailingSeparator()+newFilename);
-
- if (! newFile.exists()) {
- try {
- // create new ifile with an empty input stream
- newFile.create(new ByteArrayInputStream(new byte[0]), IResource.NONE, null);
- } catch (CoreException e) {
- e.printStackTrace();
- }
+ // create new empty locale file
+ IFile openedFile = getOpenedFile();
+ IPath path = openedFile.getProjectRelativePath();
+ String localeStr = locale != null ? "_" + locale.toString() : "";
+ String newFilename = getBaseName() + localeStr + "."
+ + openedFile.getFileExtension();
+ IFile newFile = openedFile.getProject()
+ .getFile(
+ path.removeLastSegments(1).addTrailingSeparator()
+ + newFilename);
+
+ if (!newFile.exists()) {
+ try {
+ // create new ifile with an empty input stream
+ newFile.create(new ByteArrayInputStream(new byte[0]),
+ IResource.NONE, null);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
}
- return createBundle(locale, newFile);
+ return createBundle(locale, newFile);
}
-
+
/**
* Creates a resource bundle for an existing resource.
- * @param locale locale for which to create a bundle
- * @param resource resource used to create bundle
+ *
+ * @param locale
+ * locale for which to create a bundle
+ * @param resource
+ * resource used to create bundle
* @return an initialized bundle
*/
protected MessagesBundle createBundle(Locale locale, IResource resource)
throws MessageException {
try {
MsgEditorPreferences prefs = MsgEditorPreferences.getInstance();
-
- //TODO have bundleResource created in a separate factory
- //shared between strategies
+
+ // TODO have bundleResource created in a separate factory
+ // shared between strategies
IMessagesResource messagesResource;
if (site == null) {
- //site is null during the build.
- messagesResource = new PropertiesIFileResource(
- locale,
+ // site is null during the build.
+ messagesResource = new PropertiesIFileResource(locale,
new PropertiesSerializer(prefs.getSerializerConfig()),
- new PropertiesDeserializer(prefs.getDeserializerConfig()),
+ new PropertiesDeserializer(prefs
+ .getDeserializerConfig()),
(IFile) resource, MessagesEditorPlugin.getDefault());
} else {
- messagesResource = new EclipsePropertiesEditorResource(
- locale,
+ messagesResource = new EclipsePropertiesEditorResource(locale,
new PropertiesSerializer(prefs.getSerializerConfig()),
- new PropertiesDeserializer(prefs.getDeserializerConfig()),
- createEditor(resource, locale));
+ new PropertiesDeserializer(
+ prefs.getDeserializerConfig()), createEditor(
+ resource, locale));
}
return new MessagesBundle(messagesResource);
} catch (PartInitException e) {
- throw new MessageException(
- "Cannot create bundle for locale " //$NON-NLS-1$
- + locale + " and resource " + resource, e); //$NON-NLS-1$
+ throw new MessageException("Cannot create bundle for locale " //$NON-NLS-1$
+ + locale + " and resource " + resource, e); //$NON-NLS-1$
}
}
/**
* Creates an Eclipse editor.
- * @param site
+ *
+ * @param site
* @param resource
* @param locale
* @return
@@ -233,17 +245,16 @@
*/
protected TextEditor createEditor(IResource resource, Locale locale)
throws PartInitException {
-
+
TextEditor textEditor = null;
if (resource != null && resource instanceof IFile) {
- try {
- resource.refreshLocal(IResource.DEPTH_ZERO, null);
- } catch (CoreException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- IEditorInput newEditorInput =
- new FileEditorInput((IFile) resource);
+ try {
+ resource.refreshLocal(IResource.DEPTH_ZERO, null);
+ } catch (CoreException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ }
+ IEditorInput newEditorInput = new FileEditorInput((IFile) resource);
textEditor = null;
try {
// Use PropertiesFileEditor if available
@@ -257,23 +268,24 @@
}
return textEditor;
}
-
+
/**
* @return The file opened.
*/
protected IFile getOpenedFile() {
- return file;
+ return file;
}
- /**
+ /**
* @return The base name of the resource bundle.
*/
protected String getBaseName() {
- return baseName;
+ return baseName;
}
-
+
public String getProjectName() {
- return ResourcesPlugin.getWorkspace().getRoot().getProject(file.getFullPath().segments()[0]).getName();
+ return ResourcesPlugin.getWorkspace().getRoot()
+ .getProject(file.getFullPath().segments()[0]).getName();
}
-
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/MessagesBundleGroupFactory.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/MessagesBundleGroupFactory.java
index bc28df8..f2ea37a 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/MessagesBundleGroupFactory.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/MessagesBundleGroupFactory.java
@@ -30,12 +30,11 @@
import org.eclipse.core.runtime.Path;
import org.eclipse.ui.IEditorSite;
-
/**
* @author Pascal Essiembre
* @author Hugues Malphettes
*/
-//TODO make /*default*/ that only the registry would use
+// TODO make /*default*/ that only the registry would use
public final class MessagesBundleGroupFactory {
/**
@@ -46,216 +45,227 @@
}
/**
- * Creates a new bundle group, based on the given site and file. Currently,
+ * Creates a new bundle group, based on the given site and file. Currently,
* only default bundle groups and Eclipse NL within a plugin are supported.
+ *
* @param site
* @param file
* @return
*/
- public static MessagesBundleGroup createBundleGroup(IEditorSite site, IFile file) {
- /*
- * Check if NL is supported.
- */
- if (!MsgEditorPreferences.getInstance().isNLSupportEnabled()) {
- return createDefaultBundleGroup(site, file);
- }
+ public static MessagesBundleGroup createBundleGroup(IEditorSite site,
+ IFile file) {
+ /*
+ * Check if NL is supported.
+ */
+ if (!MsgEditorPreferences.getInstance().isNLSupportEnabled()) {
+ return createDefaultBundleGroup(site, file);
+ }
- //check we are inside an eclipse plugin project where NL is supported at runtime:
- IProject proj = file.getProject();
- try {
- if (proj == null || !proj.hasNature(UIUtils.PDE_NATURE)) { //$NON-NLS-1$
- return createDefaultBundleGroup(site, file);
- }
- } catch (CoreException e) { }
+ // check we are inside an eclipse plugin project where NL is supported
+ // at runtime:
+ IProject proj = file.getProject();
+ try {
+ if (proj == null || !proj.hasNature(UIUtils.PDE_NATURE)) { //$NON-NLS-1$
+ return createDefaultBundleGroup(site, file);
+ }
+ } catch (CoreException e) {
+ }
- IFolder nl = getNLFolder(file);
-
- //look if we are inside a fragment plugin:
- String hostId = getHostPluginId(file);
- if (hostId != null) {
- //we are indeed inside a fragment.
- //use the appropriate strategy.
- //we are a priori not interested in
- //looking for the files of other languages
- //that might be in other fragments plugins.
- //this behavior could be changed.
- return new MessagesBundleGroup(
- new NLFragmentBundleGroupStrategy(site, file, hostId, nl));
- }
-
- if (site == null) {
- //this is during the build we are not interested in validating files
- //coming from other projects:
- //no need to look in other projects for related files.
- return new MessagesBundleGroup(new NLPluginBundleGroupStrategy(
- site, file, nl));
- }
+ IFolder nl = getNLFolder(file);
- //if we are in a host plugin we might have fragments for it.
- //let's look for them so we can eventually load them all.
- //in this situation we are only looking for those fragments
- //inside the workspace and with files being developed there;
- //in other words: we don't look for read-only resources
- //located inside jars or the platform itself.
- IProject[] frags = collectTargetingFragments(file);
- if (frags != null) {
- return new MessagesBundleGroup(new NLPluginBundleGroupStrategy(
- site, file, nl, frags));
- }
-
- /*
- * Check if there is an NL directory
- * something like: nl/en/US/messages.properties
- * which is for eclipse runtime equivalent to: messages_en_US.properties
- */
- return new MessagesBundleGroup(new NLPluginBundleGroupStrategy(
- site, file, nl));
+ // look if we are inside a fragment plugin:
+ String hostId = getHostPluginId(file);
+ if (hostId != null) {
+ // we are indeed inside a fragment.
+ // use the appropriate strategy.
+ // we are a priori not interested in
+ // looking for the files of other languages
+ // that might be in other fragments plugins.
+ // this behavior could be changed.
+ return new MessagesBundleGroup(new NLFragmentBundleGroupStrategy(
+ site, file, hostId, nl));
+ }
+
+ if (site == null) {
+ // this is during the build we are not interested in validating
+ // files
+ // coming from other projects:
+ // no need to look in other projects for related files.
+ return new MessagesBundleGroup(new NLPluginBundleGroupStrategy(
+ site, file, nl));
+ }
+
+ // if we are in a host plugin we might have fragments for it.
+ // let's look for them so we can eventually load them all.
+ // in this situation we are only looking for those fragments
+ // inside the workspace and with files being developed there;
+ // in other words: we don't look for read-only resources
+ // located inside jars or the platform itself.
+ IProject[] frags = collectTargetingFragments(file);
+ if (frags != null) {
+ return new MessagesBundleGroup(new NLPluginBundleGroupStrategy(
+ site, file, nl, frags));
+ }
+
+ /*
+ * Check if there is an NL directory something like:
+ * nl/en/US/messages.properties which is for eclipse runtime equivalent
+ * to: messages_en_US.properties
+ */
+ return new MessagesBundleGroup(new NLPluginBundleGroupStrategy(site,
+ file, nl));
}
- private static MessagesBundleGroup createDefaultBundleGroup(IEditorSite site, IFile file) {
- return new MessagesBundleGroup(
- new DefaultBundleGroupStrategy(site, file));
+ private static MessagesBundleGroup createDefaultBundleGroup(
+ IEditorSite site, IFile file) {
+ return new MessagesBundleGroup(new DefaultBundleGroupStrategy(site,
+ file));
}
-
-//reading plugin manifests related utility methods. TO BE MOVED TO CORE ?
-
+
+ // reading plugin manifests related utility methods. TO BE MOVED TO CORE ?
+
private static final String BUNDLE_NAME = "Bundle-SymbolicName:"; //$NON-NLS-1$
private static final String FRAG_HOST = "Fragment-Host:"; //$NON-NLS-1$
+
/**
* @param file
* @return The id of the host-plugin if the edited file is inside a
- * pde-project that is a fragment. null otherwise.
+ * pde-project that is a fragment. null otherwise.
*/
static String getHostPluginId(IResource file) {
- return getPDEManifestAttribute(file, FRAG_HOST);
+ return getPDEManifestAttribute(file, FRAG_HOST);
}
+
/**
* @param file
* @return The id of the BUNDLE_NAME if the edited file is inside a
- * pde-project. null otherwise.
+ * pde-project. null otherwise.
*/
static String getBundleId(IResource file) {
- return getPDEManifestAttribute(file, BUNDLE_NAME);
+ return getPDEManifestAttribute(file, BUNDLE_NAME);
}
+
/**
- * Fetches the IProject in which openedFile is located.
- * If the project is a PDE project, looks for the MANIFEST.MF file
- * Parses the file and returns the value corresponding to the key
- * The value is stripped of its eventual properties (version constraints and others).
+ * Fetches the IProject in which openedFile is located. If the project is a
+ * PDE project, looks for the MANIFEST.MF file Parses the file and returns
+ * the value corresponding to the key The value is stripped of its eventual
+ * properties (version constraints and others).
*/
static String getPDEManifestAttribute(IResource openedFile, String key) {
- IProject proj = openedFile.getProject();
- if (proj == null || !proj.isAccessible()) {
- return null;
- }
- if (!UIUtils.hasNature(proj, UIUtils.PDE_NATURE)) { //$NON-NLS-1$
- return null;
- }
- IResource mf = proj.findMember(new Path("META-INF/MANIFEST.MF")); //$NON-NLS-1$
- if (mf == null || mf.getType() != IResource.FILE) {
- return null;
- }
- //now look for the FragmentHost.
- //don't use the java.util.Manifest API to parse the manifest as sometimes,
- //eclipse tolerates faulty manifests where lines are more than 70 characters long.
- InputStream in = null;
- try {
- in = ((IFile)mf).getContents();
- //supposedly in utf-8. should not really matter for us
- Reader r = new InputStreamReader(in, "UTF-8");
- LineNumberReader lnr = new LineNumberReader(r);
- String line = lnr.readLine();
- while (line != null) {
- if (line.startsWith(key)) {
- String value = line.substring(key.length());
- int index = value.indexOf(';');
- if (index != -1) {
- //remove the versions constraints and other properties.
- value = value.substring(0, index);
- }
- return value.trim();
- }
- line = lnr.readLine();
- }
- lnr.close();
- r.close();
- } catch (IOException ioe) {
- //TODO: something!
- ioe.printStackTrace();
- } catch (CoreException ce) {
- //TODO: something!
- ce.printStackTrace();
- } finally {
- if (in != null) try { in.close(); } catch (IOException e) {}
- }
- return null;
+ IProject proj = openedFile.getProject();
+ if (proj == null || !proj.isAccessible()) {
+ return null;
+ }
+ if (!UIUtils.hasNature(proj, UIUtils.PDE_NATURE)) { //$NON-NLS-1$
+ return null;
+ }
+ IResource mf = proj.findMember(new Path("META-INF/MANIFEST.MF")); //$NON-NLS-1$
+ if (mf == null || mf.getType() != IResource.FILE) {
+ return null;
+ }
+ // now look for the FragmentHost.
+ // don't use the java.util.Manifest API to parse the manifest as
+ // sometimes,
+ // eclipse tolerates faulty manifests where lines are more than 70
+ // characters long.
+ InputStream in = null;
+ try {
+ in = ((IFile) mf).getContents();
+ // supposedly in utf-8. should not really matter for us
+ Reader r = new InputStreamReader(in, "UTF-8");
+ LineNumberReader lnr = new LineNumberReader(r);
+ String line = lnr.readLine();
+ while (line != null) {
+ if (line.startsWith(key)) {
+ String value = line.substring(key.length());
+ int index = value.indexOf(';');
+ if (index != -1) {
+ // remove the versions constraints and other properties.
+ value = value.substring(0, index);
+ }
+ return value.trim();
+ }
+ line = lnr.readLine();
+ }
+ lnr.close();
+ r.close();
+ } catch (IOException ioe) {
+ // TODO: something!
+ ioe.printStackTrace();
+ } catch (CoreException ce) {
+ // TODO: something!
+ ce.printStackTrace();
+ } finally {
+ if (in != null)
+ try {
+ in.close();
+ } catch (IOException e) {
+ }
+ }
+ return null;
}
-
+
/**
* @see http://dev.eclipse.org/mhonarc/lists/babel-dev/msg00111.
*
* @param openedFile
- * @return The nl folder that is a direct child of the project and an ancestor
- * of the opened file or null if no such thing.
+ * @return The nl folder that is a direct child of the project and an
+ * ancestor of the opened file or null if no such thing.
*/
protected static IFolder getNLFolder(IFile openedFile) {
- IContainer cont = openedFile.getParent();
- while (cont != null) {
- if (cont.getParent() != null
- && cont.getParent().getType() == IResource.PROJECT) {
- if (cont.getName().equals("nl")) {
- return (IFolder)cont;
- }
- return null;
- }
- cont = cont.getParent();
- }
- return null;
+ IContainer cont = openedFile.getParent();
+ while (cont != null) {
+ if (cont.getParent() != null
+ && cont.getParent().getType() == IResource.PROJECT) {
+ if (cont.getName().equals("nl")) {
+ return (IFolder) cont;
+ }
+ return null;
+ }
+ cont = cont.getParent();
+ }
+ return null;
}
-
+
private static final IProject[] EMPTY_PROJECTS = new IProject[0];
-
+
/**
- * Searches in the workspace for plugins that are fragment that target
- * the current pde plugin.
+ * Searches in the workspace for plugins that are fragment that target the
+ * current pde plugin.
*
* @param openedFile
* @return
*/
protected static IProject[] collectTargetingFragments(IFile openedFile) {
- IProject thisProject = openedFile.getProject();
- if (thisProject == null) {
- return null;
- }
- Collection<IProject> projs = null;
- String bundleId = getBundleId(openedFile);
- try {
- //now look in the workspace for the host-plugin as a
- //developed project:
- IResource[] members =
- ((IContainer)thisProject.getParent()).members();
- for (int i = 0 ; i < members.length ; i++ ) {
- IResource childRes = members[i];
- if (childRes != thisProject
- && childRes.getType() == IResource.PROJECT) {
- String hostId = getHostPluginId(childRes);
- if (bundleId.equals(hostId)) {
- if (projs == null) {
- projs = new ArrayList<IProject>();
- }
- projs.add((IProject)childRes);
- }
- }
- }
- } catch (Exception e) {
-
- }
- return projs == null ? null
- : projs.toArray(EMPTY_PROJECTS);
+ IProject thisProject = openedFile.getProject();
+ if (thisProject == null) {
+ return null;
+ }
+ Collection<IProject> projs = null;
+ String bundleId = getBundleId(openedFile);
+ try {
+ // now look in the workspace for the host-plugin as a
+ // developed project:
+ IResource[] members = ((IContainer) thisProject.getParent())
+ .members();
+ for (int i = 0; i < members.length; i++) {
+ IResource childRes = members[i];
+ if (childRes != thisProject
+ && childRes.getType() == IResource.PROJECT) {
+ String hostId = getHostPluginId(childRes);
+ if (bundleId.equals(hostId)) {
+ if (projs == null) {
+ projs = new ArrayList<IProject>();
+ }
+ projs.add((IProject) childRes);
+ }
+ }
+ }
+ } catch (Exception e) {
+
+ }
+ return projs == null ? null : projs.toArray(EMPTY_PROJECTS);
}
-
-
-
+
}
-
\ No newline at end of file
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLFragmentBundleGroupStrategy.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLFragmentBundleGroupStrategy.java
index 2248b65..bee6650 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLFragmentBundleGroupStrategy.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLFragmentBundleGroupStrategy.java
@@ -54,12 +54,12 @@
import org.osgi.framework.Bundle;
/**
- * This strategy is used when a resource bundle that belongs to a plug-in fragment
- * project is loaded.
+ * This strategy is used when a resource bundle that belongs to a plug-in
+ * fragment project is loaded.
* <p>
* This class loads resource bundles following the default strategy. If no root
- * locale resource is found, it tries to locate that resource inside the
- * host plug-in of the fragment. The host plug-in is searched inside the workspace
+ * locale resource is found, it tries to locate that resource inside the host
+ * plug-in of the fragment. The host plug-in is searched inside the workspace
* first and if not found inside the Eclipse platform being run.
* <p>
* This is useful for the development of i18n packages for eclipse plug-ins: The
@@ -70,22 +70,22 @@
*
* @author Pascal Essiembre
* @author Hugues Malphettes
- * @see <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=214521">Bug 214521 - in the resource bundle editor take into account the resources of the "Host-Plugin" when opened bundle is in a plugin-fragment</a>
+ * @see <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=214521">Bug
+ * 214521 - in the resource bundle editor take into account the resources
+ * of the "Host-Plugin" when opened bundle is in a plugin-fragment</a>
*/
public class NLFragmentBundleGroupStrategy extends NLPluginBundleGroupStrategy {
-
- private final String _fragmentHostID;
-
- private boolean hostPluginInWorkspaceWasLookedFor = false;
- private IProject hostPluginInWorkspace;
-
-
- /**
+ private final String _fragmentHostID;
+
+ private boolean hostPluginInWorkspaceWasLookedFor = false;
+ private IProject hostPluginInWorkspace;
+
+ /**
*
*/
public NLFragmentBundleGroupStrategy(IEditorSite site, IFile file,
- String fragmentHostID, IFolder nlFolder) {
+ String fragmentHostID, IFolder nlFolder) {
super(site, file, nlFolder);
_fragmentHostID = fragmentHostID;
}
@@ -94,40 +94,40 @@
* @see org.eclipse.babel.core.bundle.IBundleGroupStrategy#loadBundles()
*/
public MessagesBundle[] loadMessagesBundles() {
- MessagesBundle[] defaultFiles = super.loadMessagesBundles();
- //look if the defaut properties is already in there.
- //if that is the case we don't try to load extra properties
- for (int i = 0 ; i < defaultFiles.length ; i++) {
- MessagesBundle mb = defaultFiles[i];
- if (UIUtils.ROOT_LOCALE.equals(mb.getLocale())
- || mb.getLocale() == null) {
- //... if this is the base one then no need to look any further.:
- return defaultFiles;
- }
- }
- try {
- MessagesBundle locatedBaseProperties = loadDefaultMessagesBundle();
- if (locatedBaseProperties != null) {
- MessagesBundle[] result =
- new MessagesBundle[defaultFiles.length+1];
- result[0] = locatedBaseProperties;
- System.arraycopy(
- defaultFiles, 0, result, 1, defaultFiles.length);
- return result;
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (CoreException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ MessagesBundle[] defaultFiles = super.loadMessagesBundles();
+ // look if the defaut properties is already in there.
+ // if that is the case we don't try to load extra properties
+ for (int i = 0; i < defaultFiles.length; i++) {
+ MessagesBundle mb = defaultFiles[i];
+ if (UIUtils.ROOT_LOCALE.equals(mb.getLocale())
+ || mb.getLocale() == null) {
+ // ... if this is the base one then no need to look any
+ // further.:
+ return defaultFiles;
+ }
+ }
+ try {
+ MessagesBundle locatedBaseProperties = loadDefaultMessagesBundle();
+ if (locatedBaseProperties != null) {
+ MessagesBundle[] result = new MessagesBundle[defaultFiles.length + 1];
+ result[0] = locatedBaseProperties;
+ System.arraycopy(defaultFiles, 0, result, 1,
+ defaultFiles.length);
+ return result;
+ }
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (CoreException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
return null;
}
/**
* @see org.eclipse.babel.core.bundle.IBundleGroupStrategy
- * #createBundle(java.util.Locale)
+ * #createBundle(java.util.Locale)
*/
public MessagesBundle createMessagesBundle(Locale locale) {
return super.createMessagesBundle(locale);
@@ -135,371 +135,382 @@
/**
* @see org.eclipse.babel.core.message.internal.strategy.IMessagesBundleGroupStrategy
- * #createMessagesBundleGroupName()
+ * #createMessagesBundleGroupName()
*/
public String createMessagesBundleGroupName() {
return super.createMessagesBundleGroupName();
}
-
-
/**
* @return The message bundle for the message.properties file associated to
- * the edited resource bundle once this code is executed by eclipse.
+ * the edited resource bundle once this code is executed by eclipse.
* @throws CoreException
- * @throws IOException
+ * @throws IOException
*/
- private MessagesBundle loadDefaultMessagesBundle()
- throws IOException, CoreException {
+ private MessagesBundle loadDefaultMessagesBundle() throws IOException,
+ CoreException {
IEditorInput newEditorInput = null;
IPath propertiesBasePath = getPropertiesPath();
- //look for the bundle with the given symbolic name.
- //first look into the workspace itself through the various pde projects
+ // look for the bundle with the given symbolic name.
+ // first look into the workspace itself through the various pde projects
String resourceLocationLabel = null;
- IProject developpedProject = getHostPluginProjectDevelopedInWorkspace();
- if (developpedProject != null) {
- IFile file = getPropertiesFile(
- developpedProject, propertiesBasePath);
- if (!file.exists()) {
- //try inside the jars:
- String[] jarredProps =
- getJarredPropertiesAndResourceLocationLabel(
- developpedProject, propertiesBasePath);
- if (jarredProps != null) {
- if (site == null) {
- //then we are currently executing a build,
- //not creating editors:
- MsgEditorPreferences prefs =
- MsgEditorPreferences.getInstance();
- return new MessagesBundle(
- new PropertiesReadOnlyResource(
- UIUtils.ROOT_LOCALE,
- new PropertiesSerializer(prefs.getSerializerConfig()),
- new PropertiesDeserializer(prefs.getDeserializerConfig()),
- jarredProps[0], jarredProps[1]));
- }
- newEditorInput = new DummyEditorInput(jarredProps[0],
- getPropertiesPath().lastSegment(),
- jarredProps[1]);
- resourceLocationLabel = jarredProps[1];
- }
- }
- //well if the file does not exist, it will be clear where we were
- //looking for it and that we could not find it
- if (site == null) {
- //then we are currently executing a build,
- //not creating editors:
- if (file.exists()) {
- MsgEditorPreferences prefs =
- MsgEditorPreferences.getInstance();
- return new MessagesBundle(new PropertiesIFileResource(
- UIUtils.ROOT_LOCALE,
- new PropertiesSerializer(prefs.getSerializerConfig()),
- new PropertiesDeserializer(prefs.getDeserializerConfig()), file,
- MessagesEditorPlugin.getDefault()));
- } else {
- //during the build if the file does not exist. skip.
- return null;
- }
- }
- if (file.exists()) {
- newEditorInput = new FileEditorInput(file);
- }
- //assume there is no more than one version of the plugin
- //in the same workspace.
- }
+ IProject developpedProject = getHostPluginProjectDevelopedInWorkspace();
+ if (developpedProject != null) {
+ IFile file = getPropertiesFile(developpedProject,
+ propertiesBasePath);
+ if (!file.exists()) {
+ // try inside the jars:
+ String[] jarredProps = getJarredPropertiesAndResourceLocationLabel(
+ developpedProject, propertiesBasePath);
+ if (jarredProps != null) {
+ if (site == null) {
+ // then we are currently executing a build,
+ // not creating editors:
+ MsgEditorPreferences prefs = MsgEditorPreferences
+ .getInstance();
+ return new MessagesBundle(
+ new PropertiesReadOnlyResource(
+ UIUtils.ROOT_LOCALE,
+ new PropertiesSerializer(prefs
+ .getSerializerConfig()),
+ new PropertiesDeserializer(prefs
+ .getDeserializerConfig()),
+ jarredProps[0], jarredProps[1]));
+ }
+ newEditorInput = new DummyEditorInput(jarredProps[0],
+ getPropertiesPath().lastSegment(), jarredProps[1]);
+ resourceLocationLabel = jarredProps[1];
+ }
+ }
+ // well if the file does not exist, it will be clear where we were
+ // looking for it and that we could not find it
+ if (site == null) {
+ // then we are currently executing a build,
+ // not creating editors:
+ if (file.exists()) {
+ MsgEditorPreferences prefs = MsgEditorPreferences
+ .getInstance();
+ return new MessagesBundle(new PropertiesIFileResource(
+ UIUtils.ROOT_LOCALE, new PropertiesSerializer(
+ prefs.getSerializerConfig()),
+ new PropertiesDeserializer(prefs
+ .getDeserializerConfig()), file,
+ MessagesEditorPlugin.getDefault()));
+ } else {
+ // during the build if the file does not exist. skip.
+ return null;
+ }
+ }
+ if (file.exists()) {
+ newEditorInput = new FileEditorInput(file);
+ }
+ // assume there is no more than one version of the plugin
+ // in the same workspace.
+ }
- //second look into the current platform.
+ // second look into the current platform.
if (newEditorInput == null) {
InputStream in = null;
String resourceName = null;
-
+
try {
-
- Bundle bundle = Platform.getBundle(_fragmentHostID);
- if (bundle != null) {
- //at this point there are 2 strategies:
- //use the osgi apis to look into the bundle's resources
- //or grab the physical artifact behind the bundle and dive
- //into it.
- resourceName = propertiesBasePath.toString();
- URL url = bundle.getEntry(resourceName);
- if (url != null) {
- in = url.openStream();
- resourceLocationLabel = url.toExternalForm();
- } else {
- //it seems this is unused. at least
- //we might need to transform the path into the name of
- //the properties for the classloader here.
- url = bundle.getResource(resourceName);
- if (url != null) {
- in = url.openStream();
- resourceLocationLabel = url.toExternalForm();
- }
- }
- }
-
- if (in != null) {
- String contents = getContents(in);
- if (site == null) {
- //then we are currently executing a build,
- //not creating editors:
- MsgEditorPreferences prefs =
- MsgEditorPreferences.getInstance();
- return new MessagesBundle(
- new PropertiesReadOnlyResource(
- UIUtils.ROOT_LOCALE,
- new PropertiesSerializer(prefs.getSerializerConfig()),
- new PropertiesDeserializer(prefs.getDeserializerConfig()),
- contents, resourceLocationLabel));
- }
- newEditorInput = new DummyEditorInput(contents,
- getPropertiesPath().lastSegment(),
- getPropertiesPath().toString());
- }
+
+ Bundle bundle = Platform.getBundle(_fragmentHostID);
+ if (bundle != null) {
+ // at this point there are 2 strategies:
+ // use the osgi apis to look into the bundle's resources
+ // or grab the physical artifact behind the bundle and dive
+ // into it.
+ resourceName = propertiesBasePath.toString();
+ URL url = bundle.getEntry(resourceName);
+ if (url != null) {
+ in = url.openStream();
+ resourceLocationLabel = url.toExternalForm();
+ } else {
+ // it seems this is unused. at least
+ // we might need to transform the path into the name of
+ // the properties for the classloader here.
+ url = bundle.getResource(resourceName);
+ if (url != null) {
+ in = url.openStream();
+ resourceLocationLabel = url.toExternalForm();
+ }
+ }
+ }
+
+ if (in != null) {
+ String contents = getContents(in);
+ if (site == null) {
+ // then we are currently executing a build,
+ // not creating editors:
+ MsgEditorPreferences prefs = MsgEditorPreferences
+ .getInstance();
+ return new MessagesBundle(
+ new PropertiesReadOnlyResource(
+ UIUtils.ROOT_LOCALE,
+ new PropertiesSerializer(prefs
+ .getSerializerConfig()),
+ new PropertiesDeserializer(prefs
+ .getDeserializerConfig()),
+ contents, resourceLocationLabel));
+ }
+ newEditorInput = new DummyEditorInput(contents,
+ getPropertiesPath().lastSegment(),
+ getPropertiesPath().toString());
+ }
} finally {
- if (in != null) try { in.close(); } catch (IOException ioe) {}
+ if (in != null)
+ try {
+ in.close();
+ } catch (IOException ioe) {
+ }
}
}
-
+
// if we found something that we could factor into a text editor input
// we create a text editor and the whole MessagesBundle.
if (newEditorInput != null) {
TextEditor textEditor = null;
if (site != null) {
- //during a build the site is not there and we don't edit things
- //anyways.
- //we need a new type of PropertiesEditorResource. not based on
- //file and ifile and
- //editorinput.
- try {
- // Use PropertiesFileEditor if available
- textEditor = (TextEditor) Class.forName(
- PROPERTIES_EDITOR_CLASS_NAME).newInstance();
- } catch (Exception e) {
- // Use default editor otherwise
- textEditor = new TextEditor();
- }
- textEditor.init(site, newEditorInput);
+ // during a build the site is not there and we don't edit things
+ // anyways.
+ // we need a new type of PropertiesEditorResource. not based on
+ // file and ifile and
+ // editorinput.
+ try {
+ // Use PropertiesFileEditor if available
+ textEditor = (TextEditor) Class.forName(
+ PROPERTIES_EDITOR_CLASS_NAME).newInstance();
+ } catch (Exception e) {
+ // Use default editor otherwise
+ textEditor = new TextEditor();
+ }
+ textEditor.init(site, newEditorInput);
} else {
- System.err.println("the site " + site);
+ System.err.println("the site " + site);
}
MsgEditorPreferences prefs = MsgEditorPreferences.getInstance();
-
- EclipsePropertiesEditorResource readOnly =
- new EclipsePropertiesEditorResource(UIUtils.ROOT_LOCALE,
- new PropertiesSerializer(prefs.getSerializerConfig()),
- new PropertiesDeserializer(prefs.getDeserializerConfig()), textEditor);
+
+ EclipsePropertiesEditorResource readOnly = new EclipsePropertiesEditorResource(
+ UIUtils.ROOT_LOCALE, new PropertiesSerializer(
+ prefs.getSerializerConfig()),
+ new PropertiesDeserializer(prefs.getDeserializerConfig()),
+ textEditor);
if (resourceLocationLabel != null) {
- readOnly.setResourceLocationLabel(resourceLocationLabel);
+ readOnly.setResourceLocationLabel(resourceLocationLabel);
}
return new MessagesBundle(readOnly);
}
// we did not find it.
- return null;
+ return null;
}
-
+
private String getContents(InputStream in) throws IOException {
- Reader reader = new BufferedReader(
- new InputStreamReader(in));
- //, "ISO 8859-1");need to find actual name
+ Reader reader = new BufferedReader(new InputStreamReader(in));
+ // , "ISO 8859-1");need to find actual name
int ch;
StringBuffer buffer = new StringBuffer();
while ((ch = reader.read()) > -1) {
- buffer.append((char)ch);
+ buffer.append((char) ch);
}
in.close();
return buffer.toString();
}
-
+
/**
- * The resource bundle can be either with the rest of the classes or
- * with the bundle resources.
+ * The resource bundle can be either with the rest of the classes or with
+ * the bundle resources.
+ *
* @return
*/
protected boolean resourceBundleIsInsideClasses() {
- IProject thisProj = getOpenedFile().getProject();
- Collection<String> srcs = getSourceFolderPathes(thisProj);
- String thisPath = getOpenedFile().getProjectRelativePath().toString();
- if (srcs != null) {
- for (String srcPath : srcs) {
- if (thisPath.startsWith(srcPath)) {
- return true;
- }
- }
- }
- return false;
+ IProject thisProj = getOpenedFile().getProject();
+ Collection<String> srcs = getSourceFolderPathes(thisProj);
+ String thisPath = getOpenedFile().getProjectRelativePath().toString();
+ if (srcs != null) {
+ for (String srcPath : srcs) {
+ if (thisPath.startsWith(srcPath)) {
+ return true;
+ }
+ }
+ }
+ return false;
}
-
+
/**
* @return The path of the base properties file. Relative to a source folder
- * or the root of the project if there is no source folder.
- * <p>
- * For example if the properties file is for the package
- * org.eclipse.ui.workbench.internal.messages.properties
- * The path return is org/eclipse/ui/workbench/internal/messages/properties
- * </p>
+ * or the root of the project if there is no source folder.
+ * <p>
+ * For example if the properties file is for the package
+ * org.eclipse.ui.workbench.internal.messages.properties The path
+ * return is org/eclipse/ui/workbench/internal/messages/properties
+ * </p>
*/
protected IPath getPropertiesPath() {
- IPath projRelative = super.basePathInsideNL == null
- ? super.getOpenedFile().getParent().getProjectRelativePath()
- : new Path(super.basePathInsideNL);
- return removePathToSourceFolder(projRelative)
- .append(getBaseName() + ".properties"); //NON-NLS-1$
+ IPath projRelative = super.basePathInsideNL == null ? super
+ .getOpenedFile().getParent().getProjectRelativePath()
+ : new Path(super.basePathInsideNL);
+ return removePathToSourceFolder(projRelative).append(
+ getBaseName() + ".properties"); // NON-NLS-1$
}
-
+
/**
- * @param hostPluginProject The project in the workspace that is the host
- * plugin
- * @param propertiesBasePath The result of getPropertiesPath();
+ * @param hostPluginProject
+ * The project in the workspace that is the host plugin
+ * @param propertiesBasePath
+ * The result of getPropertiesPath();
* @return
*/
- protected IFile getPropertiesFile(
- IProject hostPluginProject, IPath propertiesBasePath) {
- //first look directly in the plugin resources:
- IResource r = hostPluginProject.findMember(propertiesBasePath);
- if (r != null && r.getType() == IResource.FILE) {
- return (IFile)r;
- }
-
- //second look into the source folders.
- Collection<String> srcPathes = getSourceFolderPathes(hostPluginProject);
- if (srcPathes != null) {
- for (String srcPath : srcPathes) {
- IFolder srcFolder = hostPluginProject.getFolder(
- new Path(srcPath));
- if (srcFolder.exists()) {
- r = srcFolder.findMember(propertiesBasePath);
- if (r != null && r.getType() == IResource.FILE) {
- return (IFile)r;
- }
- }
- }
- }
- return hostPluginProject.getFile(propertiesBasePath);
+ protected IFile getPropertiesFile(IProject hostPluginProject,
+ IPath propertiesBasePath) {
+ // first look directly in the plugin resources:
+ IResource r = hostPluginProject.findMember(propertiesBasePath);
+ if (r != null && r.getType() == IResource.FILE) {
+ return (IFile) r;
+ }
+
+ // second look into the source folders.
+ Collection<String> srcPathes = getSourceFolderPathes(hostPluginProject);
+ if (srcPathes != null) {
+ for (String srcPath : srcPathes) {
+ IFolder srcFolder = hostPluginProject.getFolder(new Path(
+ srcPath));
+ if (srcFolder.exists()) {
+ r = srcFolder.findMember(propertiesBasePath);
+ if (r != null && r.getType() == IResource.FILE) {
+ return (IFile) r;
+ }
+ }
+ }
+ }
+ return hostPluginProject.getFile(propertiesBasePath);
}
+
/**
* Returns the content of the properties if they were located inside a jar
* inside the plugin.
*
* @param hostPluginProject
* @param propertiesBasePath
- * @return The content and location label of the properties or null if
- * they could not be found.
+ * @return The content and location label of the properties or null if they
+ * could not be found.
*/
private String[] getJarredPropertiesAndResourceLocationLabel(
IProject hostPluginProject, IPath propertiesBasePath) {
- //third look into the jars:
- Collection<String> libPathes = getLibPathes(hostPluginProject);
- if (libPathes != null) {
- String entryName = propertiesBasePath.toString();
- for (String libPath : libPathes) {
- if (libPath.endsWith(".jar")) {
- IFile jar = hostPluginProject.getFile(new Path(libPath));
- if (jar.exists()) {
- File file = jar.getRawLocation().toFile();
- if (file.exists()) {
- JarFile jf = null;
- try {
- jf = new JarFile(file);
- JarEntry je = jf.getJarEntry(entryName);
- if (je != null) {
- String content =
- getContents(jf.getInputStream(je));
- String location =
- jar.getFullPath().toString()
- + "!/" + entryName;
- return new String[] {content, location};
- }
- } catch (IOException e) {
-
- } finally {
- if (jf != null) {
- try {
- jf.close();
- } catch (IOException e) {
- // swallow
- }
- }
- }
- }
- }
- }
- }
- }
-
- return null;//could not find it.
+ // third look into the jars:
+ Collection<String> libPathes = getLibPathes(hostPluginProject);
+ if (libPathes != null) {
+ String entryName = propertiesBasePath.toString();
+ for (String libPath : libPathes) {
+ if (libPath.endsWith(".jar")) {
+ IFile jar = hostPluginProject.getFile(new Path(libPath));
+ if (jar.exists()) {
+ File file = jar.getRawLocation().toFile();
+ if (file.exists()) {
+ JarFile jf = null;
+ try {
+ jf = new JarFile(file);
+ JarEntry je = jf.getJarEntry(entryName);
+ if (je != null) {
+ String content = getContents(jf
+ .getInputStream(je));
+ String location = jar.getFullPath()
+ .toString() + "!/" + entryName;
+ return new String[] { content, location };
+ }
+ } catch (IOException e) {
+
+ } finally {
+ if (jf != null) {
+ try {
+ jf.close();
+ } catch (IOException e) {
+ // swallow
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return null;// could not find it.
}
-
+
/**
* Redo a little parser utility in order to not depend on pde.
*
* @param proj
- * @return The pathes of the source folders extracted from
- * the .classpath file
+ * @return The pathes of the source folders extracted from the .classpath
+ * file
*/
protected static Collection<String> getSourceFolderPathes(IProject proj) {
- return getClasspathEntryPathes(proj, "src"); //$NON-NLS-1$
+ return getClasspathEntryPathes(proj, "src"); //$NON-NLS-1$
}
+
/**
* Redo a little parser utility in order to not depend on pde.
*
* @param proj
- * @return The pathes of the source folders extracted from the
- * .classpath file
+ * @return The pathes of the source folders extracted from the .classpath
+ * file
*/
protected Collection<String> getLibPathes(IProject proj) {
- return getClasspathEntryPathes(proj, "lib"); //$NON-NLS-1$
+ return getClasspathEntryPathes(proj, "lib"); //$NON-NLS-1$
}
- protected static Collection<String> getClasspathEntryPathes(
- IProject proj, String classpathentryKind) {
- IFile classpathRes = proj.getFile(".classpath");
- if (!classpathRes.exists()) {
- return null;
- }
- Collection<String> res = new ArrayList<String>();
-
- //<classpathentry kind="src" path="src"/>
- InputStream in = null;
- try {
- in = ((IFile)classpathRes).getContents();
- //supposedly in utf-8. should not really matter for us
- Reader r = new InputStreamReader(in, "UTF-8");
- LineNumberReader lnr = new LineNumberReader(r);
- String line = lnr.readLine();
- while (line != null) {
- if (line.indexOf("<classpathentry ") != -1
- && line.indexOf(" kind=\"" + classpathentryKind + "\" ")
- != -1) {
- int pathIndex = line.indexOf(" path=\"");
- if (pathIndex != -1) {
- int secondQuoteIndex = line.indexOf('\"',
- pathIndex + " path=\"".length());
- if (secondQuoteIndex != -1) {
- res.add(line.substring(
- pathIndex + " path=\"".length(),
- secondQuoteIndex));
- }
- }
- }
- line = lnr.readLine();
- }
- lnr.close();
- r.close();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (in != null) try { in.close(); } catch (IOException e) {}
- }
- return res;
+
+ protected static Collection<String> getClasspathEntryPathes(IProject proj,
+ String classpathentryKind) {
+ IFile classpathRes = proj.getFile(".classpath");
+ if (!classpathRes.exists()) {
+ return null;
+ }
+ Collection<String> res = new ArrayList<String>();
+
+ // <classpathentry kind="src" path="src"/>
+ InputStream in = null;
+ try {
+ in = ((IFile) classpathRes).getContents();
+ // supposedly in utf-8. should not really matter for us
+ Reader r = new InputStreamReader(in, "UTF-8");
+ LineNumberReader lnr = new LineNumberReader(r);
+ String line = lnr.readLine();
+ while (line != null) {
+ if (line.indexOf("<classpathentry ") != -1
+ && line.indexOf(" kind=\"" + classpathentryKind + "\" ") != -1) {
+ int pathIndex = line.indexOf(" path=\"");
+ if (pathIndex != -1) {
+ int secondQuoteIndex = line.indexOf('\"', pathIndex
+ + " path=\"".length());
+ if (secondQuoteIndex != -1) {
+ res.add(line.substring(
+ pathIndex + " path=\"".length(),
+ secondQuoteIndex));
+ }
+ }
+ }
+ line = lnr.readLine();
+ }
+ lnr.close();
+ r.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (in != null)
+ try {
+ in.close();
+ } catch (IOException e) {
+ }
+ }
+ return res;
}
-
+
/**
- * A dummy editor input represents text that may be shown in a
- * text editor, but cannot be saved as it does not relate to a modifiable
- * file.
+ * A dummy editor input represents text that may be shown in a text editor,
+ * but cannot be saved as it does not relate to a modifiable file.
*/
private class DummyEditorInput implements IStorageEditorInput, IStorage {
@@ -507,7 +518,7 @@
* the error messages as a Java inputStream.
*/
private String _contents;
-
+
/**
* the name of the input
*/
@@ -517,23 +528,28 @@
* the tooltip text, optional
*/
private String _toolTipText;
-
+
/**
- * Simplified constructor that does not need
- * a tooltip, the name is used instead
+ * Simplified constructor that does not need a tooltip, the name is used
+ * instead
+ *
* @param contents
* @param _name
*/
- public DummyEditorInput(
- String contents, String name, boolean isEditable) {
+ public DummyEditorInput(String contents, String name, boolean isEditable) {
this(contents, name, name);
}
+
/**
* The complete constructor.
- * @param contents the contents to be given to the editor
- * @param _name the name of the input
- * @param tipText the text to be shown when a tooltip
- * is requested on the editor name part.
+ *
+ * @param contents
+ * the contents to be given to the editor
+ * @param _name
+ * the name of the input
+ * @param tipText
+ * the text to be shown when a tooltip is requested on the
+ * editor name part.
*/
public DummyEditorInput(String contents, String name, String tipText) {
super();
@@ -592,7 +608,7 @@
}
// the methods to implement as an IStorage object
-
+
/**
* the contents
*/
@@ -614,100 +630,100 @@
return true;
}
}
-
+
/**
- * Called when using an nl structure.
- * We need to find out whether the variant is in fact a folder.
- * If we locate a folder inside the project with this name we assume it is
- * not a variant.
+ * Called when using an nl structure. We need to find out whether the
+ * variant is in fact a folder. If we locate a folder inside the project
+ * with this name we assume it is not a variant.
* <p>
- * This method is overridden inside the NLFragment thing as we need to
- * check 2 projects over there:
- * the host-plugin project and the current project.
+ * This method is overridden inside the NLFragment thing as we need to check
+ * 2 projects over there: the host-plugin project and the current project.
* </p>
+ *
* @param possibleVariant
* @return
*/
protected boolean isExistingFirstFolderForDefaultLocale(String folderName) {
- IProject thisProject = getOpenedFile().getProject();
- if (thisProject == null) {
- return false;
- }
- boolean res = thisProject.getFolder(folderName).exists();
- if (res) {
- //that is in the same plugin.
- return true;
- }
- IProject developpedProject =
- getHostPluginProjectDevelopedInWorkspace();
- if (developpedProject != null) {
- res = developpedProject.getFolder(folderName).exists();
- if (res) {
- //that is in the same plugin.
- return true;
- }
- //we don't need to look in the jar:
- //when this method is called it is because we
- //are looking inside the nl folder which is never inside a source
- //folder or inside a jar.
- return false;
- }
- //ok no project in the workspace with this.
- //maybe in the bundle
- Bundle bundle = getHostPluginBundleInPlatform();
- if (bundle != null) {
- if (bundle.getEntry(folderName) != null) {
- return true;
- }
- }
-
- return false;
+ IProject thisProject = getOpenedFile().getProject();
+ if (thisProject == null) {
+ return false;
+ }
+ boolean res = thisProject.getFolder(folderName).exists();
+ if (res) {
+ // that is in the same plugin.
+ return true;
+ }
+ IProject developpedProject = getHostPluginProjectDevelopedInWorkspace();
+ if (developpedProject != null) {
+ res = developpedProject.getFolder(folderName).exists();
+ if (res) {
+ // that is in the same plugin.
+ return true;
+ }
+ // we don't need to look in the jar:
+ // when this method is called it is because we
+ // are looking inside the nl folder which is never inside a source
+ // folder or inside a jar.
+ return false;
+ }
+ // ok no project in the workspace with this.
+ // maybe in the bundle
+ Bundle bundle = getHostPluginBundleInPlatform();
+ if (bundle != null) {
+ if (bundle.getEntry(folderName) != null) {
+ return true;
+ }
+ }
+
+ return false;
}
-
+
/**
- * Look for the host plugin inside the workspace itself.
- * Caches the result.
+ * Look for the host plugin inside the workspace itself. Caches the result.
+ *
* @return
*/
private IProject getHostPluginProjectDevelopedInWorkspace() {
- if (hostPluginInWorkspaceWasLookedFor) {
- return hostPluginInWorkspace;
- } else {
- hostPluginInWorkspaceWasLookedFor = true;
- }
-
- IProject thisProject = getOpenedFile().getProject();
- if (thisProject == null) {
- return null;
- }
- try {
- //now look in the workspace for the host-plugin as a
- //developed project:
- IResource[] members =
- ((IContainer)thisProject.getParent()).members();
- for (int i = 0 ; i < members.length ; i++ ) {
- IResource childRes = members[i];
- if (childRes != thisProject
- && childRes.getType() == IResource.PROJECT) {
- String bundle = MessagesBundleGroupFactory.getBundleId(childRes);
- if (_fragmentHostID.equals(bundle)) {
- hostPluginInWorkspace = (IProject)childRes;
- return hostPluginInWorkspace;
- }
- }
- }
- //ok no project in the workspace with this.
- } catch (Exception e) {
-
- }
- return null;
- }
- private Bundle getHostPluginBundleInPlatform() {
- Bundle bundle = Platform.getBundle(_fragmentHostID);
- if (bundle != null) {
- return bundle;
+ if (hostPluginInWorkspaceWasLookedFor) {
+ return hostPluginInWorkspace;
+ } else {
+ hostPluginInWorkspaceWasLookedFor = true;
}
- return null;
+
+ IProject thisProject = getOpenedFile().getProject();
+ if (thisProject == null) {
+ return null;
+ }
+ try {
+ // now look in the workspace for the host-plugin as a
+ // developed project:
+ IResource[] members = ((IContainer) thisProject.getParent())
+ .members();
+ for (int i = 0; i < members.length; i++) {
+ IResource childRes = members[i];
+ if (childRes != thisProject
+ && childRes.getType() == IResource.PROJECT) {
+ String bundle = MessagesBundleGroupFactory
+ .getBundleId(childRes);
+ if (_fragmentHostID.equals(bundle)) {
+ hostPluginInWorkspace = (IProject) childRes;
+ return hostPluginInWorkspace;
+ }
+ }
+ }
+ // ok no project in the workspace with this.
+ } catch (Exception e) {
+
+ }
+ return null;
}
-
+
+ private Bundle getHostPluginBundleInPlatform() {
+ Bundle bundle = Platform.getBundle(_fragmentHostID);
+ if (bundle != null) {
+ return bundle;
+ }
+ return null;
+ }
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLPluginBundleGroupStrategy.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLPluginBundleGroupStrategy.java
index 2b44d37..614dcf5 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLPluginBundleGroupStrategy.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLPluginBundleGroupStrategy.java
@@ -31,19 +31,18 @@
import org.eclipse.core.runtime.Path;
import org.eclipse.ui.IEditorSite;
-
/**
- * MessagesBundle group strategies for dealing with Eclipse "NL"
- * directory structure within a plugin.
+ * MessagesBundle group strategies for dealing with Eclipse "NL" directory
+ * structure within a plugin.
* <p>
- * This class also falls back to the usual locales as suffixes
- * by calling the methods defined in DefaultBundleGroupStrategy.
- * It enables us to re-use directly this class to support loading resources located
- * inside a fragment. In other words:
- * this class is extended by {@link NLFragmentBundleGroupStrategy}.
+ * This class also falls back to the usual locales as suffixes by calling the
+ * methods defined in DefaultBundleGroupStrategy. It enables us to re-use
+ * directly this class to support loading resources located inside a fragment.
+ * In other words: this class is extended by
+ * {@link NLFragmentBundleGroupStrategy}.
* </p>
* <p>
- * Note it is unclear how
+ * Note it is unclear how
* <p>
*
*
@@ -51,52 +50,55 @@
* @author Hugues Malphettes
*/
public class NLPluginBundleGroupStrategy extends DefaultBundleGroupStrategy {
-
- private static Set<String> ISO_LANG_CODES = new HashSet<String>();
- private static Set<String> ISO_COUNTRY_CODES = new HashSet<String>();
- static {
- String[] isos = Locale.getISOLanguages();
- for (int i = 0; i < isos.length; i++) {
- ISO_LANG_CODES.add(isos[i]);
- }
- String[] isoc = Locale.getISOCountries();
- for (int i = 0; i < isoc.length; i++) {
- ISO_COUNTRY_CODES.add(isoc[i]);
- }
- }
- private IProject[] associatedFragmentProjects;
- protected IFolder nlFolder;
- protected String basePathInsideNL;
-
+ private static Set<String> ISO_LANG_CODES = new HashSet<String>();
+ private static Set<String> ISO_COUNTRY_CODES = new HashSet<String>();
+ static {
+ String[] isos = Locale.getISOLanguages();
+ for (int i = 0; i < isos.length; i++) {
+ ISO_LANG_CODES.add(isos[i]);
+ }
+ String[] isoc = Locale.getISOCountries();
+ for (int i = 0; i < isoc.length; i++) {
+ ISO_COUNTRY_CODES.add(isoc[i]);
+ }
+ }
+
+ private IProject[] associatedFragmentProjects;
+ protected IFolder nlFolder;
+ protected String basePathInsideNL;
+
/**
- * @param nlFolder when null, this strategy behaves just like
- * DefaultBundleGroupStrategy. Otherwise it is a localized file
- * using the "nl" folder. Most complete example found so far:
- * http://dev.eclipse.org/mhonarc/lists/babel-dev/msg00111.html
- * Although it applies to properties files too:
- * See figure 1 of:
- * http://www.eclipse.org/articles/Article-Speak-The-Local-Language/article.html
+ * @param nlFolder
+ * when null, this strategy behaves just like
+ * DefaultBundleGroupStrategy. Otherwise it is a localized file
+ * using the "nl" folder. Most complete example found so far:
+ * http://dev.eclipse.org/mhonarc/lists/babel-dev/msg00111.html
+ * Although it applies to properties files too: See figure 1 of:
+ * http
+ * ://www.eclipse.org/articles/Article-Speak-The-Local-Language
+ * /article.html
*/
public NLPluginBundleGroupStrategy(IEditorSite site, IFile file,
- IFolder nlFolder, IProject[] associatedFragmentProjects) {
+ IFolder nlFolder, IProject[] associatedFragmentProjects) {
super(site, file);
this.nlFolder = nlFolder;
this.associatedFragmentProjects = associatedFragmentProjects;
}
-
/**
- * @param nlFolder when null, this strategy behaves just like
- * DefaultBundleGroupStrategy. Otherwise it is a localized file
- * using the "nl" folder. Most complete example found so far:
- * http://dev.eclipse.org/mhonarc/lists/babel-dev/msg00111.html
- * Although it applies to properties files too:
- * See figure 1 of:
- * http://www.eclipse.org/articles/Article-Speak-The-Local-Language/article.html
+ * @param nlFolder
+ * when null, this strategy behaves just like
+ * DefaultBundleGroupStrategy. Otherwise it is a localized file
+ * using the "nl" folder. Most complete example found so far:
+ * http://dev.eclipse.org/mhonarc/lists/babel-dev/msg00111.html
+ * Although it applies to properties files too: See figure 1 of:
+ * http
+ * ://www.eclipse.org/articles/Article-Speak-The-Local-Language
+ * /article.html
*/
public NLPluginBundleGroupStrategy(IEditorSite site, IFile file,
- IFolder nlFolder) {
+ IFolder nlFolder) {
super(site, file);
this.nlFolder = nlFolder;
}
@@ -106,318 +108,329 @@
*/
public MessagesBundle[] loadMessagesBundles() {
final Collection<MessagesBundle> bundles = new ArrayList<MessagesBundle>();
- Collection<IFolder> nlFolders = nlFolder != null ? new ArrayList<IFolder>() : null;
- if (associatedFragmentProjects != null) {
- IPath basePath = null;
- //true when the file opened is located in a source folder.
- //in that case we don't support the nl structure
- //as at runtime it only applies to resources that ae no inside the classes.
- boolean fileIsInsideClasses = false;
- boolean fileHasLocaleSuffix = false;
- if (nlFolder == null) {
- //in that case the project relative path to the container
- //of the properties file is always the one here.
- basePath = removePathToSourceFolder(
- getOpenedFile().getParent().getProjectRelativePath());
- fileIsInsideClasses = !basePath.equals(
- getOpenedFile().getParent().getProjectRelativePath());
- fileHasLocaleSuffix = !getOpenedFile().getName().equals(
- super.getBaseName() + ".properties");
- if (!fileHasLocaleSuffix && !fileIsInsideClasses) {
- basePathInsideNL = basePath.toString();
- }
- } else {
- //the file opened is inside an nl folder.
- //this will compute the basePathInsideNL:
- extractLocale(getOpenedFile(), true);
- basePath = new Path(basePathInsideNL);
- }
-
- for (int i = 0; i < associatedFragmentProjects.length; i++) {
- IProject frag = associatedFragmentProjects[i];
- if (fileIsInsideClasses) {
- Collection<String> srcPathes = NLFragmentBundleGroupStrategy.getSourceFolderPathes(frag);
- if (srcPathes != null) {
- //for each source folder, collect the resources we can find
- //with the suffix scheme:
- for (String srcPath : srcPathes) {
- IPath container = new Path(srcPath).append(basePath);
- super.collectBundlesInContainer(getContainer(frag, basePath), bundles);
- }
- }
- //also search directly in the bundle:
- super.collectBundlesInContainer(getContainer(frag, basePath), bundles);
- } else {
- IFolder nl = frag.getFolder("nl");
- if (nl != null && nl.exists()) {
- if (nlFolders == null) {
- nlFolders = new ArrayList<IFolder>();
- }
- nlFolders.add(nl);
- }
- if (!fileHasLocaleSuffix) {
- //when the file is not inside nl and has no locale suffix
- //and is not inside the classes
- //it means we look both inside nl and with the suffix
- //based scheme:
- super.collectBundlesInContainer(getContainer(frag, basePath), bundles);
- }
- }
- }
-
- }
-
+ Collection<IFolder> nlFolders = nlFolder != null ? new ArrayList<IFolder>()
+ : null;
+ if (associatedFragmentProjects != null) {
+ IPath basePath = null;
+ // true when the file opened is located in a source folder.
+ // in that case we don't support the nl structure
+ // as at runtime it only applies to resources that ae no inside the
+ // classes.
+ boolean fileIsInsideClasses = false;
+ boolean fileHasLocaleSuffix = false;
+ if (nlFolder == null) {
+ // in that case the project relative path to the container
+ // of the properties file is always the one here.
+ basePath = removePathToSourceFolder(getOpenedFile().getParent()
+ .getProjectRelativePath());
+ fileIsInsideClasses = !basePath.equals(getOpenedFile()
+ .getParent().getProjectRelativePath());
+ fileHasLocaleSuffix = !getOpenedFile().getName().equals(
+ super.getBaseName() + ".properties");
+ if (!fileHasLocaleSuffix && !fileIsInsideClasses) {
+ basePathInsideNL = basePath.toString();
+ }
+ } else {
+ // the file opened is inside an nl folder.
+ // this will compute the basePathInsideNL:
+ extractLocale(getOpenedFile(), true);
+ basePath = new Path(basePathInsideNL);
+ }
+
+ for (int i = 0; i < associatedFragmentProjects.length; i++) {
+ IProject frag = associatedFragmentProjects[i];
+ if (fileIsInsideClasses) {
+ Collection<String> srcPathes = NLFragmentBundleGroupStrategy
+ .getSourceFolderPathes(frag);
+ if (srcPathes != null) {
+ // for each source folder, collect the resources we can
+ // find
+ // with the suffix scheme:
+ for (String srcPath : srcPathes) {
+ IPath container = new Path(srcPath)
+ .append(basePath);
+ super.collectBundlesInContainer(
+ getContainer(frag, basePath), bundles);
+ }
+ }
+ // also search directly in the bundle:
+ super.collectBundlesInContainer(
+ getContainer(frag, basePath), bundles);
+ } else {
+ IFolder nl = frag.getFolder("nl");
+ if (nl != null && nl.exists()) {
+ if (nlFolders == null) {
+ nlFolders = new ArrayList<IFolder>();
+ }
+ nlFolders.add(nl);
+ }
+ if (!fileHasLocaleSuffix) {
+ // when the file is not inside nl and has no locale
+ // suffix
+ // and is not inside the classes
+ // it means we look both inside nl and with the suffix
+ // based scheme:
+ super.collectBundlesInContainer(
+ getContainer(frag, basePath), bundles);
+ }
+ }
+ }
+
+ }
+
if (nlFolders == null) {
- collectBundlesInContainer(getOpenedFile().getParent(), bundles);
+ collectBundlesInContainer(getOpenedFile().getParent(), bundles);
return bundles.toArray(EMPTY_BUNDLES);
}
if (nlFolder != null) {
- nlFolders.add(nlFolder);
+ nlFolders.add(nlFolder);
}
- //get the nl directory.
- //navigate the entire directory from there
- //and look for the file with the same file names.
+ // get the nl directory.
+ // navigate the entire directory from there
+ // and look for the file with the same file names.
final String name = getOpenedFile().getName();
IResourceVisitor visitor = new IResourceVisitor() {
- public boolean visit(IResource resource) throws CoreException {
- if (resource.getType() == IResource.FILE
- && resource.getName().equals(name)
- && !getOpenedFile().equals(resource)) {
- Locale locale = extractLocale((IFile)resource, false);
- if (locale != null && UIUtils.isDisplayed(locale)) {
- bundles.add(createBundle(locale, resource));
- }
- }
- return true;
- }
+ public boolean visit(IResource resource) throws CoreException {
+ if (resource.getType() == IResource.FILE
+ && resource.getName().equals(name)
+ && !getOpenedFile().equals(resource)) {
+ Locale locale = extractLocale((IFile) resource, false);
+ if (locale != null && UIUtils.isDisplayed(locale)) {
+ bundles.add(createBundle(locale, resource));
+ }
+ }
+ return true;
+ }
};
try {
- Locale locale = extractLocale(getOpenedFile(), true);
+ Locale locale = extractLocale(getOpenedFile(), true);
if (UIUtils.isDisplayed(locale)) {
- bundles.add(createBundle(locale, getOpenedFile()));
+ bundles.add(createBundle(locale, getOpenedFile()));
}
for (IFolder nlFolder : nlFolders) {
- nlFolder.accept(visitor);
+ nlFolder.accept(visitor);
}
- } catch (CoreException e) {
- e.printStackTrace();
- }
- //also look for files based on the suffix mechanism
- //if we have located the root locale file:
- IContainer container = null;
- for (MessagesBundle mb : bundles) {
- if (mb.getLocale() == null || mb.getLocale().equals(UIUtils.ROOT_LOCALE)) {
- Object src = mb.getResource().getSource();
- if (src instanceof IFile) {
- container = ((IFile)src).getParent();
- }
- break;
- }
- }
- if (container != null) {
- super.collectBundlesInContainer(container, bundles);
- }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ // also look for files based on the suffix mechanism
+ // if we have located the root locale file:
+ IContainer container = null;
+ for (MessagesBundle mb : bundles) {
+ if (mb.getLocale() == null
+ || mb.getLocale().equals(UIUtils.ROOT_LOCALE)) {
+ Object src = mb.getResource().getSource();
+ if (src instanceof IFile) {
+ container = ((IFile) src).getParent();
+ }
+ break;
+ }
+ }
+ if (container != null) {
+ super.collectBundlesInContainer(container, bundles);
+ }
return bundles.toArray(EMPTY_BUNDLES);
}
-
- private static final IContainer getContainer(IProject proj, IPath containerPath) {
- if (containerPath.segmentCount() == 0) {
- return proj;
- }
- return proj.getFolder(containerPath);
+
+ private static final IContainer getContainer(IProject proj,
+ IPath containerPath) {
+ if (containerPath.segmentCount() == 0) {
+ return proj;
+ }
+ return proj.getFolder(containerPath);
}
-
+
/**
* @param baseContainerPath
* @return if the path starts with a path to a source folder this method
- * returns the same path minus the source folder.
+ * returns the same path minus the source folder.
*/
protected IPath removePathToSourceFolder(IPath baseContainerPath) {
- Collection<String> srcPathes = NLFragmentBundleGroupStrategy.getSourceFolderPathes(
- getOpenedFile().getProject());
- if (srcPathes == null) {
- return baseContainerPath;
- }
- String projRelativePathStr = baseContainerPath.toString();
- for (String srcPath : srcPathes) {
- if (projRelativePathStr.startsWith(srcPath)) {
- return new Path(projRelativePathStr.substring(srcPath.length()));
- }
- }
- return baseContainerPath;
+ Collection<String> srcPathes = NLFragmentBundleGroupStrategy
+ .getSourceFolderPathes(getOpenedFile().getProject());
+ if (srcPathes == null) {
+ return baseContainerPath;
+ }
+ String projRelativePathStr = baseContainerPath.toString();
+ for (String srcPath : srcPathes) {
+ if (projRelativePathStr.startsWith(srcPath)) {
+ return new Path(projRelativePathStr.substring(srcPath.length()));
+ }
+ }
+ return baseContainerPath;
}
-
/**
- * Tries to parse a locale directly from the file.
- * Support the locale as a string suffix and the locale as part of a path
- * inside an nl folder.
+ * Tries to parse a locale directly from the file. Support the locale as a
+ * string suffix and the locale as part of a path inside an nl folder.
+ *
* @param file
- * @return The parsed locale or null if no locale could be parsed.
- * If the locale is the root locale UIBableUtils.ROOT_LOCALE is returned.
+ * @return The parsed locale or null if no locale could be parsed. If the
+ * locale is the root locale UIBableUtils.ROOT_LOCALE is returned.
*/
private Locale extractLocale(IFile file, boolean docomputeBasePath) {
- IFolder nl = MessagesBundleGroupFactory.getNLFolder(file);
- String path = file.getFullPath().removeFileExtension().toString();
- if (nl == null) {
- int ind = path.indexOf('_');
- int maxInd = path.length()-1;
- while (ind != -1 && ind < maxInd) {
- String possibleLocale = path.substring(ind+1);
- Locale res = BabelUtils.parseLocale(possibleLocale);
- if (res != null) {
- return res;
- }
- ind = path.indexOf('_', ind+1);
- }
-
- return null;
- }
- //the locale is not in the suffix.
- //let's look into the nl folder:
- int ind = path.lastIndexOf("/nl/");
- //so the remaining String is a composition of the base path of
- //the default properties and the path that reflects the locale.
- //for example:
- //if the default file is /theproject/icons/img.gif
- //then the french localized file is /theproject/nl/FR/icons/img.gif
- //so we need to separate fr from icons/img.gif to locate the base file.
- //unfortunately we need to look into the values of the tokens
- //to guess whether they are part of the path leading to the default file
- //or part of the path that reflects the locale.
- //we simply look whether 'icons' exist.
-
- // in other words: using folders is risky and users could
- //crash eclipse using locales that conflict with pathes to resources.
-
- //so we must verify that the first 2 or 3 tokens after nl are valid ISO codes.
- //the variant is the most problematic issue
- //as it is not standardized.
-
- //we rely on finding the base properties
- //to decide whether 'icons' is a variant or a folder.
-
-
-
- if (ind != -1) {
- ind = ind + "/nl/".length();
- int lastFolder = path.lastIndexOf('/');
- if (lastFolder == ind) {
- return UIUtils.ROOT_LOCALE;
- }
- path = path.substring(ind, lastFolder);
- StringTokenizer tokens = new StringTokenizer(path, "/", false);
- switch (tokens.countTokens()) {
- case 0:
- return null;
- case 1:
- String lang = tokens.nextToken();
+ IFolder nl = MessagesBundleGroupFactory.getNLFolder(file);
+ String path = file.getFullPath().removeFileExtension().toString();
+ if (nl == null) {
+ int ind = path.indexOf('_');
+ int maxInd = path.length() - 1;
+ while (ind != -1 && ind < maxInd) {
+ String possibleLocale = path.substring(ind + 1);
+ Locale res = BabelUtils.parseLocale(possibleLocale);
+ if (res != null) {
+ return res;
+ }
+ ind = path.indexOf('_', ind + 1);
+ }
+
+ return null;
+ }
+ // the locale is not in the suffix.
+ // let's look into the nl folder:
+ int ind = path.lastIndexOf("/nl/");
+ // so the remaining String is a composition of the base path of
+ // the default properties and the path that reflects the locale.
+ // for example:
+ // if the default file is /theproject/icons/img.gif
+ // then the french localized file is /theproject/nl/FR/icons/img.gif
+ // so we need to separate fr from icons/img.gif to locate the base file.
+ // unfortunately we need to look into the values of the tokens
+ // to guess whether they are part of the path leading to the default
+ // file
+ // or part of the path that reflects the locale.
+ // we simply look whether 'icons' exist.
+
+ // in other words: using folders is risky and users could
+ // crash eclipse using locales that conflict with pathes to resources.
+
+ // so we must verify that the first 2 or 3 tokens after nl are valid ISO
+ // codes.
+ // the variant is the most problematic issue
+ // as it is not standardized.
+
+ // we rely on finding the base properties
+ // to decide whether 'icons' is a variant or a folder.
+
+ if (ind != -1) {
+ ind = ind + "/nl/".length();
+ int lastFolder = path.lastIndexOf('/');
+ if (lastFolder == ind) {
+ return UIUtils.ROOT_LOCALE;
+ }
+ path = path.substring(ind, lastFolder);
+ StringTokenizer tokens = new StringTokenizer(path, "/", false);
+ switch (tokens.countTokens()) {
+ case 0:
+ return null;
+ case 1:
+ String lang = tokens.nextToken();
if (!ISO_LANG_CODES.contains(lang)) {
- return null;
- }
+ return null;
+ }
if (docomputeBasePath) {
- basePathInsideNL = "";
- return new Locale(lang);
+ basePathInsideNL = "";
+ return new Locale(lang);
} else if ("".equals(basePathInsideNL)) {
- return new Locale(lang);
+ return new Locale(lang);
} else {
- return null;
+ return null;
}
case 2:
- lang = tokens.nextToken();
- if (!ISO_LANG_CODES.contains(lang)) {
- return null;
- }
- String country = tokens.nextToken();
- if (!ISO_COUNTRY_CODES.contains(country)) {
- //in this case, this might be the beginning
- //of the base path.
- if (isExistingFirstFolderForDefaultLocale(country)) {
- if (docomputeBasePath) {
- basePathInsideNL = country;
- return new Locale(lang);
- } else if (basePathInsideNL.equals(country)) {
- return new Locale(lang);
- } else {
- return null;
- }
- }
- }
+ lang = tokens.nextToken();
+ if (!ISO_LANG_CODES.contains(lang)) {
+ return null;
+ }
+ String country = tokens.nextToken();
+ if (!ISO_COUNTRY_CODES.contains(country)) {
+ // in this case, this might be the beginning
+ // of the base path.
+ if (isExistingFirstFolderForDefaultLocale(country)) {
+ if (docomputeBasePath) {
+ basePathInsideNL = country;
+ return new Locale(lang);
+ } else if (basePathInsideNL.equals(country)) {
+ return new Locale(lang);
+ } else {
+ return null;
+ }
+ }
+ }
if (docomputeBasePath) {
- basePathInsideNL = "";
- return new Locale(lang, country);
+ basePathInsideNL = "";
+ return new Locale(lang, country);
} else if (basePathInsideNL.equals(country)) {
- return new Locale(lang, country);
+ return new Locale(lang, country);
} else {
- return null;
+ return null;
}
default:
- lang = tokens.nextToken();
- if (!ISO_LANG_CODES.contains(lang)) {
- return null;
- }
- country = tokens.nextToken();
- if (!ISO_COUNTRY_CODES.contains(country)) {
- if (isExistingFirstFolderForDefaultLocale(country)) {
- StringBuffer b = new StringBuffer(country);
- while (tokens.hasMoreTokens()) {
- b.append("/" + tokens.nextToken());
- }
- if (docomputeBasePath) {
- basePathInsideNL = b.toString();
- return new Locale(lang);
- } else if (basePathInsideNL.equals(b.toString())) {
- return new Locale(lang);
- } else {
- return null;
- }
- }
- }
- String variant = tokens.nextToken();
- if (isExistingFirstFolderForDefaultLocale(variant)) {
- StringBuffer b = new StringBuffer(variant);
- while (tokens.hasMoreTokens()) {
- b.append("/" + tokens.nextToken());
- }
- if (docomputeBasePath) {
- basePathInsideNL = b.toString();
- return new Locale(lang, country);
- } else if (basePathInsideNL.equals(b.toString())) {
- return new Locale(lang);
- } else {
- return null;
- }
- }
- StringBuffer b = new StringBuffer();
- while (tokens.hasMoreTokens()) {
- b.append("/" + tokens.nextToken());
- }
- if (docomputeBasePath) {
- basePathInsideNL = b.toString();
- return new Locale(lang, country, variant);
- } else if (basePathInsideNL.equals(b.toString())) {
- return new Locale(lang);
- } else {
- return null;
+ lang = tokens.nextToken();
+ if (!ISO_LANG_CODES.contains(lang)) {
+ return null;
}
- }
- }
- return UIUtils.ROOT_LOCALE;
+ country = tokens.nextToken();
+ if (!ISO_COUNTRY_CODES.contains(country)) {
+ if (isExistingFirstFolderForDefaultLocale(country)) {
+ StringBuffer b = new StringBuffer(country);
+ while (tokens.hasMoreTokens()) {
+ b.append("/" + tokens.nextToken());
+ }
+ if (docomputeBasePath) {
+ basePathInsideNL = b.toString();
+ return new Locale(lang);
+ } else if (basePathInsideNL.equals(b.toString())) {
+ return new Locale(lang);
+ } else {
+ return null;
+ }
+ }
+ }
+ String variant = tokens.nextToken();
+ if (isExistingFirstFolderForDefaultLocale(variant)) {
+ StringBuffer b = new StringBuffer(variant);
+ while (tokens.hasMoreTokens()) {
+ b.append("/" + tokens.nextToken());
+ }
+ if (docomputeBasePath) {
+ basePathInsideNL = b.toString();
+ return new Locale(lang, country);
+ } else if (basePathInsideNL.equals(b.toString())) {
+ return new Locale(lang);
+ } else {
+ return null;
+ }
+ }
+ StringBuffer b = new StringBuffer();
+ while (tokens.hasMoreTokens()) {
+ b.append("/" + tokens.nextToken());
+ }
+ if (docomputeBasePath) {
+ basePathInsideNL = b.toString();
+ return new Locale(lang, country, variant);
+ } else if (basePathInsideNL.equals(b.toString())) {
+ return new Locale(lang);
+ } else {
+ return null;
+ }
+ }
+ }
+ return UIUtils.ROOT_LOCALE;
}
-
+
/**
* Called when using an nl structure.<br/>
- * We need to find out whether the variant is in fact a folder.
- * If we locate a folder inside the project with this name we assume it is not a variant.
+ * We need to find out whether the variant is in fact a folder. If we locate
+ * a folder inside the project with this name we assume it is not a variant.
* <p>
* This method is overridden inside the NLFragment thing as we need to check
* 2 projects over there: the host-plugin project and the current project.
* </p>
+ *
* @param possibleVariant
* @return
*/
protected boolean isExistingFirstFolderForDefaultLocale(String folderName) {
- return getOpenedFile().getProject().getFolder(folderName).exists();
+ return getOpenedFile().getProject().getFolder(folderName).exists();
}
-
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryLeftBanner.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryLeftBanner.java
index dd9ec5b..a32a9c9 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryLeftBanner.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryLeftBanner.java
@@ -28,47 +28,50 @@
/**
* Tree for displaying and navigating through resource bundle keys.
+ *
* @author Pascal Essiembre
*/
public class EntryLeftBanner extends Composite {
/**
* Constructor.
- * @param parent parent composite
- * @param keyTree key tree
+ *
+ * @param parent
+ * parent composite
+ * @param keyTree
+ * key tree
*/
- public EntryLeftBanner(
- Composite parent,
- final I18NEntry i18NEntry) {
+ public EntryLeftBanner(Composite parent, final I18NEntry i18NEntry) {
super(parent, SWT.NONE);
-
+
RowLayout layout = new RowLayout();
setLayout(layout);
layout.marginBottom = 0;
layout.marginLeft = 0;
layout.marginRight = 0;
layout.marginTop = 0;
-
+
final IAction foldAction = new FoldingAction(i18NEntry);
new ActionButton(this, foldAction);
-// Button commentButton = new Button(compos, SWT.TOGGLE);
-// commentButton.setImage(UIUtils.getImage("comment.gif"));
-
-
+ // Button commentButton = new Button(compos, SWT.TOGGLE);
+ // commentButton.setImage(UIUtils.getImage("comment.gif"));
+
Link localeLabel = new Link(this, SWT.NONE);
localeLabel.setFont(UIUtils.createFont(localeLabel, SWT.BOLD));
-
+
boolean isEditable = i18NEntry.isEditable();
- localeLabel.setText("<a>" + UIUtils.getDisplayName(
- i18NEntry.getLocale()) + "</a>" + (!isEditable
- ? " (" + MessagesEditorPlugin.getString(
- "editor.readOnly") + ")" : ""));
-
- localeLabel.setToolTipText(
- MessagesEditorPlugin.getString("editor.i18nentry.resourcelocation",
- i18NEntry.getResourceLocationLabel())); //$NON-NLS-1$
-
+ localeLabel.setText("<a>"
+ + UIUtils.getDisplayName(i18NEntry.getLocale())
+ + "</a>"
+ + (!isEditable ? " ("
+ + MessagesEditorPlugin.getString("editor.readOnly")
+ + ")" : ""));
+
+ localeLabel.setToolTipText(MessagesEditorPlugin.getString(
+ "editor.i18nentry.resourcelocation",
+ i18NEntry.getResourceLocationLabel())); //$NON-NLS-1$
+
localeLabel.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
i18NEntry.getResourceBundleEditor().setActivePage(
@@ -76,8 +79,8 @@
}
});
- //TODO have "show country flags" in preferences.
- //TODO have text aligned bottom next to flag icon.
+ // TODO have "show country flags" in preferences.
+ // TODO have text aligned bottom next to flag icon.
Image countryIcon = loadCountryIcon(i18NEntry.getLocale());
if (countryIcon != null) {
Label imgLabel = new Label(this, SWT.NONE);
@@ -85,10 +88,11 @@
}
}
-
/**
* Loads country icon based on locale country.
- * @param countryLocale the locale on which to grab the country
+ *
+ * @param countryLocale
+ * the locale on which to grab the country
* @return an image, or <code>null</code> if no match could be made
*/
private Image loadCountryIcon(Locale countryLocale) {
@@ -102,9 +106,9 @@
countryCode.toLowerCase() + ".gif"; //$NON-NLS-1$
image = UIUtils.getImage(imageName);
}
-// if (image == null) {
-// image = UIUtils.getImage("countries/blank.gif"); //$NON-NLS-1$
-// }
+ // if (image == null) {
+ // image = UIUtils.getImage("countries/blank.gif"); //$NON-NLS-1$
+ // }
return image;
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryRightBanner.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryRightBanner.java
index 1cd28cb..e13feb7 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryRightBanner.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryRightBanner.java
@@ -35,6 +35,7 @@
/**
* Tree for displaying and navigating through resource bundle keys.
+ *
* @author Pascal Essiembre
*/
public class EntryRightBanner extends Composite {
@@ -46,20 +47,21 @@
private final MessagesEditor editor;
private final I18NEntry i18nEntry;
private final Locale locale;
-
+
/**
* Constructor.
- * @param parent parent composite
- * @param keyTree key tree
+ *
+ * @param parent
+ * parent composite
+ * @param keyTree
+ * key tree
*/
- public EntryRightBanner(
- Composite parent,
- final I18NEntry i18nEntry) {
+ public EntryRightBanner(Composite parent, final I18NEntry i18nEntry) {
super(parent, SWT.NONE);
this.i18nEntry = i18nEntry;
this.locale = i18nEntry.getLocale();
this.editor = i18nEntry.getResourceBundleEditor();
-
+
RowLayout layout = new RowLayout();
setLayout(layout);
layout.marginBottom = 0;
@@ -68,21 +70,19 @@
layout.marginTop = 0;
warningIcon = new Label(this, SWT.NONE);
- warningIcon.setImage(
- PlatformUI.getWorkbench().getSharedImages().getImage(
- ISharedImages.IMG_OBJS_WARN_TSK));
+ warningIcon.setImage(PlatformUI.getWorkbench().getSharedImages()
+ .getImage(ISharedImages.IMG_OBJS_WARN_TSK));
warningIcon.setVisible(false);
warningIcon.setToolTipText("This locale has warnings.");
-
+
colon = new Label(this, SWT.NONE);
colon.setText(":");
colon.setVisible(false);
toolBarMgr.createControl(this);
toolBarMgr.update(true);
-
- editor.addChangeListener(
- new MessagesEditorChangeAdapter() {
+
+ editor.addChangeListener(new MessagesEditorChangeAdapter() {
public void selectedKeyChanged(String oldKey, String newKey) {
updateMarkers();
@@ -100,46 +100,45 @@
* @param colon
*/
private void updateMarkers() {
- PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable () {
+ PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
-// if (!PlatformUI.getWorkbench().getDisplay().isDisposed()
-// && !editor.getMarkerManager().isDisposed()) {
- boolean isMarked = false;
- toolBarMgr.removeAll();
- actionByMarkerIds.clear();
- String key = editor.getSelectedKey();
- Collection<IMessageCheck> checks = editor.getMarkers().getFailedChecks(
- key, locale);
- if (checks != null) {
- for (IMessageCheck check : checks) {
- Action action = getCheckAction(key, check);
- if (action != null) {
- toolBarMgr.add(action);
- toolBarMgr.update(true);
- getParent().layout(true, true);
- isMarked = true;
- }
- }
+ // if (!PlatformUI.getWorkbench().getDisplay().isDisposed()
+ // && !editor.getMarkerManager().isDisposed()) {
+ boolean isMarked = false;
+ toolBarMgr.removeAll();
+ actionByMarkerIds.clear();
+ String key = editor.getSelectedKey();
+ Collection<IMessageCheck> checks = editor.getMarkers()
+ .getFailedChecks(key, locale);
+ if (checks != null) {
+ for (IMessageCheck check : checks) {
+ Action action = getCheckAction(key, check);
+ if (action != null) {
+ toolBarMgr.add(action);
+ toolBarMgr.update(true);
+ getParent().layout(true, true);
+ isMarked = true;
+ }
}
- toolBarMgr.update(true);
- getParent().layout(true, true);
-
- warningIcon.setVisible(isMarked);
- colon.setVisible(isMarked);
}
-// }
+ toolBarMgr.update(true);
+ getParent().layout(true, true);
+
+ warningIcon.setVisible(isMarked);
+ colon.setVisible(isMarked);
+ }
+ // }
});
-
+
}
-
- private Action getCheckAction(
- String key, IMessageCheck check) {
+
+ private Action getCheckAction(String key, IMessageCheck check) {
if (check instanceof MissingValueCheck) {
return new ShowMissingAction(key, locale);
} else if (check instanceof DuplicateValueCheck) {
return new ShowDuplicateAction(
- ((DuplicateValueCheck) check).getDuplicateKeys(),
- key, locale);
+ ((DuplicateValueCheck) check).getDuplicateKeys(), key,
+ locale);
}
return null;
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NEntry.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NEntry.java
index 13c789b..79e865c 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NEntry.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NEntry.java
@@ -39,6 +39,7 @@
/**
* Tree for displaying and navigating through resource bundle keys.
+ *
* @author Pascal Essiembre
*/
public class I18NEntry extends Composite {
@@ -52,23 +53,24 @@
private NullableText textBox;
private CBanner banner;
private String focusGainedText;
-
+
/**
* Constructor.
- * @param parent parent composite
- * @param keyTree key tree
+ *
+ * @param parent
+ * parent composite
+ * @param keyTree
+ * key tree
*/
- public I18NEntry(
- Composite parent,
- final MessagesEditor editor,
+ public I18NEntry(Composite parent, final MessagesEditor editor,
final Locale locale) {
super(parent, SWT.NONE);
this.editor = editor;
this.locale = locale;
this.bundleGroupId = editor.getBundleGroup().getResourceBundleId();
this.projectName = editor.getBundleGroup().getProjectName();
-
- GridLayout gridLayout = new GridLayout(1, false);
+
+ GridLayout gridLayout = new GridLayout(1, false);
gridLayout.horizontalSpacing = 0;
gridLayout.verticalSpacing = 0;
gridLayout.marginWidth = 0;
@@ -76,211 +78,206 @@
setLayout(gridLayout);
GridData gd = new GridData(GridData.FILL_BOTH);
-// gd.heightHint = 80;
+ // gd.heightHint = 80;
setLayoutData(gd);
banner = new CBanner(this, SWT.NONE);
Control bannerLeft = new EntryLeftBanner(banner, this);// createBannerLeft(banner);
Control bannerRight = new EntryRightBanner(banner, this);// createBannerRight(banner);
-
+
GridData gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.grabExcessHorizontalSpace = true;
-
+
banner.setLeft(bannerLeft);
banner.setRight(bannerRight);
-// banner.setRightWidth(300);
+ // banner.setRightWidth(300);
banner.setSimple(false);
banner.setLayoutData(gridData);
-
createTextbox();
-
+
}
-
-
-
public MessagesEditor getResourceBundleEditor() {
return editor;
}
-
-
-
+
public void setExpanded(boolean expanded) {
this.expanded = expanded;
textBox.setVisible(expanded);
-
+
if (expanded) {
- GridData gridData = new GridData();
- gridData.verticalAlignment = GridData.FILL;
- gridData.grabExcessVerticalSpace = true;
- gridData.horizontalAlignment = GridData.FILL;
- gridData.grabExcessHorizontalSpace = true;
- gridData.heightHint = UIUtils.getHeightInChars(textBox, 3);
- textBox.setLayoutData(gridData);
-
- GridData gd = new GridData(GridData.FILL_BOTH);
-// gd.heightHint = 80;
- setLayoutData(gd);
- getParent().pack();
- getParent().layout(true, true);
-
+ GridData gridData = new GridData();
+ gridData.verticalAlignment = GridData.FILL;
+ gridData.grabExcessVerticalSpace = true;
+ gridData.horizontalAlignment = GridData.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ gridData.heightHint = UIUtils.getHeightInChars(textBox, 3);
+ textBox.setLayoutData(gridData);
+
+ GridData gd = new GridData(GridData.FILL_BOTH);
+ // gd.heightHint = 80;
+ setLayoutData(gd);
+ getParent().pack();
+ getParent().layout(true, true);
+
} else {
- GridData gridData = ((GridData) textBox.getLayoutData());
- gridData.verticalAlignment = GridData.BEGINNING;
- gridData.grabExcessVerticalSpace = false;
- textBox.setLayoutData(gridData);
-
- gridData = (GridData) getLayoutData();
- gridData.heightHint = banner.getSize().y;
- gridData.verticalAlignment = GridData.BEGINNING;
- gridData.grabExcessVerticalSpace = false;
- setLayoutData(gridData);
-
- getParent().pack();
- getParent().layout(true, true);
+ GridData gridData = ((GridData) textBox.getLayoutData());
+ gridData.verticalAlignment = GridData.BEGINNING;
+ gridData.grabExcessVerticalSpace = false;
+ textBox.setLayoutData(gridData);
+
+ gridData = (GridData) getLayoutData();
+ gridData.heightHint = banner.getSize().y;
+ gridData.verticalAlignment = GridData.BEGINNING;
+ gridData.grabExcessVerticalSpace = false;
+ setLayoutData(gridData);
+
+ getParent().pack();
+ getParent().layout(true, true);
}
-
+
}
+
public boolean getExpanded() {
return expanded;
}
-
+
public Locale getLocale() {
return locale;
}
-
+
public boolean isEditable() {
- IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(projectName).getMessagesBundleGroup(bundleGroupId);
+ IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(
+ projectName).getMessagesBundleGroup(bundleGroupId);
IMessagesBundle bundle = messagesBundleGroup.getMessagesBundle(locale);
- return ((TextEditor) bundle.getResource().getSource()).isEditable();
+ return ((TextEditor) bundle.getResource().getSource()).isEditable();
}
-
+
public String getResourceLocationLabel() {
- IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(projectName).getMessagesBundleGroup(bundleGroupId);
- IMessagesBundle bundle = messagesBundleGroup.getMessagesBundle(locale);
- return bundle.getResource().getResourceLocationLabel();
+ IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(
+ projectName).getMessagesBundleGroup(bundleGroupId);
+ IMessagesBundle bundle = messagesBundleGroup.getMessagesBundle(locale);
+ return bundle.getResource().getResourceLocationLabel();
}
-
-// /*default*/ Text getTextBox() {
-// return textBox;
-// }
-
+
+ // /*default*/ Text getTextBox() {
+ // return textBox;
+ // }
/**
* @param editor
* @param locale
*/
private void createTextbox() {
- textBox = new NullableText(
- this, SWT.MULTI | SWT.WRAP |
- SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
+ textBox = new NullableText(this, SWT.MULTI | SWT.WRAP | SWT.H_SCROLL
+ | SWT.V_SCROLL | SWT.BORDER);
textBox.setEnabled(false);
textBox.setOrientation(UIUtils.getOrientation(locale));
-
textBox.addFocusListener(new FocusListener() {
- public void focusGained(FocusEvent event) {
- focusGainedText = textBox.getText();
- }
- public void focusLost(FocusEvent event) {
+ public void focusGained(FocusEvent event) {
+ focusGainedText = textBox.getText();
+ }
+
+ public void focusLost(FocusEvent event) {
updateModel();
- }
+ }
});
- //-- Setup read-only textbox --
- //that is the case if the corresponding editor is itself read-only.
- //it happens when the corresponding resource is defined inside the
- //target-platform for example
+ // -- Setup read-only textbox --
+ // that is the case if the corresponding editor is itself read-only.
+ // it happens when the corresponding resource is defined inside the
+ // target-platform for example
textBox.setEditable(isEditable());
-
- //--- Handle tab key ---
- //TODO add a preference property listener and add/remove this listener
+
+ // --- Handle tab key ---
+ // TODO add a preference property listener and add/remove this listener
textBox.addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent event) {
-// if (!MsgEditorPreferences.getFieldTabInserts()
-// && event.character == SWT.TAB) {
-// event.doit = true;
-// }
+ // if (!MsgEditorPreferences.getFieldTabInserts()
+ // && event.character == SWT.TAB) {
+ // event.doit = true;
+ // }
}
});
// Handle dirtyness
textBox.addKeyListener(new KeyAdapter() {
- public void keyReleased(KeyEvent event) {
- // Text field has changed: make editor dirty if not already
- if (!BabelUtils.equals(focusGainedText, textBox.getText())) {
- // Make the editor dirty if not already. If it is,
- // we wait until field focus lost (or save) to
- // update it completely.
- if (!editor.isDirty()) {
-// textEditor.isDirty();
- updateModel();
-// int caretPosition = eventBox.getCaretPosition();
-// updateBundleOnChanges();
-// eventBox.setSelection(caretPosition);
- }
- //autoDetectRequiredFont(eventBox.getText());
- }
- }
- });
-// // Eric Fettweis : new listener to automatically change the font
-// textBox.addModifyListener(new ModifyListener() {
-//
-// public void modifyText(ModifyEvent e) {
-// String text = textBox.getText();
-// Font f = textBox.getFont();
-// String fontName = getBestFont(f.getFontData()[0].getName(), text);
-// if(fontName!=null){
-// f = getSWTFont(f, fontName);
-// textBox.setFont(f);
-// }
-// }
-//
-// });
+ public void keyReleased(KeyEvent event) {
+ // Text field has changed: make editor dirty if not already
+ if (!BabelUtils.equals(focusGainedText, textBox.getText())) {
+ // Make the editor dirty if not already. If it is,
+ // we wait until field focus lost (or save) to
+ // update it completely.
+ if (!editor.isDirty()) {
+ // textEditor.isDirty();
+ updateModel();
+ // int caretPosition = eventBox.getCaretPosition();
+ // updateBundleOnChanges();
+ // eventBox.setSelection(caretPosition);
+ }
+ // autoDetectRequiredFont(eventBox.getText());
+ }
+ }
+ });
+ // // Eric Fettweis : new listener to automatically change the font
+ // textBox.addModifyListener(new ModifyListener() {
+ //
+ // public void modifyText(ModifyEvent e) {
+ // String text = textBox.getText();
+ // Font f = textBox.getFont();
+ // String fontName = getBestFont(f.getFontData()[0].getName(), text);
+ // if(fontName!=null){
+ // f = getSWTFont(f, fontName);
+ // textBox.setFont(f);
+ // }
+ // }
+ //
+ // });
-
-
-
editor.addChangeListener(new MessagesEditorChangeAdapter() {
public void selectedKeyChanged(String oldKey, String newKey) {
- updateKey(newKey);
+ updateKey(newKey);
}
});
}
-
- void updateKey(String key) {
- IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(
- projectName).getMessagesBundleGroup(bundleGroupId);
- boolean isKey = key != null && messagesBundleGroup.isMessageKey(key);
- textBox.setEnabled(isKey);
- if (isKey) {
- IMessage entry = messagesBundleGroup.getMessage(key, locale);
- if (entry == null || entry.getValue() == null) {
- textBox.setText(null);
- // commentedCheckbox.setSelection(false);
- } else {
- // commentedCheckbox.setSelection(bundleEntry.isCommented());
- textBox.setText(entry.getValue());
- }
- } else {
- textBox.setText(null);
- }
- }
+
+ void updateKey(String key) {
+ IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(
+ projectName).getMessagesBundleGroup(bundleGroupId);
+ boolean isKey = key != null && messagesBundleGroup.isMessageKey(key);
+ textBox.setEnabled(isKey);
+ if (isKey) {
+ IMessage entry = messagesBundleGroup.getMessage(key, locale);
+ if (entry == null || entry.getValue() == null) {
+ textBox.setText(null);
+ // commentedCheckbox.setSelection(false);
+ } else {
+ // commentedCheckbox.setSelection(bundleEntry.isCommented());
+ textBox.setText(entry.getValue());
+ }
+ } else {
+ textBox.setText(null);
+ }
+ }
private void updateModel() {
if (editor.getSelectedKey() != null) {
if (!BabelUtils.equals(focusGainedText, textBox.getText())) {
- IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(projectName).getMessagesBundleGroup(bundleGroupId);
+ IMessagesBundleGroup messagesBundleGroup = RBManager
+ .getInstance(projectName).getMessagesBundleGroup(
+ bundleGroupId);
String key = editor.getSelectedKey();
IMessage entry = messagesBundleGroup.getMessage(key, locale);
if (entry == null) {
entry = new Message(key, locale);
- IMessagesBundle messagesBundle = messagesBundleGroup.getMessagesBundle(locale);
+ IMessagesBundle messagesBundle = messagesBundleGroup
+ .getMessagesBundle(locale);
if (messagesBundle != null) {
- messagesBundle.addMessage(entry);
+ messagesBundle.addMessage(entry);
}
}
entry.setText(textBox.getText());
@@ -289,543 +286,547 @@
}
}
-
-
-
-
-
-
-
-//TODO Grab and Apply font fix:
-///**
+// TODO Grab and Apply font fix:
+// /**
// * Represents a data entry section for a bundle entry.
// * @author Pascal Essiembre (essiembre@users.sourceforge.net)
// * @version $Author: pessiembr $ $Revision: 1.3 $ $Date: 2008/01/11 04:15:15 $
// */
-//public class BundleEntryComposite extends Composite {
+// public class BundleEntryComposite extends Composite {
//
-// /*default*/ final ResourceManager resourceManager;
-// /*default*/ final Locale locale;
-// private final Font boldFont;
-// private final Font smallFont;
-//
-// /*default*/ Text textBox;
-// private Button commentedCheckbox;
-// private Button gotoButton;
-// private Button duplButton;
-// private Button simButton;
-//
-// /*default*/ String activeKey;
-// /*default*/ String textBeforeUpdate;
+// /*default*/ final ResourceManager resourceManager;
+// /*default*/ final Locale locale;
+// private final Font boldFont;
+// private final Font smallFont;
//
-// /*default*/ DuplicateValuesVisitor duplVisitor;
-// /*default*/ SimilarValuesVisitor similarVisitor;
-//
-//
-// /**
-// * Constructor.
-// * @param parent parent composite
-// * @param resourceManager resource manager
-// * @param locale locale for this bundle entry
-// */
-// public BundleEntryComposite(
-// final Composite parent,
-// final ResourceManager resourceManager,
-// final Locale locale) {
+// /*default*/ Text textBox;
+// private Button commentedCheckbox;
+// private Button gotoButton;
+// private Button duplButton;
+// private Button simButton;
//
-// super(parent, SWT.NONE);
-// this.resourceManager = resourceManager;
-// this.locale = locale;
-//
-// this.boldFont = UIUtils.createFont(this, SWT.BOLD, 0);
-// this.smallFont = UIUtils.createFont(SWT.NONE, -1);
-//
-// GridLayout gridLayout = new GridLayout(1, false);
-// gridLayout.horizontalSpacing = 0;
-// gridLayout.verticalSpacing = 2;
-// gridLayout.marginWidth = 0;
-// gridLayout.marginHeight = 0;
+// /*default*/ String activeKey;
+// /*default*/ String textBeforeUpdate;
//
-// createLabelRow();
-// createTextRow();
+// /*default*/ DuplicateValuesVisitor duplVisitor;
+// /*default*/ SimilarValuesVisitor similarVisitor;
//
-// setLayout(gridLayout);
-// GridData gd = new GridData(GridData.FILL_BOTH);
-// gd.heightHint = 80;
-// setLayoutData(gd);
//
-//
-// }
+// /**
+// * Constructor.
+// * @param parent parent composite
+// * @param resourceManager resource manager
+// * @param locale locale for this bundle entry
+// */
+// public BundleEntryComposite(
+// final Composite parent,
+// final ResourceManager resourceManager,
+// final Locale locale) {
//
-// /**
-// * Update bundles if the value of the active key changed.
-// */
-// public void updateBundleOnChanges(){
-// if (activeKey != null) {
-// MessagesBundleGroup messagesBundleGroup = resourceManager.getBundleGroup();
-// Message entry = messagesBundleGroup.getBundleEntry(locale, activeKey);
-// boolean commentedSelected = commentedCheckbox.getSelection();
-// String textBoxValue = textBox.getText();
-//
-// if (entry == null || !textBoxValue.equals(entry.getValue())
-// || entry.isCommented() != commentedSelected) {
-// String comment = null;
-// if (entry != null) {
-// comment = entry.getComment();
-// }
-// messagesBundleGroup.addBundleEntry(locale, new Message(
-// activeKey,
-// textBox.getText(),
-// comment,
-// commentedSelected));
-// }
-// }
-// }
-//
-// /**
-// * @see org.eclipse.swt.widgets.Widget#dispose()
-// */
-// public void dispose() {
-// super.dispose();
-// boldFont.dispose();
-// smallFont.dispose();
-//
-// //Addition by Eric Fettweis
-// for(Iterator it = swtFontCache.values().iterator();it.hasNext();){
-// Font font = (Font) it.next();
-// font.dispose();
-// }
-// swtFontCache.clear();
-// }
+// super(parent, SWT.NONE);
+// this.resourceManager = resourceManager;
+// this.locale = locale;
//
-// /**
-// * Gets the locale associated with this bundle entry
-// * @return a locale
-// */
-// public Locale getLocale() {
-// return locale;
-// }
+// this.boldFont = UIUtils.createFont(this, SWT.BOLD, 0);
+// this.smallFont = UIUtils.createFont(SWT.NONE, -1);
//
-// /**
-// * Sets a selection in the text box.
-// * @param start starting position to select
-// * @param end ending position to select
-// */
-// public void setTextSelection(int start, int end) {
-// textBox.setSelection(start, end);
-// }
-//
-// /**
-// * Refreshes the text field value with value matching given key.
-// * @param key key used to grab value
-// */
-// public void refresh(String key) {
-// activeKey = key;
-// MessagesBundleGroup messagesBundleGroup = resourceManager.getBundleGroup();
-// if (key != null && messagesBundleGroup.isKey(key)) {
-// Message bundleEntry = messagesBundleGroup.getBundleEntry(locale, key);
-// SourceEditor sourceEditor = resourceManager.getSourceEditor(locale);
-// if (bundleEntry == null) {
+// GridLayout gridLayout = new GridLayout(1, false);
+// gridLayout.horizontalSpacing = 0;
+// gridLayout.verticalSpacing = 2;
+// gridLayout.marginWidth = 0;
+// gridLayout.marginHeight = 0;
+//
+// createLabelRow();
+// createTextRow();
+//
+// setLayout(gridLayout);
+// GridData gd = new GridData(GridData.FILL_BOTH);
+// gd.heightHint = 80;
+// setLayoutData(gd);
+//
+//
+// }
+//
+// /**
+// * Update bundles if the value of the active key changed.
+// */
+// public void updateBundleOnChanges(){
+// if (activeKey != null) {
+// MessagesBundleGroup messagesBundleGroup = resourceManager.getBundleGroup();
+// Message entry = messagesBundleGroup.getBundleEntry(locale, activeKey);
+// boolean commentedSelected = commentedCheckbox.getSelection();
+// String textBoxValue = textBox.getText();
+//
+// if (entry == null || !textBoxValue.equals(entry.getValue())
+// || entry.isCommented() != commentedSelected) {
+// String comment = null;
+// if (entry != null) {
+// comment = entry.getComment();
+// }
+// messagesBundleGroup.addBundleEntry(locale, new Message(
+// activeKey,
+// textBox.getText(),
+// comment,
+// commentedSelected));
+// }
+// }
+// }
+//
+// /**
+// * @see org.eclipse.swt.widgets.Widget#dispose()
+// */
+// public void dispose() {
+// super.dispose();
+// boldFont.dispose();
+// smallFont.dispose();
+//
+// //Addition by Eric Fettweis
+// for(Iterator it = swtFontCache.values().iterator();it.hasNext();){
+// Font font = (Font) it.next();
+// font.dispose();
+// }
+// swtFontCache.clear();
+// }
+//
+// /**
+// * Gets the locale associated with this bundle entry
+// * @return a locale
+// */
+// public Locale getLocale() {
+// return locale;
+// }
+//
+// /**
+// * Sets a selection in the text box.
+// * @param start starting position to select
+// * @param end ending position to select
+// */
+// public void setTextSelection(int start, int end) {
+// textBox.setSelection(start, end);
+// }
+//
+// /**
+// * Refreshes the text field value with value matching given key.
+// * @param key key used to grab value
+// */
+// public void refresh(String key) {
+// activeKey = key;
+// MessagesBundleGroup messagesBundleGroup = resourceManager.getBundleGroup();
+// if (key != null && messagesBundleGroup.isKey(key)) {
+// Message bundleEntry = messagesBundleGroup.getBundleEntry(locale, key);
+// SourceEditor sourceEditor = resourceManager.getSourceEditor(locale);
+// if (bundleEntry == null) {
// textBox.setText(""); //$NON-NLS-1$
-// commentedCheckbox.setSelection(false);
-// } else {
-// commentedCheckbox.setSelection(bundleEntry.isCommented());
-// String value = bundleEntry.getValue();
-// textBox.setText(value);
-// }
-// commentedCheckbox.setEnabled(!sourceEditor.isReadOnly());
-// textBox.setEnabled(!sourceEditor.isReadOnly());
-// gotoButton.setEnabled(true);
-// if (MsgEditorPreferences.getReportDuplicateValues()) {
-// findDuplicates(bundleEntry);
-// } else {
-// duplVisitor = null;
-// }
-// if (MsgEditorPreferences.getReportSimilarValues()) {
-// findSimilar(bundleEntry);
-// } else {
-// similarVisitor = null;
-// }
-// } else {
-// commentedCheckbox.setSelection(false);
-// commentedCheckbox.setEnabled(false);
+// commentedCheckbox.setSelection(false);
+// } else {
+// commentedCheckbox.setSelection(bundleEntry.isCommented());
+// String value = bundleEntry.getValue();
+// textBox.setText(value);
+// }
+// commentedCheckbox.setEnabled(!sourceEditor.isReadOnly());
+// textBox.setEnabled(!sourceEditor.isReadOnly());
+// gotoButton.setEnabled(true);
+// if (MsgEditorPreferences.getReportDuplicateValues()) {
+// findDuplicates(bundleEntry);
+// } else {
+// duplVisitor = null;
+// }
+// if (MsgEditorPreferences.getReportSimilarValues()) {
+// findSimilar(bundleEntry);
+// } else {
+// similarVisitor = null;
+// }
+// } else {
+// commentedCheckbox.setSelection(false);
+// commentedCheckbox.setEnabled(false);
// textBox.setText(""); //$NON-NLS-1$
-// textBox.setEnabled(false);
-// gotoButton.setEnabled(false);
-// duplButton.setVisible(false);
-// simButton.setVisible(false);
-// }
-// resetCommented();
-// }
-//
-// private void findSimilar(Message bundleEntry) {
-// ProximityAnalyzer analyzer;
-// if (MsgEditorPreferences.getReportSimilarValuesLevensthein()) {
-// analyzer = LevenshteinDistanceAnalyzer.getInstance();
-// } else {
-// analyzer = WordCountAnalyzer.getInstance();
-// }
-// MessagesBundleGroup messagesBundleGroup = resourceManager.getBundleGroup();
-// if (similarVisitor == null) {
-// similarVisitor = new SimilarValuesVisitor();
-// }
-// similarVisitor.setProximityAnalyzer(analyzer);
-// similarVisitor.clear();
-// messagesBundleGroup.getBundle(locale).accept(similarVisitor, bundleEntry);
-// if (duplVisitor != null) {
-// similarVisitor.getSimilars().removeAll(duplVisitor.getDuplicates());
-// }
-// simButton.setVisible(similarVisitor.getSimilars().size() > 0);
-// }
-//
-// private void findDuplicates(Message bundleEntry) {
-// MessagesBundleGroup messagesBundleGroup = resourceManager.getBundleGroup();
-// if (duplVisitor == null) {
-// duplVisitor = new DuplicateValuesVisitor();
-// }
-// duplVisitor.clear();
-// messagesBundleGroup.getBundle(locale).accept(duplVisitor, bundleEntry);
-// duplButton.setVisible(duplVisitor.getDuplicates().size() > 0);
-// }
-//
-//
-// /**
-// * Creates the text field label, icon, and commented check box.
-// */
-// private void createLabelRow() {
-// Composite labelComposite = new Composite(this, SWT.NONE);
-// GridLayout gridLayout = new GridLayout();
-// gridLayout.numColumns = 6;
-// gridLayout.horizontalSpacing = 5;
-// gridLayout.verticalSpacing = 0;
-// gridLayout.marginWidth = 0;
-// gridLayout.marginHeight = 0;
-// labelComposite.setLayout(gridLayout);
-// labelComposite.setLayoutData(
-// new GridData(GridData.FILL_HORIZONTAL));
+// textBox.setEnabled(false);
+// gotoButton.setEnabled(false);
+// duplButton.setVisible(false);
+// simButton.setVisible(false);
+// }
+// resetCommented();
+// }
//
-// // Locale text
-// Label txtLabel = new Label(labelComposite, SWT.NONE);
+// private void findSimilar(Message bundleEntry) {
+// ProximityAnalyzer analyzer;
+// if (MsgEditorPreferences.getReportSimilarValuesLevensthein()) {
+// analyzer = LevenshteinDistanceAnalyzer.getInstance();
+// } else {
+// analyzer = WordCountAnalyzer.getInstance();
+// }
+// MessagesBundleGroup messagesBundleGroup = resourceManager.getBundleGroup();
+// if (similarVisitor == null) {
+// similarVisitor = new SimilarValuesVisitor();
+// }
+// similarVisitor.setProximityAnalyzer(analyzer);
+// similarVisitor.clear();
+// messagesBundleGroup.getBundle(locale).accept(similarVisitor, bundleEntry);
+// if (duplVisitor != null) {
+// similarVisitor.getSimilars().removeAll(duplVisitor.getDuplicates());
+// }
+// simButton.setVisible(similarVisitor.getSimilars().size() > 0);
+// }
+//
+// private void findDuplicates(Message bundleEntry) {
+// MessagesBundleGroup messagesBundleGroup = resourceManager.getBundleGroup();
+// if (duplVisitor == null) {
+// duplVisitor = new DuplicateValuesVisitor();
+// }
+// duplVisitor.clear();
+// messagesBundleGroup.getBundle(locale).accept(duplVisitor, bundleEntry);
+// duplButton.setVisible(duplVisitor.getDuplicates().size() > 0);
+// }
+//
+//
+// /**
+// * Creates the text field label, icon, and commented check box.
+// */
+// private void createLabelRow() {
+// Composite labelComposite = new Composite(this, SWT.NONE);
+// GridLayout gridLayout = new GridLayout();
+// gridLayout.numColumns = 6;
+// gridLayout.horizontalSpacing = 5;
+// gridLayout.verticalSpacing = 0;
+// gridLayout.marginWidth = 0;
+// gridLayout.marginHeight = 0;
+// labelComposite.setLayout(gridLayout);
+// labelComposite.setLayoutData(
+// new GridData(GridData.FILL_HORIZONTAL));
+//
+// // Locale text
+// Label txtLabel = new Label(labelComposite, SWT.NONE);
// txtLabel.setText(" " + //$NON-NLS-1$
// UIUtils.getDisplayName(locale) + " "); //$NON-NLS-1$
-// txtLabel.setFont(boldFont);
-// GridData gridData = new GridData();
+// txtLabel.setFont(boldFont);
+// GridData gridData = new GridData();
//
-// // Similar button
-// gridData = new GridData();
-// gridData.horizontalAlignment = GridData.END;
-// gridData.grabExcessHorizontalSpace = true;
-// simButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT);
+// // Similar button
+// gridData = new GridData();
+// gridData.horizontalAlignment = GridData.END;
+// gridData.grabExcessHorizontalSpace = true;
+// simButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT);
// simButton.setImage(UIUtils.getImage("similar.gif")); //$NON-NLS-1$
-// simButton.setLayoutData(gridData);
-// simButton.setVisible(false);
-// simButton.setToolTipText(
+// simButton.setLayoutData(gridData);
+// simButton.setVisible(false);
+// simButton.setToolTipText(
// RBEPlugin.getString("value.similar.tooltip")); //$NON-NLS-1$
-// simButton.addSelectionListener(new SelectionAdapter() {
-// public void widgetSelected(SelectionEvent event) {
-// String head = RBEPlugin.getString(
+// simButton.addSelectionListener(new SelectionAdapter() {
+// public void widgetSelected(SelectionEvent event) {
+// String head = RBEPlugin.getString(
// "dialog.similar.head"); //$NON-NLS-1$
-// String body = RBEPlugin.getString(
+// String body = RBEPlugin.getString(
// "dialog.similar.body", activeKey, //$NON-NLS-1$
-// UIUtils.getDisplayName(locale));
+// UIUtils.getDisplayName(locale));
// body += "\n\n"; //$NON-NLS-1$
-// for (Iterator iter = similarVisitor.getSimilars().iterator();
-// iter.hasNext();) {
+// for (Iterator iter = similarVisitor.getSimilars().iterator();
+// iter.hasNext();) {
// body += " " //$NON-NLS-1$
-// + ((Message) iter.next()).getKey()
+// + ((Message) iter.next()).getKey()
// + "\n"; //$NON-NLS-1$
-// }
-// MessageDialog.openInformation(getShell(), head, body);
-// }
-// });
+// }
+// MessageDialog.openInformation(getShell(), head, body);
+// }
+// });
//
-// // Duplicate button
-// gridData = new GridData();
-// gridData.horizontalAlignment = GridData.END;
-// duplButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT);
+// // Duplicate button
+// gridData = new GridData();
+// gridData.horizontalAlignment = GridData.END;
+// duplButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT);
// duplButton.setImage(UIUtils.getImage("duplicate.gif")); //$NON-NLS-1$
-// duplButton.setLayoutData(gridData);
-// duplButton.setVisible(false);
-// duplButton.setToolTipText(
+// duplButton.setLayoutData(gridData);
+// duplButton.setVisible(false);
+// duplButton.setToolTipText(
// RBEPlugin.getString("value.duplicate.tooltip")); //$NON-NLS-1$
//
-// duplButton.addSelectionListener(new SelectionAdapter() {
-// public void widgetSelected(SelectionEvent event) {
-// String head = RBEPlugin.getString(
+// duplButton.addSelectionListener(new SelectionAdapter() {
+// public void widgetSelected(SelectionEvent event) {
+// String head = RBEPlugin.getString(
// "dialog.identical.head"); //$NON-NLS-1$
-// String body = RBEPlugin.getString(
+// String body = RBEPlugin.getString(
// "dialog.identical.body", activeKey, //$NON-NLS-1$
-// UIUtils.getDisplayName(locale));
+// UIUtils.getDisplayName(locale));
// body += "\n\n"; //$NON-NLS-1$
-// for (Iterator iter = duplVisitor.getDuplicates().iterator();
-// iter.hasNext();) {
+// for (Iterator iter = duplVisitor.getDuplicates().iterator();
+// iter.hasNext();) {
// body += " " //$NON-NLS-1$
-// + ((Message) iter.next()).getKey()
+// + ((Message) iter.next()).getKey()
// + "\n"; //$NON-NLS-1$
-// }
-// MessageDialog.openInformation(getShell(), head, body);
-// }
-// });
-//
-// // Commented checkbox
-// gridData = new GridData();
-// gridData.horizontalAlignment = GridData.END;
-// //gridData.grabExcessHorizontalSpace = true;
-// commentedCheckbox = new Button(
-// labelComposite, SWT.CHECK);
-// commentedCheckbox.setText("#"); //$NON-NLS-1$
-// commentedCheckbox.setFont(smallFont);
-// commentedCheckbox.setLayoutData(gridData);
-// commentedCheckbox.addSelectionListener(new SelectionAdapter() {
-// public void widgetSelected(SelectionEvent event) {
-// resetCommented();
-// updateBundleOnChanges();
-// }
-// });
-// commentedCheckbox.setEnabled(false);
-//
-// // Country flag
-// gridData = new GridData();
-// gridData.horizontalAlignment = GridData.END;
-// Label imgLabel = new Label(labelComposite, SWT.NONE);
-// imgLabel.setLayoutData(gridData);
-// imgLabel.setImage(loadCountryIcon(locale));
+// }
+// MessageDialog.openInformation(getShell(), head, body);
+// }
+// });
//
-// // Goto button
-// gridData = new GridData();
-// gridData.horizontalAlignment = GridData.END;
-// gotoButton = new Button(
-// labelComposite, SWT.ARROW | SWT.RIGHT);
-// gotoButton.setToolTipText(
+// // Commented checkbox
+// gridData = new GridData();
+// gridData.horizontalAlignment = GridData.END;
+// //gridData.grabExcessHorizontalSpace = true;
+// commentedCheckbox = new Button(
+// labelComposite, SWT.CHECK);
+// commentedCheckbox.setText("#"); //$NON-NLS-1$
+// commentedCheckbox.setFont(smallFont);
+// commentedCheckbox.setLayoutData(gridData);
+// commentedCheckbox.addSelectionListener(new SelectionAdapter() {
+// public void widgetSelected(SelectionEvent event) {
+// resetCommented();
+// updateBundleOnChanges();
+// }
+// });
+// commentedCheckbox.setEnabled(false);
+//
+// // Country flag
+// gridData = new GridData();
+// gridData.horizontalAlignment = GridData.END;
+// Label imgLabel = new Label(labelComposite, SWT.NONE);
+// imgLabel.setLayoutData(gridData);
+// imgLabel.setImage(loadCountryIcon(locale));
+//
+// // Goto button
+// gridData = new GridData();
+// gridData.horizontalAlignment = GridData.END;
+// gotoButton = new Button(
+// labelComposite, SWT.ARROW | SWT.RIGHT);
+// gotoButton.setToolTipText(
// RBEPlugin.getString("value.goto.tooltip")); //$NON-NLS-1$
-// gotoButton.setEnabled(false);
-// gotoButton.addSelectionListener(new SelectionAdapter() {
-// public void widgetSelected(SelectionEvent event) {
-// ITextEditor editor = resourceManager.getSourceEditor(
-// locale).getEditor();
-// Object activeEditor =
-// editor.getSite().getPage().getActiveEditor();
-// if (activeEditor instanceof MessagesEditor) {
-// ((MessagesEditor) activeEditor).setActivePage(locale);
-// }
-// }
-// });
-// gotoButton.setLayoutData(gridData);
-// }
-// /**
-// * Creates the text row.
-// */
-// private void createTextRow() {
-// textBox = new Text(this, SWT.MULTI | SWT.WRAP |
-// SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
-// textBox.setEnabled(false);
-// //Addition by Eric FETTWEIS
-// //Note that this does not seem to work... It would however be usefull for arabic and some other languages
-// textBox.setOrientation(getOrientation(locale));
-//
-// GridData gridData = new GridData();
-// gridData.verticalAlignment = GridData.FILL;
-// gridData.grabExcessVerticalSpace = true;
-// gridData.horizontalAlignment = GridData.FILL;
-// gridData.grabExcessHorizontalSpace = true;
-// gridData.heightHint = UIUtils.getHeightInChars(textBox, 3);
-// textBox.setLayoutData(gridData);
-// textBox.addFocusListener(new FocusListener() {
-// public void focusGained(FocusEvent event) {
-// textBeforeUpdate = textBox.getText();
-// }
-// public void focusLost(FocusEvent event) {
-// updateBundleOnChanges();
-// }
-// });
-// //TODO add a preference property listener and add/remove this listener
-// textBox.addTraverseListener(new TraverseListener() {
-// public void keyTraversed(TraverseEvent event) {
-// if (!MsgEditorPreferences.getFieldTabInserts()
-// && event.character == SWT.TAB) {
-// event.doit = true;
-// }
-// }
-// });
-// textBox.addKeyListener(new KeyAdapter() {
-// public void keyReleased(KeyEvent event) {
-// Text eventBox = (Text) event.widget;
-// final ITextEditor editor = resourceManager.getSourceEditor(
-// locale).getEditor();
-// // Text field has changed: make editor dirty if not already
-// if (textBeforeUpdate != null
-// && !textBeforeUpdate.equals(eventBox.getText())) {
-// // Make the editor dirty if not already. If it is,
-// // we wait until field focus lost (or save) to
-// // update it completely.
-// if (!editor.isDirty()) {
-// int caretPosition = eventBox.getCaretPosition();
-// updateBundleOnChanges();
-// eventBox.setSelection(caretPosition);
-// }
-// //autoDetectRequiredFont(eventBox.getText());
-// }
-// }
-// });
-// // Eric Fettweis : new listener to automatically change the font
-// textBox.addModifyListener(new ModifyListener() {
-//
-// public void modifyText(ModifyEvent e) {
-// String text = textBox.getText();
-// Font f = textBox.getFont();
-// String fontName = getBestFont(f.getFontData()[0].getName(), text);
-// if(fontName!=null){
-// f = getSWTFont(f, fontName);
-// textBox.setFont(f);
-// }
-// }
-//
-// });
-// }
-//
-//
-//
-// /*default*/ void resetCommented() {
-// if (commentedCheckbox.getSelection()) {
-// commentedCheckbox.setToolTipText(
+// gotoButton.setEnabled(false);
+// gotoButton.addSelectionListener(new SelectionAdapter() {
+// public void widgetSelected(SelectionEvent event) {
+// ITextEditor editor = resourceManager.getSourceEditor(
+// locale).getEditor();
+// Object activeEditor =
+// editor.getSite().getPage().getActiveEditor();
+// if (activeEditor instanceof MessagesEditor) {
+// ((MessagesEditor) activeEditor).setActivePage(locale);
+// }
+// }
+// });
+// gotoButton.setLayoutData(gridData);
+// }
+// /**
+// * Creates the text row.
+// */
+// private void createTextRow() {
+// textBox = new Text(this, SWT.MULTI | SWT.WRAP |
+// SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
+// textBox.setEnabled(false);
+// //Addition by Eric FETTWEIS
+// //Note that this does not seem to work... It would however be usefull for
+// arabic and some other languages
+// textBox.setOrientation(getOrientation(locale));
+//
+// GridData gridData = new GridData();
+// gridData.verticalAlignment = GridData.FILL;
+// gridData.grabExcessVerticalSpace = true;
+// gridData.horizontalAlignment = GridData.FILL;
+// gridData.grabExcessHorizontalSpace = true;
+// gridData.heightHint = UIUtils.getHeightInChars(textBox, 3);
+// textBox.setLayoutData(gridData);
+// textBox.addFocusListener(new FocusListener() {
+// public void focusGained(FocusEvent event) {
+// textBeforeUpdate = textBox.getText();
+// }
+// public void focusLost(FocusEvent event) {
+// updateBundleOnChanges();
+// }
+// });
+// //TODO add a preference property listener and add/remove this listener
+// textBox.addTraverseListener(new TraverseListener() {
+// public void keyTraversed(TraverseEvent event) {
+// if (!MsgEditorPreferences.getFieldTabInserts()
+// && event.character == SWT.TAB) {
+// event.doit = true;
+// }
+// }
+// });
+// textBox.addKeyListener(new KeyAdapter() {
+// public void keyReleased(KeyEvent event) {
+// Text eventBox = (Text) event.widget;
+// final ITextEditor editor = resourceManager.getSourceEditor(
+// locale).getEditor();
+// // Text field has changed: make editor dirty if not already
+// if (textBeforeUpdate != null
+// && !textBeforeUpdate.equals(eventBox.getText())) {
+// // Make the editor dirty if not already. If it is,
+// // we wait until field focus lost (or save) to
+// // update it completely.
+// if (!editor.isDirty()) {
+// int caretPosition = eventBox.getCaretPosition();
+// updateBundleOnChanges();
+// eventBox.setSelection(caretPosition);
+// }
+// //autoDetectRequiredFont(eventBox.getText());
+// }
+// }
+// });
+// // Eric Fettweis : new listener to automatically change the font
+// textBox.addModifyListener(new ModifyListener() {
+//
+// public void modifyText(ModifyEvent e) {
+// String text = textBox.getText();
+// Font f = textBox.getFont();
+// String fontName = getBestFont(f.getFontData()[0].getName(), text);
+// if(fontName!=null){
+// f = getSWTFont(f, fontName);
+// textBox.setFont(f);
+// }
+// }
+//
+// });
+// }
+//
+//
+//
+// /*default*/ void resetCommented() {
+// if (commentedCheckbox.getSelection()) {
+// commentedCheckbox.setToolTipText(
// RBEPlugin.getString("value.uncomment.tooltip"));//$NON-NLS-1$
-// textBox.setForeground(
-// getDisplay().getSystemColor(SWT.COLOR_GRAY));
-// } else {
-// commentedCheckbox.setToolTipText(
+// textBox.setForeground(
+// getDisplay().getSystemColor(SWT.COLOR_GRAY));
+// } else {
+// commentedCheckbox.setToolTipText(
// RBEPlugin.getString("value.comment.tooltip"));//$NON-NLS-1$
-// textBox.setForeground(null);
-// }
-// }
-//
-//
-//
-// /** Additions by Eric FETTWEIS */
-// /*private void autoDetectRequiredFont(String value) {
-// Font f = getFont();
-// FontData[] data = f.getFontData();
-// boolean resetFont = true;
-// for (int i = 0; i < data.length; i++) {
-// java.awt.Font test = new java.awt.Font(data[i].getName(), java.awt.Font.PLAIN, 12);
-// if(test.canDisplayUpTo(value)==-1){
-// resetFont = false;
-// break;
-// }
-// }
-// if(resetFont){
-// String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
-// for (int i = 0; i < fonts.length; i++) {
-// java.awt.Font fnt = new java.awt.Font(fonts[i],java.awt.Font.PLAIN,12);
-// if(fnt.canDisplayUpTo(value)==-1){
-// textBox.setFont(createFont(fonts[i]));
-// break;
-// }
-// }
-// }
-//}*/
-// /**
-// * Holds swt fonts used for the textBox.
-// */
-// private Map swtFontCache = new HashMap();
-//
-// /**
-// * Gets a font by its name. The resulting font is build based on the baseFont parameter.
-// * The font is retrieved from the swtFontCache, or created if needed.
-// * @param baseFont the current font used to build the new one.
-// * Only the name of the new font will differ fromm the original one.
-// * @parama baseFont a font
-// * @param name the new font name
-// * @return a font with the same style and size as the original.
-// */
-// private Font getSWTFont(Font baseFont, String name){
-// Font font = (Font) swtFontCache.get(name);
-// if(font==null){
-// font = createFont(baseFont, getDisplay(), name);
-// swtFontCache.put(name, font);
-// }
-// return font;
-// }
-// /**
-// * Gets the name of the font which will be the best to display a String.
-// * All installed fonts are searched. If a font can display the entire string, then it is retuned immediately.
-// * Otherwise, the font returned is the one which can display properly the longest substring possible from the argument value.
-// * @param baseFontName a font to be tested before any other. It will be the current font used by a widget.
-// * @param value the string to be displayed.
-// * @return a font name
-// */
-// private static String getBestFont(String baseFontName, String value){
-// if(canFullyDisplay(baseFontName, value)) return baseFontName;
-// String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
-// String fontName=null;
-// int currentScore = 0;
-// for (int i = 0; i < fonts.length; i++) {
-// int score = canDisplayUpTo(fonts[i], value);
-// if(score==-1){//no need to loop further
-// fontName=fonts[i];
-// break;
-// }
-// if(score>currentScore){
-// fontName=fonts[i];
-// currentScore = score;
-// }
-// }
-//
-// return fontName;
-// }
-//
-// /**
-// * A cache holding an instance of every AWT font tested.
-// */
-// private static Map awtFontCache = new HashMap();
-//
-// /**
-// * Creates a variation from an original font, by changing the face name.
-// * @param baseFont the original font
-// * @param display the current display
-// * @param name the new font face name
-// * @return a new Font
-// */
-// private static Font createFont(Font baseFont, Display display, String name){
-// FontData[] fontData = baseFont.getFontData();
-// for (int i = 0; i < fontData.length; i++) {
-// fontData[i].setName(name);
-// }
-// return new Font(display, fontData);
-// }
-// /**
-// * Can a font display correctly an entire string ?
-// * @param fontName the font name
-// * @param value the string to be displayed
-// * @return
-// */
-// private static boolean canFullyDisplay(String fontName, String value){
-// return canDisplayUpTo(fontName, value)==-1;
-// }
-//
-// /**
-// * Test the number of characters from a given String that a font can display correctly.
-// * @param fontName the name of the font
-// * @param value the value to be displayed
-// * @return the number of characters that can be displayed, or -1 if the entire string can be displayed successfuly.
-// * @see java.aw.Font#canDisplayUpTo(String)
-// */
-// private static int canDisplayUpTo(String fontName, String value){
-// java.awt.Font font = getAWTFont(fontName);
-// return font.canDisplayUpTo(value);
-// }
-// /**
-// * Returns a cached or new AWT font by its name.
-// * If the font needs to be created, its style will be Font.PLAIN and its size will be 12.
-// * @param name teh font name
-// * @return an AWT Font
-// */
-// private static java.awt.Font getAWTFont(String name){
-// java.awt.Font font = (java.awt.Font) awtFontCache.get(name);
-// if(font==null){
-// font = new java.awt.Font(name, java.awt.Font.PLAIN, 12);
-// awtFontCache.put(name, font);
-// }
-// return font;
-// }
+// textBox.setForeground(null);
+// }
+// }
+//
+//
+//
+// /** Additions by Eric FETTWEIS */
+// /*private void autoDetectRequiredFont(String value) {
+// Font f = getFont();
+// FontData[] data = f.getFontData();
+// boolean resetFont = true;
+// for (int i = 0; i < data.length; i++) {
+// java.awt.Font test = new java.awt.Font(data[i].getName(),
+// java.awt.Font.PLAIN, 12);
+// if(test.canDisplayUpTo(value)==-1){
+// resetFont = false;
+// break;
+// }
+// }
+// if(resetFont){
+// String[] fonts =
+// GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
+// for (int i = 0; i < fonts.length; i++) {
+// java.awt.Font fnt = new java.awt.Font(fonts[i],java.awt.Font.PLAIN,12);
+// if(fnt.canDisplayUpTo(value)==-1){
+// textBox.setFont(createFont(fonts[i]));
+// break;
+// }
+// }
+// }
+// }*/
+// /**
+// * Holds swt fonts used for the textBox.
+// */
+// private Map swtFontCache = new HashMap();
+//
+// /**
+// * Gets a font by its name. The resulting font is build based on the baseFont
+// parameter.
+// * The font is retrieved from the swtFontCache, or created if needed.
+// * @param baseFont the current font used to build the new one.
+// * Only the name of the new font will differ fromm the original one.
+// * @parama baseFont a font
+// * @param name the new font name
+// * @return a font with the same style and size as the original.
+// */
+// private Font getSWTFont(Font baseFont, String name){
+// Font font = (Font) swtFontCache.get(name);
+// if(font==null){
+// font = createFont(baseFont, getDisplay(), name);
+// swtFontCache.put(name, font);
+// }
+// return font;
+// }
+// /**
+// * Gets the name of the font which will be the best to display a String.
+// * All installed fonts are searched. If a font can display the entire string,
+// then it is retuned immediately.
+// * Otherwise, the font returned is the one which can display properly the
+// longest substring possible from the argument value.
+// * @param baseFontName a font to be tested before any other. It will be the
+// current font used by a widget.
+// * @param value the string to be displayed.
+// * @return a font name
+// */
+// private static String getBestFont(String baseFontName, String value){
+// if(canFullyDisplay(baseFontName, value)) return baseFontName;
+// String[] fonts =
+// GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
+// String fontName=null;
+// int currentScore = 0;
+// for (int i = 0; i < fonts.length; i++) {
+// int score = canDisplayUpTo(fonts[i], value);
+// if(score==-1){//no need to loop further
+// fontName=fonts[i];
+// break;
+// }
+// if(score>currentScore){
+// fontName=fonts[i];
+// currentScore = score;
+// }
+// }
+//
+// return fontName;
+// }
+//
+// /**
+// * A cache holding an instance of every AWT font tested.
+// */
+// private static Map awtFontCache = new HashMap();
+//
+// /**
+// * Creates a variation from an original font, by changing the face name.
+// * @param baseFont the original font
+// * @param display the current display
+// * @param name the new font face name
+// * @return a new Font
+// */
+// private static Font createFont(Font baseFont, Display display, String name){
+// FontData[] fontData = baseFont.getFontData();
+// for (int i = 0; i < fontData.length; i++) {
+// fontData[i].setName(name);
+// }
+// return new Font(display, fontData);
+// }
+// /**
+// * Can a font display correctly an entire string ?
+// * @param fontName the font name
+// * @param value the string to be displayed
+// * @return
+// */
+// private static boolean canFullyDisplay(String fontName, String value){
+// return canDisplayUpTo(fontName, value)==-1;
+// }
+//
+// /**
+// * Test the number of characters from a given String that a font can display
+// correctly.
+// * @param fontName the name of the font
+// * @param value the value to be displayed
+// * @return the number of characters that can be displayed, or -1 if the entire
+// string can be displayed successfuly.
+// * @see java.aw.Font#canDisplayUpTo(String)
+// */
+// private static int canDisplayUpTo(String fontName, String value){
+// java.awt.Font font = getAWTFont(fontName);
+// return font.canDisplayUpTo(value);
+// }
+// /**
+// * Returns a cached or new AWT font by its name.
+// * If the font needs to be created, its style will be Font.PLAIN and its size
+// will be 12.
+// * @param name teh font name
+// * @return an AWT Font
+// */
+// private static java.awt.Font getAWTFont(String name){
+// java.awt.Font font = (java.awt.Font) awtFontCache.get(name);
+// if(font==null){
+// font = new java.awt.Font(name, java.awt.Font.PLAIN, 12);
+// awtFontCache.put(name, font);
+// }
+// return font;
+// }
-//}
+// }
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NPage.java
index 2efe433..c6a8bf1 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NPage.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NPage.java
@@ -37,8 +37,9 @@
import org.eclipse.ui.IWorkbenchPart;
/**
- * Internationalization page where one can edit all resource bundle entries
- * at once for all supported locales.
+ * Internationalization page where one can edit all resource bundle entries at
+ * once for all supported locales.
+ *
* @author Pascal Essiembre
*/
public class I18NPage extends ScrolledComposite implements ISelectionProvider {
@@ -49,82 +50,94 @@
private final MessagesEditor editor;
private final SideNavComposite keysComposite;
private final Composite valuesComposite;
- private final Map<Locale,I18NEntry> entryComposites = new HashMap<Locale,I18NEntry>();
+ private final Map<Locale, I18NEntry> entryComposites = new HashMap<Locale, I18NEntry>();
private Composite entriesComposite;
-
-// private Composite parent;
+
+ // private Composite parent;
private boolean keyTreeVisible = true;
-
-// private final StackLayout layout = new StackLayout();
+
+ // private final StackLayout layout = new StackLayout();
private final SashForm sashForm;
-
-
+
/**
* Constructor.
- * @param parent parent component.
- * @param style style to apply to this component
- * @param resourceMediator resource manager
+ *
+ * @param parent
+ * parent component.
+ * @param style
+ * style to apply to this component
+ * @param resourceMediator
+ * resource manager
*/
- public I18NPage(
- Composite parent, int style,
- final MessagesEditor editor) {
+ public I18NPage(Composite parent, int style, final MessagesEditor editor) {
super(parent, style);
- this.editor = editor;
+ this.editor = editor;
sashForm = new SashForm(this, SWT.SMOOTH);
- sashForm.setBackground(UIUtils.getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT));
- editor.getEditorSite().getPage().addPartListener(new IPartListener(){
+ sashForm.setBackground(UIUtils
+ .getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT));
+ editor.getEditorSite().getPage().addPartListener(new IPartListener() {
public void partActivated(IWorkbenchPart part) {
if (part == editor) {
- sashForm.setBackground(UIUtils.getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT));
+ sashForm.setBackground(UIUtils
+ .getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT));
}
}
+
public void partDeactivated(IWorkbenchPart part) {
if (part == editor) {
- sashForm.setBackground(UIUtils.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
+ sashForm.setBackground(UIUtils
+ .getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
}
}
- public void partBroughtToTop(IWorkbenchPart part) {}
- public void partClosed(IWorkbenchPart part) {}
- public void partOpened(IWorkbenchPart part) {}
+
+ public void partBroughtToTop(IWorkbenchPart part) {
+ }
+
+ public void partClosed(IWorkbenchPart part) {
+ }
+
+ public void partOpened(IWorkbenchPart part) {
+ }
});
-
+
setContent(sashForm);
-
keysComposite = new SideNavComposite(sashForm, editor);
-
+
valuesComposite = createValuesComposite(sashForm);
-
- sashForm.setWeights(new int[]{25, 75});
+ sashForm.setWeights(new int[] { 25, 75 });
setExpandHorizontal(true);
setExpandVertical(true);
setMinWidth(400);
-
- RBManager instance = RBManager.getInstance(editor.getBundleGroup().getProjectName());
+
+ RBManager instance = RBManager.getInstance(editor.getBundleGroup()
+ .getProjectName());
instance.addMessagesEditorListener(new IMessagesEditorListener() {
-
- public void onSave() {
- // TODO Auto-generated method stub
-
- }
-
- public void onModify() {
- // TODO Auto-generated method stub
- }
-
- public void onResourceChanged(IMessagesBundle bundle) {
- I18NEntry i18nEntry = entryComposites.get(bundle.getLocale());
- if (i18nEntry != null && !getSelection().isEmpty()) {
- i18nEntry.updateKey(String.valueOf(((IStructuredSelection)getSelection()).getFirstElement()));
- }
- }
-
- });
+
+ public void onSave() {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void onModify() {
+ // TODO Auto-generated method stub
+ }
+
+ public void onResourceChanged(IMessagesBundle bundle) {
+ I18NEntry i18nEntry = entryComposites.get(bundle.getLocale());
+ if (i18nEntry != null && !getSelection().isEmpty()) {
+ i18nEntry.updateKey(String
+ .valueOf(((IStructuredSelection) getSelection())
+ .getFirstElement()));
+ }
+ }
+
+ });
}
-
+
/**
* @see org.eclipse.swt.widgets.Widget#dispose()
*/
@@ -132,7 +145,7 @@
keysComposite.dispose();
super.dispose();
}
-
+
public void setKeyTreeVisible(boolean visible) {
keyTreeVisible = visible;
if (visible) {
@@ -140,31 +153,28 @@
} else {
sashForm.setMaximizedControl(valuesComposite);
}
- for (IMessagesEditorChangeListener listener : editor.getChangeListeners()) {
- listener.keyTreeVisibleChanged(visible);
+ for (IMessagesEditorChangeListener listener : editor
+ .getChangeListeners()) {
+ listener.keyTreeVisibleChanged(visible);
}
}
-
+
public boolean isKeyTreeVisible() {
return keyTreeVisible;
}
-
-
+
private Composite createValuesComposite(SashForm parent) {
- final ScrolledComposite scrolledComposite =
- new ScrolledComposite(parent, SWT.V_SCROLL | SWT.H_SCROLL);
+ final ScrolledComposite scrolledComposite = new ScrolledComposite(
+ parent, SWT.V_SCROLL | SWT.H_SCROLL);
scrolledComposite.setExpandHorizontal(true);
scrolledComposite.setExpandVertical(true);
scrolledComposite.setSize(SWT.DEFAULT, 100);
- entriesComposite =
- new Composite(scrolledComposite, SWT.BORDER);
+ entriesComposite = new Composite(scrolledComposite, SWT.BORDER);
scrolledComposite.setContent(entriesComposite);
- scrolledComposite.setMinSize(entriesComposite.computeSize(
- SWT.DEFAULT,
+ scrolledComposite.setMinSize(entriesComposite.computeSize(SWT.DEFAULT,
editor.getBundleGroup().getLocales().length * TEXT_MIN_HEIGHT));
-
entriesComposite.setLayout(new GridLayout(1, false));
Locale[] locales = editor.getBundleGroup().getLocales();
UIUtils.sortLocales(locales);
@@ -173,63 +183,60 @@
Locale locale = locales[i];
addI18NEntry(editor, locale);
}
-
+
editor.addChangeListener(new MessagesEditorChangeAdapter() {
public void selectedKeyChanged(String oldKey, String newKey) {
- boolean isKey =
- newKey != null && editor.getBundleGroup().isMessageKey(newKey);
-// scrolledComposite.setBackground(isKey);
+ boolean isKey = newKey != null
+ && editor.getBundleGroup().isMessageKey(newKey);
+ // scrolledComposite.setBackground(isKey);
}
});
-
-
return scrolledComposite;
}
-
+
public void addI18NEntry(MessagesEditor editor, Locale locale) {
- I18NEntry i18NEntry = new I18NEntry(
- entriesComposite, editor, locale);
-// entryComposite.addFocusListener(localBehaviour);
+ I18NEntry i18NEntry = new I18NEntry(entriesComposite, editor, locale);
+ // entryComposite.addFocusListener(localBehaviour);
entryComposites.put(locale, i18NEntry);
entriesComposite.layout();
}
-
+
public void selectLocale(Locale locale) {
Collection<Locale> locales = entryComposites.keySet();
for (Locale entryLocale : locales) {
- I18NEntry entry =
- entryComposites.get(entryLocale);
+ I18NEntry entry = entryComposites.get(entryLocale);
- //TODO add equivalent method on entry composite
-// Text textBox = entry.getTextBox();
-// if (BabelUtils.equals(locale, entryLocale)) {
-// textBox.selectAll();
-// textBox.setFocus();
-// } else {
-// textBox.clearSelection();
-// }
+ // TODO add equivalent method on entry composite
+ // Text textBox = entry.getTextBox();
+ // if (BabelUtils.equals(locale, entryLocale)) {
+ // textBox.selectAll();
+ // textBox.setFocus();
+ // } else {
+ // textBox.clearSelection();
+ // }
}
}
public void addSelectionChangedListener(ISelectionChangedListener listener) {
keysComposite.getTreeViewer().addSelectionChangedListener(listener);
-
+
}
public ISelection getSelection() {
return keysComposite.getTreeViewer().getSelection();
}
- public void removeSelectionChangedListener(ISelectionChangedListener listener) {
+ public void removeSelectionChangedListener(
+ ISelectionChangedListener listener) {
keysComposite.getTreeViewer().removeSelectionChangedListener(listener);
}
public void setSelection(ISelection selection) {
keysComposite.getTreeViewer().setSelection(selection);
}
-
+
public TreeViewer getTreeViewer() {
- return keysComposite.getTreeViewer();
+ return keysComposite.getTreeViewer();
}
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavComposite.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavComposite.java
index 86da7ff..a71649e 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavComposite.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavComposite.java
@@ -27,22 +27,25 @@
/**
* Tree for displaying and navigating through resource bundle keys.
+ *
* @author Pascal Essiembre
*/
public class SideNavComposite extends Composite {
/** Key Tree Viewer. */
private TreeViewer treeViewer;
-
+
private MessagesEditor editor;
-
+
/**
* Constructor.
- * @param parent parent composite
- * @param keyTree key tree
+ *
+ * @param parent
+ * parent composite
+ * @param keyTree
+ * key tree
*/
- public SideNavComposite(
- Composite parent, final MessagesEditor editor) {
+ public SideNavComposite(Composite parent, final MessagesEditor editor) {
super(parent, SWT.BORDER);
this.editor = editor;
@@ -50,11 +53,9 @@
ToolBarManager toolBarMgr = new ToolBarManager(SWT.FLAT);
ToolBar toolBar = toolBarMgr.createControl(this);
-
- this.treeViewer = new TreeViewer(this,
- SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
+ this.treeViewer = new TreeViewer(this, SWT.SINGLE | SWT.BORDER
+ | SWT.V_SCROLL | SWT.H_SCROLL);
-
setLayout(new GridLayout(1, false));
GridData gid;
@@ -69,45 +70,47 @@
toolBarMgr.add(new ExpandAllAction(editor, treeViewer));
toolBarMgr.add(new CollapseAllAction(editor, treeViewer));
toolBarMgr.update(true);
-
- //TODO have two toolbars, one left-align, and one right, with drop
- //down menu
-// initListener();
-
-// createTopSection();
+
+ // TODO have two toolbars, one left-align, and one right, with drop
+ // down menu
+ // initListener();
+
+ // createTopSection();
createKeyTree();
new SideNavTextBoxComposite(this, editor);
}
-// private void initListener() {
-// IResourceChangeListener listener = new IResourceChangeListener() {
-//
-// public void resourceChanged(IResourceChangeEvent event) {
-// if (!Boolean.valueOf(System.getProperty("dirty"))) {
-// createKeyTree();
-// }
-// }
-// };
-//
-// ResourcesPlugin.getWorkspace().addResourceChangeListener(listener, IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.POST_CHANGE);
-//
-// }
+ // private void initListener() {
+ // IResourceChangeListener listener = new IResourceChangeListener() {
+ //
+ // public void resourceChanged(IResourceChangeEvent event) {
+ // if (!Boolean.valueOf(System.getProperty("dirty"))) {
+ // createKeyTree();
+ // }
+ // }
+ // };
+ //
+ // ResourcesPlugin.getWorkspace().addResourceChangeListener(listener,
+ // IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.POST_CHANGE);
+ //
+ // }
/**
* Gets the tree viewer.
+ *
* @return tree viewer
*/
public TreeViewer getTreeViewer() {
return treeViewer;
}
-
+
/**
* @see org.eclipse.swt.widgets.Widget#dispose()
*/
public void dispose() {
super.dispose();
}
-
+
/**
* Creates the middle (tree) section of this composite.
*/
@@ -119,11 +122,10 @@
gridData.horizontalAlignment = GridData.FILL;
gridData.grabExcessHorizontalSpace = true;
-
KeyTreeContributor treeContributor = new KeyTreeContributor(editor);
treeContributor.contribute(treeViewer);
- treeViewer.getTree().setLayoutData(gridData);
+ treeViewer.getTree().setLayoutData(gridData);
}
-
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavTextBoxComposite.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavTextBoxComposite.java
index 02f82e7..15b5163 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavTextBoxComposite.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavTextBoxComposite.java
@@ -30,27 +30,28 @@
/**
* Tree for displaying and navigating through resource bundle keys.
+ *
* @author Pascal Essiembre
*/
public class SideNavTextBoxComposite extends Composite {
-
/** Whether to synchronize the add text box with tree key selection. */
private boolean syncAddTextBox = true;
-
+
/** Text box to add a new key. */
private Text addTextBox;
private MessagesEditor editor;
-
+
/**
* Constructor.
- * @param parent parent composite
- * @param keyTree key tree
+ *
+ * @param parent
+ * parent composite
+ * @param keyTree
+ * key tree
*/
- public SideNavTextBoxComposite(
- Composite parent,
- final MessagesEditor editor) {
+ public SideNavTextBoxComposite(Composite parent, final MessagesEditor editor) {
super(parent, SWT.NONE);
this.editor = editor;
@@ -89,9 +90,9 @@
String key = addTextBox.getText();
if (event.character == SWT.CR && isNewKey(key)) {
addKey(key);
- } else if (key.length() > 0){
+ } else if (key.length() > 0) {
NodePathRegexVisitor visitor = new NodePathRegexVisitor(
- "^" + key + ".*"); //$NON-NLS-1$//$NON-NLS-2$
+ "^" + key + ".*"); //$NON-NLS-1$//$NON-NLS-2$
editor.getKeyTreeModel().accept(visitor, null);
IKeyTreeNode node = visitor.getKeyTreeNode();
if (node != null) {
@@ -114,14 +115,14 @@
syncAddTextBox = true;
}
});
-
+
}
-
+
private void addKey(String key) {
editor.getBundleGroup().addMessages(key);
editor.setSelectedKey(key);
}
-
+
private boolean isNewKey(String key) {
return !editor.getBundleGroup().isMessageKey(key) && key.length() > 0;
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/FoldingAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/FoldingAction.java
index 9558a3d..00cb990 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/FoldingAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/FoldingAction.java
@@ -16,13 +16,13 @@
/**
* @author Pascal Essiembre
- *
+ *
*/
public class FoldingAction extends Action {
private final I18NEntry i18NEntry;
private boolean expanded;
-
+
/**
*
*/
@@ -31,12 +31,13 @@
this.i18NEntry = i18NEntry;
this.expanded = i18NEntry.getExpanded();
setText("Collapse");
- setImageDescriptor(
- UIUtils.getImageDescriptor("minus.gif"));
- setToolTipText("TODO put something here"); //TODO put tooltip
+ setImageDescriptor(UIUtils.getImageDescriptor("minus.gif"));
+ setToolTipText("TODO put something here"); // TODO put tooltip
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowDuplicateAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowDuplicateAction.java
index 08e5763..bb49fbc 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowDuplicateAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowDuplicateAction.java
@@ -23,48 +23,48 @@
*/
public class ShowDuplicateAction extends Action {
- private final String[] keys;
- private final String key;
- private final Locale locale;
+ private final String[] keys;
+ private final String key;
+ private final Locale locale;
- /**
+ /**
*
*/
- public ShowDuplicateAction(String[] keys, String key, Locale locale) {
- super();
- this.keys = keys;
- this.key = key;
- this.locale = locale;
- setText("Show duplicate keys.");
- setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_DUPLICATE));
- setToolTipText("Check duplicate values");
- }
+ public ShowDuplicateAction(String[] keys, String key, Locale locale) {
+ super();
+ this.keys = keys;
+ this.key = key;
+ this.locale = locale;
+ setText("Show duplicate keys.");
+ setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_DUPLICATE));
+ setToolTipText("Check duplicate values");
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.action.IAction#run()
- */
- public void run() {
- // TODO have preference for whether to do cross locale checking
- StringBuffer buf = new StringBuffer("\"" + key + "\" ("
- + UIUtils.getDisplayName(locale) + ") has the same "
- + "value as the following key(s): \n\n");
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.action.IAction#run()
+ */
+ public void run() {
+ // TODO have preference for whether to do cross locale checking
+ StringBuffer buf = new StringBuffer("\"" + key + "\" ("
+ + UIUtils.getDisplayName(locale) + ") has the same "
+ + "value as the following key(s): \n\n");
- if (keys != null) { // keys = duplicated values
- for (int i = 0; i < keys.length; i++) {
- String duplKey = keys[i];
- if (!key.equals(duplKey)) {
- buf.append(" · ");
- buf.append(duplKey);
- buf.append(" (" + UIUtils.getDisplayName(locale) + ")");
- buf.append("\n");
- }
- }
- MessageDialog.openInformation(
- Display.getDefault().getActiveShell(), "Duplicate value",
- buf.toString());
- }
- }
+ if (keys != null) { // keys = duplicated values
+ for (int i = 0; i < keys.length; i++) {
+ String duplKey = keys[i];
+ if (!key.equals(duplKey)) {
+ buf.append(" · ");
+ buf.append(duplKey);
+ buf.append(" (" + UIUtils.getDisplayName(locale) + ")");
+ buf.append("\n");
+ }
+ }
+ MessageDialog.openInformation(
+ Display.getDefault().getActiveShell(), "Duplicate value",
+ buf.toString());
+ }
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowMissingAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowMissingAction.java
index 31b9485..691f1c7 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowMissingAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowMissingAction.java
@@ -17,10 +17,9 @@
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
-
/**
* @author Pascal Essiembre
- *
+ *
*/
public class ShowMissingAction extends Action {
@@ -30,19 +29,18 @@
public ShowMissingAction(String key, Locale locale) {
super();
setText("Key missing a value.");
- setImageDescriptor(
- UIUtils.getImageDescriptor("empty.gif"));
- setToolTipText("TODO put something here"); //TODO put tooltip
+ setImageDescriptor(UIUtils.getImageDescriptor("empty.gif"));
+ setToolTipText("TODO put something here"); // TODO put tooltip
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
- MessageDialog.openInformation(
- Display.getDefault().getActiveShell(),
- "Missing value",
- "Key missing a value");
+ MessageDialog.openInformation(Display.getDefault().getActiveShell(),
+ "Missing value", "Key missing a value");
}
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowSimilarAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowSimilarAction.java
index c4910be..6a65986 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowSimilarAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowSimilarAction.java
@@ -17,17 +17,16 @@
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
-
/**
* @author Pascal Essiembre
- *
+ *
*/
public class ShowSimilarAction extends Action {
private final String[] keys;
private final String key;
private final Locale locale;
-
+
/**
*
*/
@@ -37,16 +36,18 @@
this.key = key;
this.locale = locale;
setText("Show similar keys.");
- setImageDescriptor(
- UIUtils.getImageDescriptor("similar.gif"));
- setToolTipText("TODO put something here"); //TODO put tooltip
+ setImageDescriptor(UIUtils.getImageDescriptor("similar.gif"));
+ setToolTipText("TODO put something here"); // TODO put tooltip
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
- StringBuffer buf = new StringBuffer("\"" + key + "\" (" + UIUtils.getDisplayName(locale) + ") has similar "
+ StringBuffer buf = new StringBuffer("\"" + key + "\" ("
+ + UIUtils.getDisplayName(locale) + ") has similar "
+ "value as the following key(s): \n\n");
for (int i = 0; i < keys.length; i++) {
String similarKey = keys[i];
@@ -57,10 +58,8 @@
buf.append("\n");
}
}
- MessageDialog.openInformation(
- Display.getDefault().getActiveShell(),
- "Similar value",
- buf.toString());
+ MessageDialog.openInformation(Display.getDefault().getActiveShell(),
+ "Similar value", buf.toString());
}
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditor.java
index bb15e63..59bdf5b 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditor.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditor.java
@@ -68,495 +68,500 @@
public class MessagesEditor extends MultiPageEditorPart implements IGotoMarker,
IMessagesEditor {
- /** Editor ID, as defined in plugin.xml. */
- public static final String EDITOR_ID = "org.eclilpse.babel.editor.editor.MessagesEditor"; //$NON-NLS-1$
+ /** Editor ID, as defined in plugin.xml. */
+ public static final String EDITOR_ID = "org.eclilpse.babel.editor.editor.MessagesEditor"; //$NON-NLS-1$
- private String selectedKey;
- private List<IMessagesEditorChangeListener> changeListeners = new ArrayList<IMessagesEditorChangeListener>(
- 2);
+ private String selectedKey;
+ private List<IMessagesEditorChangeListener> changeListeners = new ArrayList<IMessagesEditorChangeListener>(
+ 2);
- /** MessagesBundle group. */
- private MessagesBundleGroup messagesBundleGroup;
+ /** MessagesBundle group. */
+ private MessagesBundleGroup messagesBundleGroup;
- /** Page with key tree and text fields for all locales. */
- private I18NPage i18nPage;
- private final List<Locale> localesIndex = new ArrayList<Locale>();
- private final List<ITextEditor> textEditorsIndex = new ArrayList<ITextEditor>();
+ /** Page with key tree and text fields for all locales. */
+ private I18NPage i18nPage;
+ private final List<Locale> localesIndex = new ArrayList<Locale>();
+ private final List<ITextEditor> textEditorsIndex = new ArrayList<ITextEditor>();
- private MessagesBundleGroupOutline outline;
+ private MessagesBundleGroupOutline outline;
- private MessagesEditorMarkers markers;
+ private MessagesEditorMarkers markers;
- private AbstractKeyTreeModel keyTreeModel;
+ private AbstractKeyTreeModel keyTreeModel;
- private IFile file; // init
+ private IFile file; // init
- private boolean updateSelectedKey;
+ private boolean updateSelectedKey;
- /**
- * Creates a multi-page editor example.
- */
- public MessagesEditor() {
- super();
- outline = new MessagesBundleGroupOutline(this);
- }
+ /**
+ * Creates a multi-page editor example.
+ */
+ public MessagesEditor() {
+ super();
+ outline = new MessagesBundleGroupOutline(this);
+ }
- public MessagesEditorMarkers getMarkers() {
- return markers;
- }
+ public MessagesEditorMarkers getMarkers() {
+ return markers;
+ }
- private IPropertyChangeListener preferenceListener;
+ private IPropertyChangeListener preferenceListener;
- /**
- * The <code>MultiPageEditorExample</code> implementation of this method
- * checks that the input is an instance of <code>IFileEditorInput</code>.
- */
- @Override
- public void init(IEditorSite site, IEditorInput editorInput)
- throws PartInitException {
+ /**
+ * The <code>MultiPageEditorExample</code> implementation of this method
+ * checks that the input is an instance of <code>IFileEditorInput</code>.
+ */
+ @Override
+ public void init(IEditorSite site, IEditorInput editorInput)
+ throws PartInitException {
- if (editorInput instanceof IFileEditorInput) {
- file = ((IFileEditorInput) editorInput).getFile();
- if (MsgEditorPreferences.getInstance()
- .isBuilderSetupAutomatically()) {
- IProject p = file.getProject();
- if (p != null && p.isAccessible()) {
- ToggleNatureAction
- .addOrRemoveNatureOnProject(p, true, true);
- }
- }
- try {
- messagesBundleGroup = MessagesBundleGroupFactory
- .createBundleGroup(site, file);
- } catch (MessageException e) {
- throw new PartInitException("Cannot create bundle group.", e); //$NON-NLS-1$
- }
- // register bundle group listener to refresh editor when new a bundle is added
- messagesBundleGroup.addMessagesBundleGroupListener(new MessagesBundleGroupAdapter() {
- @Override
- public void messagesBundleAdded(MessagesBundle messagesBundle) {
- addMessagesBundle(messagesBundle, messagesBundle.getLocale());
- // refresh i18n page
- i18nPage.addI18NEntry(MessagesEditor.this, messagesBundle.getLocale());
- }
- });
- markers = new MessagesEditorMarkers(messagesBundleGroup);
- setPartName(messagesBundleGroup.getName());
- setTitleImage(UIUtils.getImage(UIUtils.IMAGE_RESOURCE_BUNDLE));
- closeIfAreadyOpen(site, file);
- super.init(site, editorInput);
- // TODO figure out model to use based on preferences
- keyTreeModel = new AbstractKeyTreeModel(messagesBundleGroup);
- // markerManager = new RBEMarkerManager(this);
- } else {
- throw new PartInitException(
- "Invalid Input: Must be IFileEditorInput"); //$NON-NLS-1$
- }
- }
+ if (editorInput instanceof IFileEditorInput) {
+ file = ((IFileEditorInput) editorInput).getFile();
+ if (MsgEditorPreferences.getInstance()
+ .isBuilderSetupAutomatically()) {
+ IProject p = file.getProject();
+ if (p != null && p.isAccessible()) {
+ ToggleNatureAction
+ .addOrRemoveNatureOnProject(p, true, true);
+ }
+ }
+ try {
+ messagesBundleGroup = MessagesBundleGroupFactory
+ .createBundleGroup(site, file);
+ } catch (MessageException e) {
+ throw new PartInitException("Cannot create bundle group.", e); //$NON-NLS-1$
+ }
+ // register bundle group listener to refresh editor when new a
+ // bundle is added
+ messagesBundleGroup
+ .addMessagesBundleGroupListener(new MessagesBundleGroupAdapter() {
+ @Override
+ public void messagesBundleAdded(
+ MessagesBundle messagesBundle) {
+ addMessagesBundle(messagesBundle,
+ messagesBundle.getLocale());
+ // refresh i18n page
+ i18nPage.addI18NEntry(MessagesEditor.this,
+ messagesBundle.getLocale());
+ }
+ });
+ markers = new MessagesEditorMarkers(messagesBundleGroup);
+ setPartName(messagesBundleGroup.getName());
+ setTitleImage(UIUtils.getImage(UIUtils.IMAGE_RESOURCE_BUNDLE));
+ closeIfAreadyOpen(site, file);
+ super.init(site, editorInput);
+ // TODO figure out model to use based on preferences
+ keyTreeModel = new AbstractKeyTreeModel(messagesBundleGroup);
+ // markerManager = new RBEMarkerManager(this);
+ } else {
+ throw new PartInitException(
+ "Invalid Input: Must be IFileEditorInput"); //$NON-NLS-1$
+ }
+ }
- // public RBEMarkerManager getMarkerManager() {
- // return markerManager;
- // }
+ // public RBEMarkerManager getMarkerManager() {
+ // return markerManager;
+ // }
- /**
- * Creates the pages of the multi-page editor.
- */
- @Override
- protected void createPages() {
- // Create I18N page
- i18nPage = new I18NPage(getContainer(), SWT.NONE, this);
- int index = addPage(i18nPage);
- setPageText(index, MessagesEditorPlugin.getString("editor.properties")); //$NON-NLS-1$
- setPageImage(index, UIUtils.getImage(UIUtils.IMAGE_RESOURCE_BUNDLE));
+ /**
+ * Creates the pages of the multi-page editor.
+ */
+ @Override
+ protected void createPages() {
+ // Create I18N page
+ i18nPage = new I18NPage(getContainer(), SWT.NONE, this);
+ int index = addPage(i18nPage);
+ setPageText(index, MessagesEditorPlugin.getString("editor.properties")); //$NON-NLS-1$
+ setPageImage(index, UIUtils.getImage(UIUtils.IMAGE_RESOURCE_BUNDLE));
- // Create text editor pages for each locales
- Locale[] locales = messagesBundleGroup.getLocales();
- // first: sort the locales.
- UIUtils.sortLocales(locales);
- // second: filter+sort them according to the filter preferences.
- locales = UIUtils.filterLocales(locales);
- for (int i = 0; i < locales.length; i++) {
- Locale locale = locales[i];
- MessagesBundle messagesBundle = (MessagesBundle) messagesBundleGroup
- .getMessagesBundle(locale);
- addMessagesBundle(messagesBundle, locale);
- }
- }
+ // Create text editor pages for each locales
+ Locale[] locales = messagesBundleGroup.getLocales();
+ // first: sort the locales.
+ UIUtils.sortLocales(locales);
+ // second: filter+sort them according to the filter preferences.
+ locales = UIUtils.filterLocales(locales);
+ for (int i = 0; i < locales.length; i++) {
+ Locale locale = locales[i];
+ MessagesBundle messagesBundle = (MessagesBundle) messagesBundleGroup
+ .getMessagesBundle(locale);
+ addMessagesBundle(messagesBundle, locale);
+ }
+ }
- /**
- * Creates a new text editor for the messages bundle and locale, which gets added to a new page
- */
- private void addMessagesBundle(MessagesBundle messagesBundle, Locale locale) {
- try {
- IMessagesResource resource = messagesBundle.getResource();
- TextEditor textEditor = (TextEditor) resource.getSource();
- int index = addPage(textEditor, textEditor.getEditorInput());
- setPageText(index,
- UIUtils.getDisplayName(messagesBundle.getLocale()));
- setPageImage(index,
- UIUtils.getImage(UIUtils.IMAGE_PROPERTIES_FILE));
- localesIndex.add(locale);
- textEditorsIndex.add(textEditor);
- } catch (PartInitException e) {
- ErrorDialog.openError(getSite().getShell(),
- "Error creating text editor page.", //$NON-NLS-1$
- null, e.getStatus());
- }
- }
-
- /**
- * Called when the editor's pages need to be reloaded. For example when the
- * filters of locale is changed.
- * <p>
- * Currently this only reloads the index page. TODO: remove and add the new
- * locales? it actually looks quite hard to do.
- * </p>
- */
- public void reloadDisplayedContents() {
- super.removePage(0);
- int currentlyActivePage = super.getActivePage();
- i18nPage.dispose();
- i18nPage = new I18NPage(getContainer(), SWT.NONE, this);
- super.addPage(0, i18nPage);
- if (currentlyActivePage == 0) {
- super.setActivePage(currentlyActivePage);
- }
- }
+ /**
+ * Creates a new text editor for the messages bundle and locale, which gets
+ * added to a new page
+ */
+ private void addMessagesBundle(MessagesBundle messagesBundle, Locale locale) {
+ try {
+ IMessagesResource resource = messagesBundle.getResource();
+ TextEditor textEditor = (TextEditor) resource.getSource();
+ int index = addPage(textEditor, textEditor.getEditorInput());
+ setPageText(index,
+ UIUtils.getDisplayName(messagesBundle.getLocale()));
+ setPageImage(index, UIUtils.getImage(UIUtils.IMAGE_PROPERTIES_FILE));
+ localesIndex.add(locale);
+ textEditorsIndex.add(textEditor);
+ } catch (PartInitException e) {
+ ErrorDialog.openError(getSite().getShell(),
+ "Error creating text editor page.", //$NON-NLS-1$
+ null, e.getStatus());
+ }
+ }
- /**
- * Saves the multi-page editor's document.
- */
- @Override
- public void doSave(IProgressMonitor monitor) {
- for (ITextEditor textEditor : textEditorsIndex) {
- textEditor.doSave(monitor);
- }
+ /**
+ * Called when the editor's pages need to be reloaded. For example when the
+ * filters of locale is changed.
+ * <p>
+ * Currently this only reloads the index page. TODO: remove and add the new
+ * locales? it actually looks quite hard to do.
+ * </p>
+ */
+ public void reloadDisplayedContents() {
+ super.removePage(0);
+ int currentlyActivePage = super.getActivePage();
+ i18nPage.dispose();
+ i18nPage = new I18NPage(getContainer(), SWT.NONE, this);
+ super.addPage(0, i18nPage);
+ if (currentlyActivePage == 0) {
+ super.setActivePage(currentlyActivePage);
+ }
+ }
- try { // [alst] remove in near future
- Thread.sleep(200);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ /**
+ * Saves the multi-page editor's document.
+ */
+ @Override
+ public void doSave(IProgressMonitor monitor) {
+ for (ITextEditor textEditor : textEditorsIndex) {
+ textEditor.doSave(monitor);
+ }
- updateSelectedKey = true;
+ try { // [alst] remove in near future
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
- RBManager instance = RBManager.getInstance(messagesBundleGroup
- .getProjectName());
+ updateSelectedKey = true;
- refreshKeyTreeModel(); // keeps editor and I18NPage in sync
+ RBManager instance = RBManager.getInstance(messagesBundleGroup
+ .getProjectName());
- instance.fireEditorSaved();
+ refreshKeyTreeModel(); // keeps editor and I18NPage in sync
- // // maybe new init?
- }
+ instance.fireEditorSaved();
- private void refreshKeyTreeModel() {
- String selectedKey = getSelectedKey(); // memorize
+ // // maybe new init?
+ }
- if (messagesBundleGroup == null) {
- messagesBundleGroup = MessagesBundleGroupFactory.createBundleGroup(
- (IEditorSite) getSite(), file);
- }
+ private void refreshKeyTreeModel() {
+ String selectedKey = getSelectedKey(); // memorize
- AbstractKeyTreeModel oldModel = this.keyTreeModel;
- this.keyTreeModel = new AbstractKeyTreeModel(messagesBundleGroup);
+ if (messagesBundleGroup == null) {
+ messagesBundleGroup = MessagesBundleGroupFactory.createBundleGroup(
+ (IEditorSite) getSite(), file);
+ }
- for (IMessagesEditorChangeListener listener : changeListeners) {
- listener.keyTreeModelChanged(oldModel, this.keyTreeModel);
- }
+ AbstractKeyTreeModel oldModel = this.keyTreeModel;
+ this.keyTreeModel = new AbstractKeyTreeModel(messagesBundleGroup);
- i18nPage.getTreeViewer().expandAll();
+ for (IMessagesEditorChangeListener listener : changeListeners) {
+ listener.keyTreeModelChanged(oldModel, this.keyTreeModel);
+ }
- if (selectedKey != null) {
- setSelectedKey(selectedKey);
- }
- }
+ i18nPage.getTreeViewer().expandAll();
- /**
- * @see org.eclipse.ui.ISaveablePart#doSaveAs()
- */
- @Override
- public void doSaveAs() {
- // Save As not allowed.
- }
+ if (selectedKey != null) {
+ setSelectedKey(selectedKey);
+ }
+ }
- /**
- * @see org.eclipse.ui.ISaveablePart#isSaveAsAllowed()
- */
- @Override
- public boolean isSaveAsAllowed() {
- return false;
- }
+ /**
+ * @see org.eclipse.ui.ISaveablePart#doSaveAs()
+ */
+ @Override
+ public void doSaveAs() {
+ // Save As not allowed.
+ }
- /**
- * Change current page based on locale. If there is no editors associated
- * with current locale, do nothing.
- *
- * @param locale
- * locale used to identify the page to change to
- */
- public void setActivePage(Locale locale) {
- int index = localesIndex.indexOf(locale);
- if (index > -1) {
- setActivePage(index + 1);
- }
- }
+ /**
+ * @see org.eclipse.ui.ISaveablePart#isSaveAsAllowed()
+ */
+ @Override
+ public boolean isSaveAsAllowed() {
+ return false;
+ }
- /**
- * @see org.eclipse.ui.ide.IGotoMarker#gotoMarker(org.eclipse.core.resources.IMarker)
- */
- public void gotoMarker(IMarker marker) {
- // String key = marker.getAttribute(RBEMarker.KEY, "");
- // if (key != null && key.length() > 0) {
- // setActivePage(0);
- // setSelectedKey(key);
- // getI18NPage().selectLocale(BabelUtils.parseLocale(
- // marker.getAttribute(RBEMarker.LOCALE, "")));
- // } else {
- IResource resource = marker.getResource();
- Locale[] locales = messagesBundleGroup.getLocales();
- for (int i = 0; i < locales.length; i++) {
- IMessagesResource messagesResource = ((MessagesBundle) messagesBundleGroup
- .getMessagesBundle(locales[i])).getResource();
- if (messagesResource instanceof EclipsePropertiesEditorResource) {
- EclipsePropertiesEditorResource propFile = (EclipsePropertiesEditorResource) messagesResource;
- if (resource.equals(propFile.getResource())) {
- // ok we got the locale.
- // try to open the master i18n page and select the
- // corresponding key.
- try {
- String key = (String) marker
- .getAttribute(IMarker.LOCATION);
- if (key != null && key.length() > 0) {
- getI18NPage().selectLocale(locales[i]);
- setActivePage(0);
- setSelectedKey(key);
- return;
- }
- } catch (Exception e) {
- e.printStackTrace();// something better.s
- }
- // it did not work... fall back to the text editor.
- setActivePage(locales[i]);
- IDE.gotoMarker((IEditorPart) propFile.getSource(), marker);
- break;
- }
- }
- }
- // }
- }
+ /**
+ * Change current page based on locale. If there is no editors associated
+ * with current locale, do nothing.
+ *
+ * @param locale
+ * locale used to identify the page to change to
+ */
+ public void setActivePage(Locale locale) {
+ int index = localesIndex.indexOf(locale);
+ if (index > -1) {
+ setActivePage(index + 1);
+ }
+ }
- /**
- * Calculates the contents of page GUI page when it is activated.
- */
- @Override
- protected void pageChange(int newPageIndex) {
- super.pageChange(newPageIndex);
- if (newPageIndex != 0) { // if we just want the default page -> == 1
- setSelection(newPageIndex);
- } else if (newPageIndex == 0 && updateSelectedKey) {
- // TODO: find better way
- for (IMessagesBundle bundle : messagesBundleGroup
- .getMessagesBundles()) {
- RBManager.getInstance(messagesBundleGroup.getProjectName())
- .fireResourceChanged(bundle);
- }
- updateSelectedKey = false;
- }
+ /**
+ * @see org.eclipse.ui.ide.IGotoMarker#gotoMarker(org.eclipse.core.resources.IMarker)
+ */
+ public void gotoMarker(IMarker marker) {
+ // String key = marker.getAttribute(RBEMarker.KEY, "");
+ // if (key != null && key.length() > 0) {
+ // setActivePage(0);
+ // setSelectedKey(key);
+ // getI18NPage().selectLocale(BabelUtils.parseLocale(
+ // marker.getAttribute(RBEMarker.LOCALE, "")));
+ // } else {
+ IResource resource = marker.getResource();
+ Locale[] locales = messagesBundleGroup.getLocales();
+ for (int i = 0; i < locales.length; i++) {
+ IMessagesResource messagesResource = ((MessagesBundle) messagesBundleGroup
+ .getMessagesBundle(locales[i])).getResource();
+ if (messagesResource instanceof EclipsePropertiesEditorResource) {
+ EclipsePropertiesEditorResource propFile = (EclipsePropertiesEditorResource) messagesResource;
+ if (resource.equals(propFile.getResource())) {
+ // ok we got the locale.
+ // try to open the master i18n page and select the
+ // corresponding key.
+ try {
+ String key = (String) marker
+ .getAttribute(IMarker.LOCATION);
+ if (key != null && key.length() > 0) {
+ getI18NPage().selectLocale(locales[i]);
+ setActivePage(0);
+ setSelectedKey(key);
+ return;
+ }
+ } catch (Exception e) {
+ e.printStackTrace();// something better.s
+ }
+ // it did not work... fall back to the text editor.
+ setActivePage(locales[i]);
+ IDE.gotoMarker((IEditorPart) propFile.getSource(), marker);
+ break;
+ }
+ }
+ }
+ // }
+ }
- // if (newPageIndex == 0) {
- // resourceMediator.reloadProperties();
- // i18nPage.refreshTextBoxes();
- // }
- }
+ /**
+ * Calculates the contents of page GUI page when it is activated.
+ */
+ @Override
+ protected void pageChange(int newPageIndex) {
+ super.pageChange(newPageIndex);
+ if (newPageIndex != 0) { // if we just want the default page -> == 1
+ setSelection(newPageIndex);
+ } else if (newPageIndex == 0 && updateSelectedKey) {
+ // TODO: find better way
+ for (IMessagesBundle bundle : messagesBundleGroup
+ .getMessagesBundles()) {
+ RBManager.getInstance(messagesBundleGroup.getProjectName())
+ .fireResourceChanged(bundle);
+ }
+ updateSelectedKey = false;
+ }
- private void setSelection(int newPageIndex) {
- ITextEditor editor = textEditorsIndex.get(--newPageIndex);
- String selectedKey = getSelectedKey();
- if (selectedKey != null) {
- if (editor.getEditorInput() instanceof FileEditorInput) {
- FileEditorInput input = (FileEditorInput) editor
- .getEditorInput();
- try {
- BufferedReader reader = new BufferedReader(
- new InputStreamReader(input.getFile().getContents()));
- String line = "";
- int selectionIndex = 0;
- boolean found = false;
+ // if (newPageIndex == 0) {
+ // resourceMediator.reloadProperties();
+ // i18nPage.refreshTextBoxes();
+ // }
+ }
- while ((line = reader.readLine()) != null) {
- int index = line.indexOf('=');
- if (index != -1) {
- if (selectedKey.equals(line.substring(0, index)
- .trim())) {
- found = true;
- break;
- }
- }
- selectionIndex += line.length() + 2; // + \r\n
- }
+ private void setSelection(int newPageIndex) {
+ ITextEditor editor = textEditorsIndex.get(--newPageIndex);
+ String selectedKey = getSelectedKey();
+ if (selectedKey != null) {
+ if (editor.getEditorInput() instanceof FileEditorInput) {
+ FileEditorInput input = (FileEditorInput) editor
+ .getEditorInput();
+ try {
+ BufferedReader reader = new BufferedReader(
+ new InputStreamReader(input.getFile().getContents()));
+ String line = "";
+ int selectionIndex = 0;
+ boolean found = false;
- if (found) {
- editor.selectAndReveal(selectionIndex, 0);
- }
- } catch (CoreException e) {
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
+ while ((line = reader.readLine()) != null) {
+ int index = line.indexOf('=');
+ if (index != -1) {
+ if (selectedKey.equals(line.substring(0, index)
+ .trim())) {
+ found = true;
+ break;
+ }
+ }
+ selectionIndex += line.length() + 2; // + \r\n
+ }
- }
+ if (found) {
+ editor.selectAndReveal(selectionIndex, 0);
+ }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ }
- /**
- * Is the given file a member of this resource bundle.
- *
- * @param file
- * file to test
- * @return <code>true</code> if file is part of bundle
- */
- public boolean isBundleMember(IFile file) {
- // return resourceMediator.isResource(file);
- return false;
- }
+ }
- private void closeIfAreadyOpen(IEditorSite site, IFile file) {
- IWorkbenchPage[] pages = site.getWorkbenchWindow().getPages();
- for (int i = 0; i < pages.length; i++) {
- IWorkbenchPage page = pages[i];
- IEditorReference[] editors = page.getEditorReferences();
- for (int j = 0; j < editors.length; j++) {
- IEditorPart editor = editors[j].getEditor(false);
- if (editor instanceof MessagesEditor) {
- MessagesEditor rbe = (MessagesEditor) editor;
- if (rbe.isBundleMember(file)) {
- page.closeEditor(editor, true);
- }
- }
- }
- }
- }
+ /**
+ * Is the given file a member of this resource bundle.
+ *
+ * @param file
+ * file to test
+ * @return <code>true</code> if file is part of bundle
+ */
+ public boolean isBundleMember(IFile file) {
+ // return resourceMediator.isResource(file);
+ return false;
+ }
- /**
- * @see org.eclipse.ui.IWorkbenchPart#dispose()
- */
- @Override
- public void dispose() {
- for (IMessagesEditorChangeListener listener : changeListeners) {
- listener.editorDisposed();
- }
- i18nPage.dispose();
- for (ITextEditor textEditor : textEditorsIndex) {
- textEditor.dispose();
- }
- }
+ private void closeIfAreadyOpen(IEditorSite site, IFile file) {
+ IWorkbenchPage[] pages = site.getWorkbenchWindow().getPages();
+ for (int i = 0; i < pages.length; i++) {
+ IWorkbenchPage page = pages[i];
+ IEditorReference[] editors = page.getEditorReferences();
+ for (int j = 0; j < editors.length; j++) {
+ IEditorPart editor = editors[j].getEditor(false);
+ if (editor instanceof MessagesEditor) {
+ MessagesEditor rbe = (MessagesEditor) editor;
+ if (rbe.isBundleMember(file)) {
+ page.closeEditor(editor, true);
+ }
+ }
+ }
+ }
+ }
- /**
- * @return Returns the selectedKey.
- */
- public String getSelectedKey() {
- return selectedKey;
- }
+ /**
+ * @see org.eclipse.ui.IWorkbenchPart#dispose()
+ */
+ @Override
+ public void dispose() {
+ for (IMessagesEditorChangeListener listener : changeListeners) {
+ listener.editorDisposed();
+ }
+ i18nPage.dispose();
+ for (ITextEditor textEditor : textEditorsIndex) {
+ textEditor.dispose();
+ }
+ }
- /**
- * @param selectedKey
- * The selectedKey to set.
- */
- public void setSelectedKey(String activeKey) {
- if ((selectedKey == null && activeKey != null)
- || (selectedKey != null && activeKey == null)
- || (selectedKey != null && !selectedKey.equals(activeKey))) {
- String oldKey = this.selectedKey;
- this.selectedKey = activeKey;
- for (IMessagesEditorChangeListener listener : changeListeners) {
- listener.selectedKeyChanged(oldKey, activeKey);
- }
- }
- }
+ /**
+ * @return Returns the selectedKey.
+ */
+ public String getSelectedKey() {
+ return selectedKey;
+ }
- public void addChangeListener(IMessagesEditorChangeListener listener) {
- changeListeners.add(0, listener);
- }
+ /**
+ * @param selectedKey
+ * The selectedKey to set.
+ */
+ public void setSelectedKey(String activeKey) {
+ if ((selectedKey == null && activeKey != null)
+ || (selectedKey != null && activeKey == null)
+ || (selectedKey != null && !selectedKey.equals(activeKey))) {
+ String oldKey = this.selectedKey;
+ this.selectedKey = activeKey;
+ for (IMessagesEditorChangeListener listener : changeListeners) {
+ listener.selectedKeyChanged(oldKey, activeKey);
+ }
+ }
+ }
- public void removeChangeListener(IMessagesEditorChangeListener listener) {
- changeListeners.remove(listener);
- }
+ public void addChangeListener(IMessagesEditorChangeListener listener) {
+ changeListeners.add(0, listener);
+ }
- public Collection<IMessagesEditorChangeListener> getChangeListeners() {
- return changeListeners;
- }
+ public void removeChangeListener(IMessagesEditorChangeListener listener) {
+ changeListeners.remove(listener);
+ }
- /**
- * @return Returns the messagesBundleGroup.
- */
- public MessagesBundleGroup getBundleGroup() {
- return messagesBundleGroup;
- }
+ public Collection<IMessagesEditorChangeListener> getChangeListeners() {
+ return changeListeners;
+ }
- /**
- * @return Returns the keyTreeModel.
- */
- public AbstractKeyTreeModel getKeyTreeModel() {
- return keyTreeModel;
- }
+ /**
+ * @return Returns the messagesBundleGroup.
+ */
+ public MessagesBundleGroup getBundleGroup() {
+ return messagesBundleGroup;
+ }
- /**
- * @param keyTreeModel
- * The keyTreeModel to set.
- */
- public void setKeyTreeModel(AbstractKeyTreeModel newKeyTreeModel) {
- if ((this.keyTreeModel == null && newKeyTreeModel != null)
- || (keyTreeModel != null && newKeyTreeModel == null)
- || (!keyTreeModel.equals(newKeyTreeModel))) {
- AbstractKeyTreeModel oldModel = this.keyTreeModel;
- this.keyTreeModel = newKeyTreeModel;
- for (IMessagesEditorChangeListener listener : changeListeners) {
- listener.keyTreeModelChanged(oldModel, newKeyTreeModel);
- }
- }
- }
+ /**
+ * @return Returns the keyTreeModel.
+ */
+ public AbstractKeyTreeModel getKeyTreeModel() {
+ return keyTreeModel;
+ }
- public I18NPage getI18NPage() {
- return i18nPage;
- }
+ /**
+ * @param keyTreeModel
+ * The keyTreeModel to set.
+ */
+ public void setKeyTreeModel(AbstractKeyTreeModel newKeyTreeModel) {
+ if ((this.keyTreeModel == null && newKeyTreeModel != null)
+ || (keyTreeModel != null && newKeyTreeModel == null)
+ || (!keyTreeModel.equals(newKeyTreeModel))) {
+ AbstractKeyTreeModel oldModel = this.keyTreeModel;
+ this.keyTreeModel = newKeyTreeModel;
+ for (IMessagesEditorChangeListener listener : changeListeners) {
+ listener.keyTreeModelChanged(oldModel, newKeyTreeModel);
+ }
+ }
+ }
- /**
- * one of the SHOW_* constants defined in the
- * {@link IMessagesEditorChangeListener}
- */
- private int showOnlyMissingAndUnusedKeys = IMessagesEditorChangeListener.SHOW_ALL;
+ public I18NPage getI18NPage() {
+ return i18nPage;
+ }
- /**
- * @return true when only unused and missing keys should be displayed. flase
- * by default.
- */
- public int isShowOnlyUnusedAndMissingKeys() {
- return showOnlyMissingAndUnusedKeys;
- }
+ /**
+ * one of the SHOW_* constants defined in the
+ * {@link IMessagesEditorChangeListener}
+ */
+ private int showOnlyMissingAndUnusedKeys = IMessagesEditorChangeListener.SHOW_ALL;
- public void setShowOnlyUnusedMissingKeys(int showFlag) {
- showOnlyMissingAndUnusedKeys = showFlag;
- for (IMessagesEditorChangeListener listener : getChangeListeners()) {
- listener.showOnlyUnusedAndMissingChanged(showFlag);
- }
- }
+ /**
+ * @return true when only unused and missing keys should be displayed. flase
+ * by default.
+ */
+ public int isShowOnlyUnusedAndMissingKeys() {
+ return showOnlyMissingAndUnusedKeys;
+ }
- @Override
- public Object getAdapter(Class adapter) {
- Object obj = super.getAdapter(adapter);
- if (obj == null) {
- if (IContentOutlinePage.class.equals(adapter)) {
- return (outline);
- }
- }
- return (obj);
- }
+ public void setShowOnlyUnusedMissingKeys(int showFlag) {
+ showOnlyMissingAndUnusedKeys = showFlag;
+ for (IMessagesEditorChangeListener listener : getChangeListeners()) {
+ listener.showOnlyUnusedAndMissingChanged(showFlag);
+ }
+ }
- public ITextEditor getTextEditor(Locale locale) {
- int index = localesIndex.indexOf(locale);
- return textEditorsIndex.get(index);
- }
+ @Override
+ public Object getAdapter(Class adapter) {
+ Object obj = super.getAdapter(adapter);
+ if (obj == null) {
+ if (IContentOutlinePage.class.equals(adapter)) {
+ return (outline);
+ }
+ }
+ return (obj);
+ }
+
+ public ITextEditor getTextEditor(Locale locale) {
+ int index = localesIndex.indexOf(locale);
+ return textEditorsIndex.get(index);
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorChangeAdapter.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorChangeAdapter.java
index 721d120..ae1baf0 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorChangeAdapter.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorChangeAdapter.java
@@ -15,9 +15,10 @@
/**
* @author Pascal Essiembre
- *
+ *
*/
-public class MessagesEditorChangeAdapter implements IMessagesEditorChangeListener {
+public class MessagesEditorChangeAdapter implements
+ IMessagesEditorChangeListener {
/**
*
@@ -32,6 +33,7 @@
public void keyTreeVisibleChanged(boolean visible) {
// do nothing
}
+
/**
* @see org.eclipse.babel.editor.IMessagesEditorChangeListener#keyTreeVisibleChanged(boolean)
*/
@@ -40,19 +42,26 @@
}
/**
- * @see org.eclipse.babel.editor.IMessagesEditorChangeListener#selectedKeyChanged(java.lang.String, java.lang.String)
+ * @see org.eclipse.babel.editor.IMessagesEditorChangeListener#selectedKeyChanged(java.lang.String,
+ * java.lang.String)
*/
public void selectedKeyChanged(String oldKey, String newKey) {
// do nothing
}
- /* (non-Javadoc)
- * @see org.eclilpse.babel.editor.editor.IMessagesEditorChangeListener#keyTreeModelChanged(org.eclipse.babel.core.message.internal.tree.internal.IKeyTreeModel, org.eclipse.babel.core.message.internal.tree.internal.IKeyTreeModel)
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclilpse.babel.editor.editor.IMessagesEditorChangeListener#
+ * keyTreeModelChanged
+ * (org.eclipse.babel.core.message.internal.tree.internal.IKeyTreeModel,
+ * org.eclipse.babel.core.message.internal.tree.internal.IKeyTreeModel)
*/
- public void keyTreeModelChanged(AbstractKeyTreeModel oldModel, AbstractKeyTreeModel newModel) {
+ public void keyTreeModelChanged(AbstractKeyTreeModel oldModel,
+ AbstractKeyTreeModel newModel) {
// do nothing
}
-
+
/**
* @see org.eclipse.babel.editor.IMessagesEditorChangeListener#editorDisposed()
*/
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorContributor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorContributor.java
index 48bf6bf..c0c2135 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorContributor.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorContributor.java
@@ -29,154 +29,156 @@
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-
/**
- * Manages the installation/deinstallation of global actions for multi-page
- * editors. Responsible for the redirection of global actions to the active
- * editor.
- * Multi-page contributor replaces the contributors for the individual editors
- * in the multi-page editor.
+ * Manages the installation/deinstallation of global actions for multi-page
+ * editors. Responsible for the redirection of global actions to the active
+ * editor. Multi-page contributor replaces the contributors for the individual
+ * editors in the multi-page editor.
*/
-public class MessagesEditorContributor
- extends MultiPageEditorActionBarContributor {
- private IEditorPart activeEditorPart;
+public class MessagesEditorContributor extends
+ MultiPageEditorActionBarContributor {
+ private IEditorPart activeEditorPart;
private KeyTreeVisibleAction toggleKeyTreeAction;
private NewLocaleAction newLocaleAction;
private IMenuManager resourceBundleMenu;
private static String resourceBundleMenuID;
-
+
/** singleton: probably not the cleanest way to access it from anywhere. */
public static ActionGroup FILTERS = new FilterKeysActionGroup();
-
- /**
- * Creates a multi-page contributor.
- */
- public MessagesEditorContributor() {
- super();
- createActions();
- }
- /**
- * Returns the action registed with the given text editor.
- * @param editor eclipse text editor
- * @param actionID action id
- * @return IAction or null if editor is null.
- */
- protected IAction getAction(ITextEditor editor, String actionID) {
- return (editor == null ? null : editor.getAction(actionID));
- }
/**
- * @see MultiPageEditorActionBarContributor
- * #setActivePage(org.eclipse.ui.IEditorPart)
- */
- public void setActivePage(IEditorPart part) {
+ * Creates a multi-page contributor.
+ */
+ public MessagesEditorContributor() {
+ super();
+ createActions();
+ }
+
+ /**
+ * Returns the action registed with the given text editor.
+ *
+ * @param editor
+ * eclipse text editor
+ * @param actionID
+ * action id
+ * @return IAction or null if editor is null.
+ */
+ protected IAction getAction(ITextEditor editor, String actionID) {
+ return (editor == null ? null : editor.getAction(actionID));
+ }
+
+ /**
+ * @see MultiPageEditorActionBarContributor
+ * #setActivePage(org.eclipse.ui.IEditorPart)
+ */
+ public void setActivePage(IEditorPart part) {
if (activeEditorPart == part) {
- return;
+ return;
}
- activeEditorPart = part;
+ activeEditorPart = part;
- IActionBars actionBars = getActionBars();
- if (actionBars != null) {
+ IActionBars actionBars = getActionBars();
+ if (actionBars != null) {
- ITextEditor editor = (part instanceof ITextEditor)
- ? (ITextEditor) part : null;
+ ITextEditor editor = (part instanceof ITextEditor) ? (ITextEditor) part
+ : null;
- actionBars.setGlobalActionHandler(
- ActionFactory.DELETE.getId(),
- getAction(editor, ITextEditorActionConstants.DELETE));
- actionBars.setGlobalActionHandler(
- ActionFactory.UNDO.getId(),
- getAction(editor, ITextEditorActionConstants.UNDO));
- actionBars.setGlobalActionHandler(
- ActionFactory.REDO.getId(),
- getAction(editor, ITextEditorActionConstants.REDO));
- actionBars.setGlobalActionHandler(
- ActionFactory.CUT.getId(),
- getAction(editor, ITextEditorActionConstants.CUT));
- actionBars.setGlobalActionHandler(
- ActionFactory.COPY.getId(),
- getAction(editor, ITextEditorActionConstants.COPY));
- actionBars.setGlobalActionHandler(
- ActionFactory.PASTE.getId(),
- getAction(editor, ITextEditorActionConstants.PASTE));
- actionBars.setGlobalActionHandler(
- ActionFactory.SELECT_ALL.getId(),
- getAction(editor, ITextEditorActionConstants.SELECT_ALL));
- actionBars.setGlobalActionHandler(
- ActionFactory.FIND.getId(),
- getAction(editor, ITextEditorActionConstants.FIND));
- actionBars.setGlobalActionHandler(
- IDEActionFactory.BOOKMARK.getId(),
- getAction(editor, IDEActionFactory.BOOKMARK.getId()));
- actionBars.updateActionBars();
- }
- }
- private void createActions() {
-// sampleAction = new Action() {
-// public void run() {
-// MessageDialog.openInformation(null,
-// "ResourceBundle Editor Plug-in", "Sample Action Executed");
-// }
-// };
-// sampleAction.setText("Sample Action");
-// sampleAction.setToolTipText("Sample Action tool tip");
-// sampleAction.setImageDescriptor(
-// PlatformUI.getWorkbench().getSharedImages().
-// getImageDescriptor(IDE.SharedImages.IMG_OBJS_TASK_TSK));
-
+ actionBars.setGlobalActionHandler(ActionFactory.DELETE.getId(),
+ getAction(editor, ITextEditorActionConstants.DELETE));
+ actionBars.setGlobalActionHandler(ActionFactory.UNDO.getId(),
+ getAction(editor, ITextEditorActionConstants.UNDO));
+ actionBars.setGlobalActionHandler(ActionFactory.REDO.getId(),
+ getAction(editor, ITextEditorActionConstants.REDO));
+ actionBars.setGlobalActionHandler(ActionFactory.CUT.getId(),
+ getAction(editor, ITextEditorActionConstants.CUT));
+ actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(),
+ getAction(editor, ITextEditorActionConstants.COPY));
+ actionBars.setGlobalActionHandler(ActionFactory.PASTE.getId(),
+ getAction(editor, ITextEditorActionConstants.PASTE));
+ actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(),
+ getAction(editor, ITextEditorActionConstants.SELECT_ALL));
+ actionBars.setGlobalActionHandler(ActionFactory.FIND.getId(),
+ getAction(editor, ITextEditorActionConstants.FIND));
+ actionBars.setGlobalActionHandler(
+ IDEActionFactory.BOOKMARK.getId(),
+ getAction(editor, IDEActionFactory.BOOKMARK.getId()));
+ actionBars.updateActionBars();
+ }
+ }
+
+ private void createActions() {
+ // sampleAction = new Action() {
+ // public void run() {
+ // MessageDialog.openInformation(null,
+ // "ResourceBundle Editor Plug-in", "Sample Action Executed");
+ // }
+ // };
+ // sampleAction.setText("Sample Action");
+ // sampleAction.setToolTipText("Sample Action tool tip");
+ // sampleAction.setImageDescriptor(
+ // PlatformUI.getWorkbench().getSharedImages().
+ // getImageDescriptor(IDE.SharedImages.IMG_OBJS_TASK_TSK));
+
toggleKeyTreeAction = new KeyTreeVisibleAction();
newLocaleAction = new NewLocaleAction();
-
-// toggleKeyTreeAction.setText("Show/Hide Key Tree");
-// toggleKeyTreeAction.setToolTipText("Click to show/hide the key tree");
-// toggleKeyTreeAction.setImageDescriptor(
-// PlatformUI.getWorkbench().getSharedImages().
-// getImageDescriptor(IDE.SharedImages.IMG_OPEN_MARKER));
+ // toggleKeyTreeAction.setText("Show/Hide Key Tree");
+ // toggleKeyTreeAction.setToolTipText("Click to show/hide the key tree");
+ // toggleKeyTreeAction.setImageDescriptor(
+ // PlatformUI.getWorkbench().getSharedImages().
+ // getImageDescriptor(IDE.SharedImages.IMG_OPEN_MARKER));
}
- /**
- * @see org.eclipse.ui.part.EditorActionBarContributor
- * #contributeToMenu(org.eclipse.jface.action.IMenuManager)
- */
- public void contributeToMenu(IMenuManager manager) {
-// System.out.println("active editor part:" +activeEditorPart);
-// System.out.println("menu editor:" + rbEditor);
- resourceBundleMenu = new MenuManager("&Messages", resourceBundleMenuID);
- manager.prependToGroup(IWorkbenchActionConstants.M_EDIT, resourceBundleMenu);
- resourceBundleMenu.add(toggleKeyTreeAction);
- resourceBundleMenu.add(newLocaleAction);
-
- FILTERS.fillContextMenu(resourceBundleMenu);
- }
+
/**
* @see org.eclipse.ui.part.EditorActionBarContributor
- * #contributeToToolBar(org.eclipse.jface.action.IToolBarManager)
+ * #contributeToMenu(org.eclipse.jface.action.IMenuManager)
*/
- public void contributeToToolBar(IToolBarManager manager) {
-// System.out.println("toolbar get page:" + getPage());
-// System.out.println("toolbar editor:" + rbEditor);
- manager.add(new Separator());
-// manager.add(sampleAction);
- manager.add(toggleKeyTreeAction);
+ public void contributeToMenu(IMenuManager manager) {
+ // System.out.println("active editor part:" +activeEditorPart);
+ // System.out.println("menu editor:" + rbEditor);
+ resourceBundleMenu = new MenuManager("&Messages", resourceBundleMenuID);
+ manager.prependToGroup(IWorkbenchActionConstants.M_EDIT,
+ resourceBundleMenu);
+ resourceBundleMenu.add(toggleKeyTreeAction);
+ resourceBundleMenu.add(newLocaleAction);
+
+ FILTERS.fillContextMenu(resourceBundleMenu);
+ }
+
+ /**
+ * @see org.eclipse.ui.part.EditorActionBarContributor
+ * #contributeToToolBar(org.eclipse.jface.action.IToolBarManager)
+ */
+ public void contributeToToolBar(IToolBarManager manager) {
+ // System.out.println("toolbar get page:" + getPage());
+ // System.out.println("toolbar editor:" + rbEditor);
+ manager.add(new Separator());
+ // manager.add(sampleAction);
+ manager.add(toggleKeyTreeAction);
manager.add(newLocaleAction);
-
- ((FilterKeysActionGroup)FILTERS).fillActionBars(getActionBars());
- }
- /* (non-Javadoc)
- * @see org.eclipse.ui.part.MultiPageEditorActionBarContributor#setActiveEditor(org.eclipse.ui.IEditorPart)
+
+ ((FilterKeysActionGroup) FILTERS).fillActionBars(getActionBars());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.part.MultiPageEditorActionBarContributor#setActiveEditor
+ * (org.eclipse.ui.IEditorPart)
*/
public void setActiveEditor(IEditorPart part) {
super.setActiveEditor(part);
- MessagesEditor me = part instanceof MessagesEditor
- ? (MessagesEditor)part : null;
+ MessagesEditor me = part instanceof MessagesEditor ? (MessagesEditor) part
+ : null;
toggleKeyTreeAction.setEditor(me);
((FilterKeysActionGroup) FILTERS).setActiveEditor(part);
newLocaleAction.setEditor(me);
}
-
+
/**
* Groups the filter actions together.
*/
@@ -184,38 +186,43 @@
FilterKeysAction[] filtersAction = new FilterKeysAction[4];
public FilterKeysActionGroup() {
- filtersAction[0] = new FilterKeysAction(IMessagesEditorChangeListener.SHOW_ALL);
- filtersAction[1] = new FilterKeysAction(IMessagesEditorChangeListener.SHOW_ONLY_MISSING);
- filtersAction[2] = new FilterKeysAction(IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED);
- filtersAction[3] = new FilterKeysAction(IMessagesEditorChangeListener.SHOW_ONLY_UNUSED);
+ filtersAction[0] = new FilterKeysAction(
+ IMessagesEditorChangeListener.SHOW_ALL);
+ filtersAction[1] = new FilterKeysAction(
+ IMessagesEditorChangeListener.SHOW_ONLY_MISSING);
+ filtersAction[2] = new FilterKeysAction(
+ IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED);
+ filtersAction[3] = new FilterKeysAction(
+ IMessagesEditorChangeListener.SHOW_ONLY_UNUSED);
}
-
- public void fillActionBars(IActionBars actionBars) {
- for (int i = 0; i < filtersAction.length; i++) {
- actionBars.getToolBarManager().add(filtersAction[i]);
- }
- }
- public void fillContextMenu(IMenuManager menu) {
- MenuManager filters = new MenuManager("Filters");
- for (int i = 0; i < filtersAction.length; i++) {
- filters.add(filtersAction[i]);
- }
- menu.add(filters);
- }
+ public void fillActionBars(IActionBars actionBars) {
+ for (int i = 0; i < filtersAction.length; i++) {
+ actionBars.getToolBarManager().add(filtersAction[i]);
+ }
+ }
- public void updateActionBars() {
- for (int i = 0; i < filtersAction.length;i++) {
- filtersAction[i].update();
- }
- }
- public void setActiveEditor(IEditorPart part) {
- MessagesEditor me = part instanceof MessagesEditor
- ? (MessagesEditor)part : null;
- for (int i = 0; i < filtersAction.length; i++) {
- filtersAction[i].setEditor(me);
- }
- }
+ public void fillContextMenu(IMenuManager menu) {
+ MenuManager filters = new MenuManager("Filters");
+ for (int i = 0; i < filtersAction.length; i++) {
+ filters.add(filtersAction[i]);
+ }
+ menu.add(filters);
+ }
+
+ public void updateActionBars() {
+ for (int i = 0; i < filtersAction.length; i++) {
+ filtersAction[i].update();
+ }
+ }
+
+ public void setActiveEditor(IEditorPart part) {
+ MessagesEditor me = part instanceof MessagesEditor ? (MessagesEditor) part
+ : null;
+ for (int i = 0; i < filtersAction.length; i++) {
+ filtersAction[i].setEditor(me);
+ }
+ }
}
-
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorMarkers.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorMarkers.java
index f69c340..a4f018e 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorMarkers.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorMarkers.java
@@ -30,28 +30,31 @@
import org.eclipse.babel.editor.util.UIUtils;
import org.eclipse.swt.widgets.Display;
-
/**
* @author Pascal Essiembre
- *
+ *
*/
-public class MessagesEditorMarkers
- extends Observable implements IValidationMarkerStrategy {
+public class MessagesEditorMarkers extends Observable implements
+ IValidationMarkerStrategy {
-// private final Collection validationEvents = new ArrayList();
+ // private final Collection validationEvents = new ArrayList();
private final MessagesBundleGroup messagesBundleGroup;
-
- // private Map<String,Set<ValidationFailureEvent>> markersIndex = new HashMap();
- /** index is the name of the key. value is the collection of markers on that key */
+
+ // private Map<String,Set<ValidationFailureEvent>> markersIndex = new
+ // HashMap();
+ /**
+ * index is the name of the key. value is the collection of markers on that
+ * key
+ */
private Map<String, Collection<IMessageCheck>> markersIndex = new HashMap<String, Collection<IMessageCheck>>();
-
- /**
- * Maps a localized key (a locale and key pair) to the collection of markers
- * for that key and that locale. If no there are no markers for the key and
- * locale then there will be no entry in the map.
- */
+
+ /**
+ * Maps a localized key (a locale and key pair) to the collection of markers
+ * for that key and that locale. If no there are no markers for the key and
+ * locale then there will be no entry in the map.
+ */
private Map<String, Collection<IMessageCheck>> localizedMarkersMap = new HashMap<String, Collection<IMessageCheck>>();
-
+
/**
* @param messagesBundleGroup
*/
@@ -59,65 +62,70 @@
super();
this.messagesBundleGroup = messagesBundleGroup;
validate();
- messagesBundleGroup.addMessagesBundleGroupListener(
- new MessagesBundleGroupAdapter() {
- public void messageChanged(MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- resetMarkers();
- }
- public void messagesBundleChanged(
- MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- Display.getDefault().asyncExec(new Runnable(){
- public void run() {
- resetMarkers();
- }
- });
- }
- public void propertyChange(PropertyChangeEvent evt) {
- resetMarkers();
- }
- private void resetMarkers() {
- clear();
- validate();
- }
- });
- }
-
- private String buildLocalizedKey(Locale locale, String key) {
- //the '=' is hack to make sure no local=key can ever conflict
- //with another local=key: in other words
- //it makes a hash of the combination (key+locale).
- if (locale == null) {
- locale = UIUtils.ROOT_LOCALE;
- }
- return locale + "=" + key;
+ messagesBundleGroup
+ .addMessagesBundleGroupListener(new MessagesBundleGroupAdapter() {
+ public void messageChanged(MessagesBundle messagesBundle,
+ PropertyChangeEvent changeEvent) {
+ resetMarkers();
+ }
+
+ public void messagesBundleChanged(
+ MessagesBundle messagesBundle,
+ PropertyChangeEvent changeEvent) {
+ Display.getDefault().asyncExec(new Runnable() {
+ public void run() {
+ resetMarkers();
+ }
+ });
+ }
+
+ public void propertyChange(PropertyChangeEvent evt) {
+ resetMarkers();
+ }
+
+ private void resetMarkers() {
+ clear();
+ validate();
+ }
+ });
}
+ private String buildLocalizedKey(Locale locale, String key) {
+ // the '=' is hack to make sure no local=key can ever conflict
+ // with another local=key: in other words
+ // it makes a hash of the combination (key+locale).
+ if (locale == null) {
+ locale = UIUtils.ROOT_LOCALE;
+ }
+ return locale + "=" + key;
+ }
/**
- * @see org.eclipse.babel.editor.resource.validator.IValidationMarkerStrategy#markFailed(org.eclipse.core.resources.IResource, org.eclipse.babel.core.bundle.checks.IBundleEntryCheck)
+ * @see org.eclipse.babel.editor.resource.validator.IValidationMarkerStrategy#markFailed(org.eclipse.core.resources.IResource,
+ * org.eclipse.babel.core.bundle.checks.IBundleEntryCheck)
*/
public void markFailed(ValidationFailureEvent event) {
- Collection<IMessageCheck> markersForKey = markersIndex.get(event.getKey());
+ Collection<IMessageCheck> markersForKey = markersIndex.get(event
+ .getKey());
if (markersForKey == null) {
- markersForKey = new HashSet<IMessageCheck>();
- markersIndex.put(event.getKey(), markersForKey);
+ markersForKey = new HashSet<IMessageCheck>();
+ markersIndex.put(event.getKey(), markersForKey);
}
markersForKey.add(event.getCheck());
-
- String localizedKey = buildLocalizedKey(event.getLocale(), event.getKey());
+
+ String localizedKey = buildLocalizedKey(event.getLocale(),
+ event.getKey());
markersForKey = localizedMarkersMap.get(localizedKey);
if (markersForKey == null) {
- markersForKey = new HashSet<IMessageCheck>();
- localizedMarkersMap.put(localizedKey, markersForKey);
+ markersForKey = new HashSet<IMessageCheck>();
+ localizedMarkersMap.put(localizedKey, markersForKey);
}
markersForKey.add(event.getCheck());
-
- //System.out.println("CREATE EDITOR MARKER");
+
+ // System.out.println("CREATE EDITOR MARKER");
setChanged();
}
-
+
public void clear() {
markersIndex.clear();
localizedMarkersMap.clear();
@@ -125,103 +133,107 @@
notifyObservers(this);
}
- public boolean isMarked(String key) {
- return markersIndex.containsKey(key);
+ public boolean isMarked(String key) {
+ return markersIndex.containsKey(key);
}
public Collection<IMessageCheck> getFailedChecks(String key) {
- return markersIndex.get(key);
+ return markersIndex.get(key);
}
-
+
/**
*
* @param key
* @param locale
- * @return the collection of markers for the locale and key; the return value may be
- * null if there are no markers
+ * @return the collection of markers for the locale and key; the return
+ * value may be null if there are no markers
*/
- public Collection<IMessageCheck> getFailedChecks(final String key, final Locale locale) {
- return localizedMarkersMap.get(buildLocalizedKey(locale, key));
+ public Collection<IMessageCheck> getFailedChecks(final String key,
+ final Locale locale) {
+ return localizedMarkersMap.get(buildLocalizedKey(locale, key));
}
-
+
private void validate() {
- //TODO in a UI thread
+ // TODO in a UI thread
Locale[] locales = messagesBundleGroup.getLocales();
- for (int i = 0; i < locales.length; i++) {
- Locale locale = locales[i];
- MessagesBundleGroupValidator.validate(messagesBundleGroup, locale, this);
- }
-
- /*
- * If anything has changed in this observable, notify the observers.
- *
- * Something will have changed if, for example, multiple keys have the
- * same text. Note that notifyObservers will in fact do nothing if
- * nothing in the above call to 'validate' resulted in a call to
- * setChange.
- */
- notifyObservers(null);
+ for (int i = 0; i < locales.length; i++) {
+ Locale locale = locales[i];
+ MessagesBundleGroupValidator.validate(messagesBundleGroup, locale,
+ this);
+ }
+
+ /*
+ * If anything has changed in this observable, notify the observers.
+ *
+ * Something will have changed if, for example, multiple keys have the
+ * same text. Note that notifyObservers will in fact do nothing if
+ * nothing in the above call to 'validate' resulted in a call to
+ * setChange.
+ */
+ notifyObservers(null);
}
-
+
/**
* @param key
* @return true when the key has a missing or unused issue
*/
public boolean isMissingOrUnusedKey(String key) {
- Collection<IMessageCheck> markers = getFailedChecks(key);
- return markers != null && markersContainMissing(markers);
+ Collection<IMessageCheck> markers = getFailedChecks(key);
+ return markers != null && markersContainMissing(markers);
}
-
+
/**
* @param key
* @return true when the key has a missing issue
*/
public boolean isMissingKey(String key) {
- Collection<IMessageCheck> markers = getFailedChecks(key);
- return markers != null && markersContainMissing(markers);
+ Collection<IMessageCheck> markers = getFailedChecks(key);
+ return markers != null && markersContainMissing(markers);
}
-
+
/**
* @param key
- * @param isMissingOrUnused true when it has been assesed already
- * that it is missing or unused
+ * @param isMissingOrUnused
+ * true when it has been assesed already that it is missing or
+ * unused
* @return true when the key is unused
*/
public boolean isUnusedKey(String key, boolean isMissingOrUnused) {
- if (!isMissingOrUnused) {
- return false;
- }
- Collection<IMessageCheck> markers = getFailedChecks(key, UIUtils.ROOT_LOCALE);
- //if we get a missing on the root locale, it means the
- //that some localized resources are referring to a key that is not in
- //the default locale anymore: in other words, assuming the
- //the code is up to date with the default properties
- //file, the key is now unused.
- return markers != null && markersContainMissing(markers);
+ if (!isMissingOrUnused) {
+ return false;
+ }
+ Collection<IMessageCheck> markers = getFailedChecks(key,
+ UIUtils.ROOT_LOCALE);
+ // if we get a missing on the root locale, it means the
+ // that some localized resources are referring to a key that is not in
+ // the default locale anymore: in other words, assuming the
+ // the code is up to date with the default properties
+ // file, the key is now unused.
+ return markers != null && markersContainMissing(markers);
}
-
+
/**
*
* @param key
* @return true when the value is a duplicate value
*/
public boolean isDuplicateValue(String key) {
- Collection<IMessageCheck> markers = getFailedChecks(key);
- for (IMessageCheck marker : markers) {
- if (marker instanceof DuplicateValueCheck) {
- return true;
- }
- }
- return false;
+ Collection<IMessageCheck> markers = getFailedChecks(key);
+ for (IMessageCheck marker : markers) {
+ if (marker instanceof DuplicateValueCheck) {
+ return true;
+ }
+ }
+ return false;
}
-
+
private boolean markersContainMissing(Collection<IMessageCheck> markers) {
- for (IMessageCheck marker : markers) {
- if (marker == MissingValueCheck.MISSING_KEY) {
- return true;
- }
- }
- return false;
+ for (IMessageCheck marker : markers) {
+ if (marker == MissingValueCheck.MISSING_KEY) {
+ return true;
+ }
+ }
+ return false;
}
-
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/MessagesEditorPlugin.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/MessagesEditorPlugin.java
index 46e6a6e..3619a1e 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/MessagesEditorPlugin.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/MessagesEditorPlugin.java
@@ -48,105 +48,110 @@
/**
* The activator class controls the plug-in life cycle
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
-public class MessagesEditorPlugin extends AbstractUIPlugin implements IFileChangeListenerRegistry {
+public class MessagesEditorPlugin extends AbstractUIPlugin implements
+ IFileChangeListenerRegistry {
- //TODO move somewhere more appropriate
- public static final String MARKER_TYPE =
- "org.eclipse.babel.editor.nlsproblem"; //$NON-NLS-1$
-
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.babel.editor";
+ // TODO move somewhere more appropriate
+ public static final String MARKER_TYPE = "org.eclipse.babel.editor.nlsproblem"; //$NON-NLS-1$
- // The shared instance
- private static MessagesEditorPlugin plugin;
-
- //Resource bundle.
- //TODO Use Eclipse MessagesBundle instead.
- private ResourceBundle resourceBundle;
-
- //The resource change litener for the entire plugin.
- //objects interested in changes in the workspace resources must
- //subscribe to this listener by calling subscribe/unsubscribe on the plugin.
- private IResourceChangeListener resourceChangeListener;
-
- //The map of resource change subscribers.
- //The key is the full path of the resource listened. The value as set of SimpleResourceChangeListners
- //private Map<String,Set<SimpleResourceChangeListners>> resourceChangeSubscribers;
- private Map<String,Set<AbstractIFileChangeListener>> resourceChangeSubscribers;
-
- private ResourceBundleModel model;
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.babel.editor";
- /**
- * The constructor
- */
- public MessagesEditorPlugin() {
- resourceChangeSubscribers = new HashMap<String,Set<AbstractIFileChangeListener>>();
- }
-
- private static class UndoKeyListener implements Listener {
-
- public void handleEvent(Event event) {
- Control focusControl = event.display.getFocusControl();
- if (event.stateMask == SWT.CONTROL && focusControl instanceof Text) {
-
- Text txt = (Text) focusControl;
- String actText = txt.getText();
- Stack<String> undoStack = (Stack<String>) txt.getData("UNDO");
- Stack<String> redoStack = (Stack<String>) txt.getData("REDO");
-
- if (event.keyCode == 'z' && undoStack != null && redoStack != null) { // Undo
- event.doit = false;
-
- if (undoStack.size() > 0) {
- String peek = undoStack.peek();
- if (actText != null && !txt.getText().equals(peek)) {
- String pop = undoStack.pop();
- txt.setText(pop);
- txt.setSelection(pop.length());
- redoStack.push(actText);
- }
- }
- } else if (event.keyCode == 'y' && undoStack != null && redoStack != null) { // Redo
-
- event.doit = false;
-
- if (redoStack.size() > 0) {
- String peek = redoStack.peek();
-
- if (actText != null && !txt.getText().equals(peek)) {
- String pop = redoStack.pop();
- txt.setText(pop);
- txt.setSelection(pop.length());
- undoStack.push(actText);
- }
- }
- }
- }
- }
-
+ // The shared instance
+ private static MessagesEditorPlugin plugin;
+
+ // Resource bundle.
+ // TODO Use Eclipse MessagesBundle instead.
+ private ResourceBundle resourceBundle;
+
+ // The resource change litener for the entire plugin.
+ // objects interested in changes in the workspace resources must
+ // subscribe to this listener by calling subscribe/unsubscribe on the
+ // plugin.
+ private IResourceChangeListener resourceChangeListener;
+
+ // The map of resource change subscribers.
+ // The key is the full path of the resource listened. The value as set of
+ // SimpleResourceChangeListners
+ // private Map<String,Set<SimpleResourceChangeListners>>
+ // resourceChangeSubscribers;
+ private Map<String, Set<AbstractIFileChangeListener>> resourceChangeSubscribers;
+
+ private ResourceBundleModel model;
+
+ /**
+ * The constructor
+ */
+ public MessagesEditorPlugin() {
+ resourceChangeSubscribers = new HashMap<String, Set<AbstractIFileChangeListener>>();
}
- /**
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(
- * org.osgi.framework.BundleContext)
- */
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
-
- //make sure the rbe nature and builder are set on java projects
- //if that is what the users prefers.
- if (MsgEditorPreferences.getInstance().isBuilderSetupAutomatically()) {
- ToggleNatureAction.addOrRemoveNatureOnAllJavaProjects(true);
- }
+ private static class UndoKeyListener implements Listener {
- //TODO replace deprecated
+ public void handleEvent(Event event) {
+ Control focusControl = event.display.getFocusControl();
+ if (event.stateMask == SWT.CONTROL && focusControl instanceof Text) {
+
+ Text txt = (Text) focusControl;
+ String actText = txt.getText();
+ Stack<String> undoStack = (Stack<String>) txt.getData("UNDO");
+ Stack<String> redoStack = (Stack<String>) txt.getData("REDO");
+
+ if (event.keyCode == 'z' && undoStack != null
+ && redoStack != null) { // Undo
+ event.doit = false;
+
+ if (undoStack.size() > 0) {
+ String peek = undoStack.peek();
+ if (actText != null && !txt.getText().equals(peek)) {
+ String pop = undoStack.pop();
+ txt.setText(pop);
+ txt.setSelection(pop.length());
+ redoStack.push(actText);
+ }
+ }
+ } else if (event.keyCode == 'y' && undoStack != null
+ && redoStack != null) { // Redo
+
+ event.doit = false;
+
+ if (redoStack.size() > 0) {
+ String peek = redoStack.peek();
+
+ if (actText != null && !txt.getText().equals(peek)) {
+ String pop = redoStack.pop();
+ txt.setText(pop);
+ txt.setSelection(pop.length());
+ undoStack.push(actText);
+ }
+ }
+ }
+ }
+ }
+
+ }
+
+ /**
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+
+ // make sure the rbe nature and builder are set on java projects
+ // if that is what the users prefers.
+ if (MsgEditorPreferences.getInstance().isBuilderSetupAutomatically()) {
+ ToggleNatureAction.addOrRemoveNatureOnAllJavaProjects(true);
+ }
+
+ // TODO replace deprecated
try {
- URL messagesUrl = FileLocator.find(getBundle(),
- new Path("$nl$/messages.properties"), null);//$NON-NLS-1$
- if(messagesUrl != null) {
+ URL messagesUrl = FileLocator.find(getBundle(), new Path(
+ "$nl$/messages.properties"), null);//$NON-NLS-1$
+ if (messagesUrl != null) {
resourceBundle = new PropertyResourceBundle(
messagesUrl.openStream());
}
@@ -154,207 +159,236 @@
resourceBundle = null;
}
- //the unique file change listener
+ // the unique file change listener
resourceChangeListener = new IResourceChangeListener() {
- public void resourceChanged(IResourceChangeEvent event) {
- IResource resource = event.getResource();
- if (resource != null) {
- String fullpath = resource.getFullPath().toString();
- Set<AbstractIFileChangeListener> listeners = resourceChangeSubscribers.get(fullpath);
- if (listeners != null) {
- AbstractIFileChangeListener[] larray = listeners.toArray(new AbstractIFileChangeListener[0]);//avoid concurrency issues. kindof.
- for (int i = 0; i < larray.length; i++) {
- larray[i].listenedFileChanged(event);
- }
- }
- }
- }
+ public void resourceChanged(IResourceChangeEvent event) {
+ IResource resource = event.getResource();
+ if (resource != null) {
+ String fullpath = resource.getFullPath().toString();
+ Set<AbstractIFileChangeListener> listeners = resourceChangeSubscribers
+ .get(fullpath);
+ if (listeners != null) {
+ AbstractIFileChangeListener[] larray = listeners
+ .toArray(new AbstractIFileChangeListener[0]);// avoid
+ // concurrency
+ // issues.
+ // kindof.
+ for (int i = 0; i < larray.length; i++) {
+ larray[i].listenedFileChanged(event);
+ }
+ }
+ }
+ }
};
- ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceChangeListener);
-
+ ResourcesPlugin.getWorkspace().addResourceChangeListener(
+ resourceChangeListener);
+
Display.getDefault().asyncExec(new Runnable() {
-
- public void run() {
- Display.getDefault().addFilter(SWT.KeyUp, new UndoKeyListener());
-
- }
- });
- }
- /**
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(
- * org.osgi.framework.BundleContext)
- */
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceChangeListener);
- super.stop(context);
- }
-
- /**
- * @param rcl Adds a subscriber to a resource change event.
- */
- public void subscribe(AbstractIFileChangeListener fileChangeListener) {
- synchronized (resourceChangeListener) {
- String channel = fileChangeListener.getListenedFileFullPath();
- Set<AbstractIFileChangeListener> channelListeners = resourceChangeSubscribers.get(channel);
- if (channelListeners == null) {
- channelListeners = new HashSet<AbstractIFileChangeListener>();
- resourceChangeSubscribers.put(channel, channelListeners);
- }
- channelListeners.add(fileChangeListener);
- }
- }
-
- /**
- * @param rcl Removes a subscriber to a resource change event.
- */
- public void unsubscribe(AbstractIFileChangeListener fileChangeListener) {
- synchronized (resourceChangeListener) {
- String channel = fileChangeListener.getListenedFileFullPath();
- Set<AbstractIFileChangeListener> channelListeners = resourceChangeSubscribers.get(channel);
- if (channelListeners != null
- && channelListeners.remove(fileChangeListener)
- && channelListeners.isEmpty()) {
- //nobody left listening to this file.
- resourceChangeSubscribers.remove(channel);
- }
- }
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static MessagesEditorPlugin getDefault() {
- return plugin;
- }
+ public void run() {
+ Display.getDefault()
+ .addFilter(SWT.KeyUp, new UndoKeyListener());
- //--------------------------------------------------------------------------
- //TODO Better way/location for these methods?
-
- /**
- * Returns the string from the plugin's resource bundle,
- * or 'key' if not found.
- * @param key the key for which to fetch a localized text
- * @return localized string corresponding to key
- */
- public static String getString(String key) {
- ResourceBundle bundle =
- MessagesEditorPlugin.getDefault().getResourceBundle();
- try {
- return (bundle != null) ? bundle.getString(key) : key;
- } catch (MissingResourceException e) {
- return key;
- }
- }
+ }
+ });
+ }
/**
- * Returns the string from the plugin's resource bundle,
- * or 'key' if not found.
- * @param key the key for which to fetch a localized text
- * @param arg1 runtime argument to replace in key value
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ ResourcesPlugin.getWorkspace().removeResourceChangeListener(
+ resourceChangeListener);
+ super.stop(context);
+ }
+
+ /**
+ * @param rcl
+ * Adds a subscriber to a resource change event.
+ */
+ public void subscribe(AbstractIFileChangeListener fileChangeListener) {
+ synchronized (resourceChangeListener) {
+ String channel = fileChangeListener.getListenedFileFullPath();
+ Set<AbstractIFileChangeListener> channelListeners = resourceChangeSubscribers
+ .get(channel);
+ if (channelListeners == null) {
+ channelListeners = new HashSet<AbstractIFileChangeListener>();
+ resourceChangeSubscribers.put(channel, channelListeners);
+ }
+ channelListeners.add(fileChangeListener);
+ }
+ }
+
+ /**
+ * @param rcl
+ * Removes a subscriber to a resource change event.
+ */
+ public void unsubscribe(AbstractIFileChangeListener fileChangeListener) {
+ synchronized (resourceChangeListener) {
+ String channel = fileChangeListener.getListenedFileFullPath();
+ Set<AbstractIFileChangeListener> channelListeners = resourceChangeSubscribers
+ .get(channel);
+ if (channelListeners != null
+ && channelListeners.remove(fileChangeListener)
+ && channelListeners.isEmpty()) {
+ // nobody left listening to this file.
+ resourceChangeSubscribers.remove(channel);
+ }
+ }
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static MessagesEditorPlugin getDefault() {
+ return plugin;
+ }
+
+ // --------------------------------------------------------------------------
+ // TODO Better way/location for these methods?
+
+ /**
+ * Returns the string from the plugin's resource bundle, or 'key' if not
+ * found.
+ *
+ * @param key
+ * the key for which to fetch a localized text
+ * @return localized string corresponding to key
+ */
+ public static String getString(String key) {
+ ResourceBundle bundle = MessagesEditorPlugin.getDefault()
+ .getResourceBundle();
+ try {
+ return (bundle != null) ? bundle.getString(key) : key;
+ } catch (MissingResourceException e) {
+ return key;
+ }
+ }
+
+ /**
+ * Returns the string from the plugin's resource bundle, or 'key' if not
+ * found.
+ *
+ * @param key
+ * the key for which to fetch a localized text
+ * @param arg1
+ * runtime argument to replace in key value
* @return localized string corresponding to key
*/
public static String getString(String key, String arg1) {
- return MessageFormat.format(getString(key), new Object[]{arg1});
+ return MessageFormat.format(getString(key), new Object[] { arg1 });
}
-
+
/**
- * Returns the string from the plugin's resource bundle,
- * or 'key' if not found.
- * @param key the key for which to fetch a localized text
- * @param arg1 runtime first argument to replace in key value
- * @param arg2 runtime second argument to replace in key value
+ * Returns the string from the plugin's resource bundle, or 'key' if not
+ * found.
+ *
+ * @param key
+ * the key for which to fetch a localized text
+ * @param arg1
+ * runtime first argument to replace in key value
+ * @param arg2
+ * runtime second argument to replace in key value
* @return localized string corresponding to key
*/
public static String getString(String key, String arg1, String arg2) {
- return MessageFormat.format(
- getString(key), new Object[]{arg1, arg2});
+ return MessageFormat
+ .format(getString(key), new Object[] { arg1, arg2 });
}
-
+
/**
- * Returns the string from the plugin's resource bundle,
- * or 'key' if not found.
- * @param key the key for which to fetch a localized text
- * @param arg1 runtime argument to replace in key value
- * @param arg2 runtime second argument to replace in key value
- * @param arg3 runtime third argument to replace in key value
+ * Returns the string from the plugin's resource bundle, or 'key' if not
+ * found.
+ *
+ * @param key
+ * the key for which to fetch a localized text
+ * @param arg1
+ * runtime argument to replace in key value
+ * @param arg2
+ * runtime second argument to replace in key value
+ * @param arg3
+ * runtime third argument to replace in key value
* @return localized string corresponding to key
*/
- public static String getString(
- String key, String arg1, String arg2, String arg3) {
- return MessageFormat.format(
- getString(key), new Object[]{arg1, arg2, arg3});
+ public static String getString(String key, String arg1, String arg2,
+ String arg3) {
+ return MessageFormat.format(getString(key), new Object[] { arg1, arg2,
+ arg3 });
}
-
- /**
- * Returns the plugin's resource bundle.
+
+ /**
+ * Returns the plugin's resource bundle.
+ *
* @return resource bundle
- */
- protected ResourceBundle getResourceBundle() {
- return resourceBundle;
- }
-
- // Stefan's activator methods:
-
- /**
- * Returns an image descriptor for the given icon filename.
- *
- * @param filename the icon filename relative to the icons path
- * @return the image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String filename) {
- String iconPath = "icons/"; //$NON-NLS-1$
- return imageDescriptorFromPlugin(PLUGIN_ID, iconPath + filename);
- }
+ */
+ protected ResourceBundle getResourceBundle() {
+ return resourceBundle;
+ }
- public static ResourceBundleModel getModel(IProgressMonitor monitor) {
- if (plugin.model == null) {
- plugin.model = new ResourceBundleModel(monitor);
- }
- return plugin.model;
- }
+ // Stefan's activator methods:
- public static void disposeModel() {
- if (plugin != null) {
- plugin.model = null;
- }
- }
+ /**
+ * Returns an image descriptor for the given icon filename.
+ *
+ * @param filename
+ * the icon filename relative to the icons path
+ * @return the image descriptor
+ */
+ public static ImageDescriptor getImageDescriptor(String filename) {
+ String iconPath = "icons/"; //$NON-NLS-1$
+ return imageDescriptorFromPlugin(PLUGIN_ID, iconPath + filename);
+ }
- // Logging
+ public static ResourceBundleModel getModel(IProgressMonitor monitor) {
+ if (plugin.model == null) {
+ plugin.model = new ResourceBundleModel(monitor);
+ }
+ return plugin.model;
+ }
- /**
- * Adds the given exception to the log.
- *
- * @param e the exception to log
- * @return the logged status
- */
- public static IStatus log(Throwable e) {
- return log(new Status(IStatus.ERROR, PLUGIN_ID, 0, "Internal error.", e));
- }
+ public static void disposeModel() {
+ if (plugin != null) {
+ plugin.model = null;
+ }
+ }
- /**
- * Adds the given exception to the log.
- *
- * @param exception the exception to log
- * @return the logged status
- */
- public static IStatus log(String message, Throwable exception) {
- return log(new Status(IStatus.ERROR, PLUGIN_ID, -1, message, exception));
- }
+ // Logging
- /**
- * Adds the given <code>IStatus</code> to the log.
- *
- * @param status the status to log
- * @return the logged status
- */
- public static IStatus log(IStatus status) {
- getDefault().getLog().log(status);
- return status;
- }
+ /**
+ * Adds the given exception to the log.
+ *
+ * @param e
+ * the exception to log
+ * @return the logged status
+ */
+ public static IStatus log(Throwable e) {
+ return log(new Status(IStatus.ERROR, PLUGIN_ID, 0, "Internal error.", e));
+ }
-
+ /**
+ * Adds the given exception to the log.
+ *
+ * @param exception
+ * the exception to log
+ * @return the logged status
+ */
+ public static IStatus log(String message, Throwable exception) {
+ return log(new Status(IStatus.ERROR, PLUGIN_ID, -1, message, exception));
+ }
+
+ /**
+ * Adds the given <code>IStatus</code> to the log.
+ *
+ * @param status
+ * the status to log
+ * @return the logged status
+ */
+ public static IStatus log(IStatus status) {
+ getDefault().getLog().log(status);
+ return status;
+ }
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/Startup.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/Startup.java
index 5952a10..2d43da3 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/Startup.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/Startup.java
@@ -14,7 +14,7 @@
/**
* @author Pascal Essiembre
- *
+ *
*/
public class Startup implements IStartup {
@@ -22,10 +22,10 @@
* @see org.eclipse.ui.IStartup#earlyStartup()
*/
public void earlyStartup() {
- //done.
-// System.out.println("Starting up. "
-// + "TODO: Register nature with every project and listen for new "
-// + "projects???");
+ // done.
+ // System.out.println("Starting up. "
+ // + "TODO: Register nature with every project and listen for new "
+ // + "projects???");
}
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/AbstractPrefPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/AbstractPrefPage.java
index 80a5f6e..3ef7be0 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/AbstractPrefPage.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/AbstractPrefPage.java
@@ -29,17 +29,18 @@
/**
* Plugin base preference page.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public abstract class AbstractPrefPage extends PreferencePage implements
IWorkbenchPreferencePage {
- /** Number of pixels per field indentation */
+ /** Number of pixels per field indentation */
protected final int indentPixels = 20;
-
+
/** Controls with errors in them. */
- protected final Map<Text,String> errors = new HashMap<Text,String>();
-
+ protected final Map<Text, String> errors = new HashMap<Text, String>();
+
/**
* Constructor.
*/
@@ -52,13 +53,14 @@
* #init(org.eclipse.ui.IWorkbench)
*/
public void init(IWorkbench workbench) {
- setPreferenceStore(
- MessagesEditorPlugin.getDefault().getPreferenceStore());
+ setPreferenceStore(MessagesEditorPlugin.getDefault()
+ .getPreferenceStore());
}
protected Composite createFieldComposite(Composite parent) {
return createFieldComposite(parent, 0);
}
+
protected Composite createFieldComposite(Composite parent, int indent) {
Composite composite = new Composite(parent, SWT.NONE);
GridLayout gridLayout = new GridLayout(2, false);
@@ -70,24 +72,26 @@
}
protected class IntTextValidatorKeyListener extends KeyAdapter {
-
+
private String errMsg = null;
-
+
/**
* Constructor.
- * @param errMsg error message
+ *
+ * @param errMsg
+ * error message
*/
public IntTextValidatorKeyListener(String errMsg) {
super();
this.errMsg = errMsg;
}
+
/**
- * @see org.eclipse.swt.events.KeyAdapter#keyPressed(
- * org.eclipse.swt.events.KeyEvent)
+ * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*/
public void keyReleased(KeyEvent event) {
Text text = (Text) event.widget;
- String value = text.getText();
+ String value = text.getText();
event.doit = value.matches("^\\d*$"); //$NON-NLS-1$
if (event.doit) {
errors.remove(text);
@@ -95,8 +99,7 @@
setErrorMessage(null);
setValid(true);
} else {
- setErrorMessage(
- (String) errors.values().iterator().next());
+ setErrorMessage((String) errors.values().iterator().next());
}
} else {
errors.put(text, errMsg);
@@ -107,40 +110,46 @@
}
protected class DoubleTextValidatorKeyListener extends KeyAdapter {
-
+
private String errMsg;
private double minValue;
private double maxValue;
-
+
/**
* Constructor.
- * @param errMsg error message
+ *
+ * @param errMsg
+ * error message
*/
public DoubleTextValidatorKeyListener(String errMsg) {
super();
this.errMsg = errMsg;
}
+
/**
* Constructor.
- * @param errMsg error message
- * @param minValue minimum value (inclusive)
- * @param maxValue maximum value (inclusive)
+ *
+ * @param errMsg
+ * error message
+ * @param minValue
+ * minimum value (inclusive)
+ * @param maxValue
+ * maximum value (inclusive)
*/
- public DoubleTextValidatorKeyListener(
- String errMsg, double minValue, double maxValue) {
+ public DoubleTextValidatorKeyListener(String errMsg, double minValue,
+ double maxValue) {
super();
this.errMsg = errMsg;
this.minValue = minValue;
this.maxValue = maxValue;
}
-
+
/**
- * @see org.eclipse.swt.events.KeyAdapter#keyPressed(
- * org.eclipse.swt.events.KeyEvent)
+ * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*/
public void keyReleased(KeyEvent event) {
Text text = (Text) event.widget;
- String value = text.getText();
+ String value = text.getText();
boolean valid = value.length() > 0;
if (valid) {
valid = value.matches("^\\d*\\.?\\d*$"); //$NON-NLS-1$
@@ -165,7 +174,7 @@
}
}
}
-
+
protected void setWidthInChars(Control field, int widthInChars) {
GridData gd = new GridData();
gd.widthHint = UIUtils.getWidthInChars(field, widthInChars);
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/FormattingPrefPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/FormattingPrefPage.java
index 496d7ba..032cec9 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/FormattingPrefPage.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/FormattingPrefPage.java
@@ -25,10 +25,11 @@
/**
* Plugin formatting preference page.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public class FormattingPrefPage extends AbstractPrefPage {
-
+
/* Preference fields. */
private Button showGeneratedBy;
@@ -37,24 +38,24 @@
private Button alignEqualSigns;
private Button ensureSpacesAroundEquals;
-
+
private Button groupKeys;
private Text groupLevelDeep;
private Text groupLineBreaks;
private Button groupAlignEqualSigns;
-
+
private Button wrapLines;
private Text wrapCharLimit;
private Button wrapAlignEqualSigns;
private Text wrapIndentSpaces;
private Button wrapNewLine;
-
+
private Button newLineTypeForce;
private Button[] newLineTypes = new Button[3];
private Button keepEmptyFields;
private Button sortKeys;
-
+
/**
* Constructor.
*/
@@ -63,183 +64,179 @@
}
/**
- * @see org.eclipse.jface.preference.PreferencePage#createContents(
- * org.eclipse.swt.widgets.Composite)
+ * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
*/
protected Control createContents(Composite parent) {
IPreferenceStore prefs = getPreferenceStore();
Composite field = null;
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
-
+
// Show generated by comment?
field = createFieldComposite(composite);
showGeneratedBy = new Button(field, SWT.CHECK);
- showGeneratedBy.setSelection(
- prefs.getBoolean(MsgEditorPreferences.SHOW_SUPPORT_ENABLED));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.showGeneratedBy")); //$NON-NLS-1$
+ showGeneratedBy.setSelection(prefs
+ .getBoolean(MsgEditorPreferences.SHOW_SUPPORT_ENABLED));
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.showGeneratedBy")); //$NON-NLS-1$
// Convert unicode to encoded?
field = createFieldComposite(composite);
convertUnicodeToEncoded = new Button(field, SWT.CHECK);
- convertUnicodeToEncoded.setSelection(
- prefs.getBoolean(MsgEditorPreferences.UNICODE_ESCAPE_ENABLED));
+ convertUnicodeToEncoded.setSelection(prefs
+ .getBoolean(MsgEditorPreferences.UNICODE_ESCAPE_ENABLED));
convertUnicodeToEncoded.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
refreshEnabledStatuses();
}
});
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.convertUnicode")); //$NON-NLS-1$
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.convertUnicode")); //$NON-NLS-1$
// Use upper case for encoded hexadecimal values?
field = createFieldComposite(composite, indentPixels);
convertUnicodeUpperCase = new Button(field, SWT.CHECK);
- convertUnicodeUpperCase.setSelection(prefs.getBoolean(
- MsgEditorPreferences.UNICODE_ESCAPE_UPPERCASE));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.convertUnicode.upper"));//$NON-NLS-1$
-
+ convertUnicodeUpperCase.setSelection(prefs
+ .getBoolean(MsgEditorPreferences.UNICODE_ESCAPE_UPPERCASE));
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.convertUnicode.upper"));//$NON-NLS-1$
+
// Align equal signs?
field = createFieldComposite(composite);
alignEqualSigns = new Button(field, SWT.CHECK);
- alignEqualSigns.setSelection(
- prefs.getBoolean(MsgEditorPreferences.ALIGN_EQUALS_ENABLED));
+ alignEqualSigns.setSelection(prefs
+ .getBoolean(MsgEditorPreferences.ALIGN_EQUALS_ENABLED));
alignEqualSigns.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
refreshEnabledStatuses();
}
});
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.alignEquals")); //$NON-NLS-1$
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.alignEquals")); //$NON-NLS-1$
field = createFieldComposite(composite);
ensureSpacesAroundEquals = new Button(field, SWT.CHECK);
- ensureSpacesAroundEquals.setSelection(
- prefs.getBoolean(MsgEditorPreferences.SPACES_AROUND_EQUALS_ENABLED));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.spacesAroundEquals")); //$NON-NLS-1$
-
+ ensureSpacesAroundEquals.setSelection(prefs
+ .getBoolean(MsgEditorPreferences.SPACES_AROUND_EQUALS_ENABLED));
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.spacesAroundEquals")); //$NON-NLS-1$
+
// Group keys?
field = createFieldComposite(composite);
groupKeys = new Button(field, SWT.CHECK);
- groupKeys.setSelection(prefs.getBoolean(MsgEditorPreferences.GROUP_KEYS_ENABLED));
+ groupKeys.setSelection(prefs
+ .getBoolean(MsgEditorPreferences.GROUP_KEYS_ENABLED));
groupKeys.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
refreshEnabledStatuses();
}
});
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.groupKeys")); //$NON-NLS-1$
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.groupKeys")); //$NON-NLS-1$
// Group keys by how many level deep?
field = createFieldComposite(composite, indentPixels);
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.levelDeep")); //$NON-NLS-1$
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.levelDeep")); //$NON-NLS-1$
groupLevelDeep = new Text(field, SWT.BORDER);
- groupLevelDeep.setText(prefs.getString(MsgEditorPreferences.GROUP_LEVEL_DEEP));
+ groupLevelDeep.setText(prefs
+ .getString(MsgEditorPreferences.GROUP_LEVEL_DEEP));
groupLevelDeep.setTextLimit(2);
setWidthInChars(groupLevelDeep, 2);
groupLevelDeep.addKeyListener(new IntTextValidatorKeyListener(
- MessagesEditorPlugin.getString(
- "prefs.levelDeep.error"))); //$NON-NLS-1$
-
+ MessagesEditorPlugin.getString("prefs.levelDeep.error"))); //$NON-NLS-1$
+
// How many lines between groups?
field = createFieldComposite(composite, indentPixels);
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.linesBetween")); //$NON-NLS-1$
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.linesBetween")); //$NON-NLS-1$
groupLineBreaks = new Text(field, SWT.BORDER);
- groupLineBreaks.setText(
- prefs.getString(MsgEditorPreferences.GROUP_SEP_BLANK_LINE_COUNT));
+ groupLineBreaks.setText(prefs
+ .getString(MsgEditorPreferences.GROUP_SEP_BLANK_LINE_COUNT));
groupLineBreaks.setTextLimit(2);
setWidthInChars(groupLineBreaks, 2);
groupLineBreaks.addKeyListener(new IntTextValidatorKeyListener(
- MessagesEditorPlugin.getString(
- "prefs.linesBetween.error"))); //$NON-NLS-1$
+ MessagesEditorPlugin.getString("prefs.linesBetween.error"))); //$NON-NLS-1$
// Align equal signs within groups?
field = createFieldComposite(composite, indentPixels);
groupAlignEqualSigns = new Button(field, SWT.CHECK);
- groupAlignEqualSigns.setSelection(
- prefs.getBoolean(MsgEditorPreferences.GROUP_ALIGN_EQUALS_ENABLED));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString(
- "prefs.groupAlignEquals")); //$NON-NLS-1$
+ groupAlignEqualSigns.setSelection(prefs
+ .getBoolean(MsgEditorPreferences.GROUP_ALIGN_EQUALS_ENABLED));
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.groupAlignEquals")); //$NON-NLS-1$
// Wrap lines?
field = createFieldComposite(composite);
wrapLines = new Button(field, SWT.CHECK);
- wrapLines.setSelection(prefs.getBoolean(MsgEditorPreferences.WRAP_LINES_ENABLED));
+ wrapLines.setSelection(prefs
+ .getBoolean(MsgEditorPreferences.WRAP_LINES_ENABLED));
wrapLines.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
refreshEnabledStatuses();
}
});
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.wrapLines")); //$NON-NLS-1$
-
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.wrapLines")); //$NON-NLS-1$
+
// After how many characters should we wrap?
field = createFieldComposite(composite, indentPixels);
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.wrapLinesChar")); //$NON-NLS-1$
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.wrapLinesChar")); //$NON-NLS-1$
wrapCharLimit = new Text(field, SWT.BORDER);
- wrapCharLimit.setText(prefs.getString(MsgEditorPreferences.WRAP_LINE_LENGTH));
+ wrapCharLimit.setText(prefs
+ .getString(MsgEditorPreferences.WRAP_LINE_LENGTH));
wrapCharLimit.setTextLimit(4);
setWidthInChars(wrapCharLimit, 4);
wrapCharLimit.addKeyListener(new IntTextValidatorKeyListener(
- MessagesEditorPlugin.getString(
- "prefs.wrapLinesChar.error"))); //$NON-NLS-1$
-
+ MessagesEditorPlugin.getString("prefs.wrapLinesChar.error"))); //$NON-NLS-1$
+
// Align wrapped lines with equal signs?
field = createFieldComposite(composite, indentPixels);
wrapAlignEqualSigns = new Button(field, SWT.CHECK);
- wrapAlignEqualSigns.setSelection(
- prefs.getBoolean(MsgEditorPreferences.WRAP_ALIGN_EQUALS_ENABLED));
+ wrapAlignEqualSigns.setSelection(prefs
+ .getBoolean(MsgEditorPreferences.WRAP_ALIGN_EQUALS_ENABLED));
wrapAlignEqualSigns.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
refreshEnabledStatuses();
}
});
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.wrapAlignEquals")); //$NON-NLS-1$
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.wrapAlignEquals")); //$NON-NLS-1$
// How many spaces/tabs to use for indenting?
field = createFieldComposite(composite, indentPixels);
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.wrapIndent")); //$NON-NLS-1$
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.wrapIndent")); //$NON-NLS-1$
wrapIndentSpaces = new Text(field, SWT.BORDER);
- wrapIndentSpaces.setText(
- prefs.getString(MsgEditorPreferences.WRAP_INDENT_LENGTH));
+ wrapIndentSpaces.setText(prefs
+ .getString(MsgEditorPreferences.WRAP_INDENT_LENGTH));
wrapIndentSpaces.setTextLimit(2);
setWidthInChars(wrapIndentSpaces, 2);
wrapIndentSpaces.addKeyListener(new IntTextValidatorKeyListener(
- MessagesEditorPlugin.getString(
- "prefs.wrapIndent.error"))); //$NON-NLS-1$
+ MessagesEditorPlugin.getString("prefs.wrapIndent.error"))); //$NON-NLS-1$
// Should we wrap after new line characters
field = createFieldComposite(composite);
wrapNewLine = new Button(field, SWT.CHECK);
- wrapNewLine.setSelection(
- prefs.getBoolean(MsgEditorPreferences.NEW_LINE_NICE));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString(
- "prefs.newline.nice")); //$NON-NLS-1$
+ wrapNewLine.setSelection(prefs
+ .getBoolean(MsgEditorPreferences.NEW_LINE_NICE));
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.newline.nice")); //$NON-NLS-1$
// How should new lines appear in properties file
field = createFieldComposite(composite);
newLineTypeForce = new Button(field, SWT.CHECK);
- newLineTypeForce.setSelection(
- prefs.getBoolean(MsgEditorPreferences.FORCE_NEW_LINE_TYPE));
+ newLineTypeForce.setSelection(prefs
+ .getBoolean(MsgEditorPreferences.FORCE_NEW_LINE_TYPE));
newLineTypeForce.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
refreshEnabledStatuses();
}
});
- Composite newLineRadioGroup = new Composite(field, SWT.NONE);
- new Label(newLineRadioGroup, SWT.NONE).setText(
- MessagesEditorPlugin.getString(
- "prefs.newline.force")); //$NON-NLS-1$
+ Composite newLineRadioGroup = new Composite(field, SWT.NONE);
+ new Label(newLineRadioGroup, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.newline.force")); //$NON-NLS-1$
newLineRadioGroup.setLayout(new RowLayout());
newLineTypes[0] = new Button(newLineRadioGroup, SWT.RADIO);
newLineTypes[0].setText("UNIX (\\n)"); //$NON-NLS-1$
@@ -247,31 +244,29 @@
newLineTypes[1].setText("Windows (\\r\\n)"); //$NON-NLS-1$
newLineTypes[2] = new Button(newLineRadioGroup, SWT.RADIO);
newLineTypes[2].setText("Mac (\\r)"); //$NON-NLS-1$
- newLineTypes[prefs.getInt(
- MsgEditorPreferences.NEW_LINE_STYLE) - 1].setSelection(true);
-
+ newLineTypes[prefs.getInt(MsgEditorPreferences.NEW_LINE_STYLE) - 1]
+ .setSelection(true);
+
// Keep empty fields?
field = createFieldComposite(composite);
keepEmptyFields = new Button(field, SWT.CHECK);
- keepEmptyFields.setSelection(prefs.getBoolean(
- MsgEditorPreferences.KEEP_EMPTY_FIELDS));
- new Label(field, SWT.NONE).setText(MessagesEditorPlugin.getString(
- "prefs.keepEmptyFields"));//$NON-NLS-1$
+ keepEmptyFields.setSelection(prefs
+ .getBoolean(MsgEditorPreferences.KEEP_EMPTY_FIELDS));
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.keepEmptyFields"));//$NON-NLS-1$
// Sort keys?
field = createFieldComposite(composite);
sortKeys = new Button(field, SWT.CHECK);
- sortKeys.setSelection(prefs.getBoolean(
- MsgEditorPreferences.SORT_KEYS));
- new Label(field, SWT.NONE).setText(MessagesEditorPlugin.getString(
- "prefs.keysSorted"));//$NON-NLS-1$
+ sortKeys.setSelection(prefs.getBoolean(MsgEditorPreferences.SORT_KEYS));
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.keysSorted"));//$NON-NLS-1$
refreshEnabledStatuses();
-
+
return composite;
}
-
/**
* @see org.eclipse.jface.preference.IPreferencePage#performOk()
*/
@@ -318,55 +313,60 @@
refreshEnabledStatuses();
return super.performOk();
}
-
-
+
/**
* @see org.eclipse.jface.preference.PreferencePage#performDefaults()
*/
protected void performDefaults() {
IPreferenceStore prefs = getPreferenceStore();
- showGeneratedBy.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.SHOW_SUPPORT_ENABLED));
- convertUnicodeToEncoded.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.UNICODE_ESCAPE_ENABLED));
- convertUnicodeToEncoded.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.UNICODE_ESCAPE_UPPERCASE));
- alignEqualSigns.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.ALIGN_EQUALS_ENABLED));
- alignEqualSigns.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.SPACES_AROUND_EQUALS_ENABLED));
- groupKeys.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.GROUP_KEYS_ENABLED));
- groupLevelDeep.setText(prefs.getDefaultString(
- MsgEditorPreferences.GROUP_LEVEL_DEEP));
- groupLineBreaks.setText(prefs.getDefaultString(
- MsgEditorPreferences.GROUP_SEP_BLANK_LINE_COUNT));
- groupAlignEqualSigns.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.GROUP_ALIGN_EQUALS_ENABLED));
- wrapLines.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.WRAP_LINES_ENABLED));
- wrapCharLimit.setText(prefs.getDefaultString(
- MsgEditorPreferences.WRAP_LINE_LENGTH));
- wrapAlignEqualSigns.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.WRAP_ALIGN_EQUALS_ENABLED));
- wrapIndentSpaces.setText(prefs.getDefaultString(
- MsgEditorPreferences.WRAP_INDENT_LENGTH));
- wrapNewLine.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.NEW_LINE_NICE));
- newLineTypeForce.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.FORCE_NEW_LINE_TYPE));
- newLineTypes[Math.min(prefs.getDefaultInt(
- MsgEditorPreferences.NEW_LINE_STYLE) - 1, 0)].setSelection(
- true);
- keepEmptyFields.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.KEEP_EMPTY_FIELDS));
- sortKeys.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.SORT_KEYS));
+ showGeneratedBy.setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.SHOW_SUPPORT_ENABLED));
+ convertUnicodeToEncoded
+ .setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.UNICODE_ESCAPE_ENABLED));
+ convertUnicodeToEncoded
+ .setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.UNICODE_ESCAPE_UPPERCASE));
+ alignEqualSigns.setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.ALIGN_EQUALS_ENABLED));
+ alignEqualSigns
+ .setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.SPACES_AROUND_EQUALS_ENABLED));
+ groupKeys.setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.GROUP_KEYS_ENABLED));
+ groupLevelDeep.setText(prefs
+ .getDefaultString(MsgEditorPreferences.GROUP_LEVEL_DEEP));
+ groupLineBreaks
+ .setText(prefs
+ .getDefaultString(MsgEditorPreferences.GROUP_SEP_BLANK_LINE_COUNT));
+ groupAlignEqualSigns
+ .setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.GROUP_ALIGN_EQUALS_ENABLED));
+ wrapLines.setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.WRAP_LINES_ENABLED));
+ wrapCharLimit.setText(prefs
+ .getDefaultString(MsgEditorPreferences.WRAP_LINE_LENGTH));
+ wrapAlignEqualSigns
+ .setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.WRAP_ALIGN_EQUALS_ENABLED));
+ wrapIndentSpaces.setText(prefs
+ .getDefaultString(MsgEditorPreferences.WRAP_INDENT_LENGTH));
+ wrapNewLine.setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.NEW_LINE_NICE));
+ newLineTypeForce.setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.FORCE_NEW_LINE_TYPE));
+ newLineTypes[Math
+ .min(prefs.getDefaultInt(MsgEditorPreferences.NEW_LINE_STYLE) - 1,
+ 0)].setSelection(true);
+ keepEmptyFields.setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.KEEP_EMPTY_FIELDS));
+ sortKeys.setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.SORT_KEYS));
refreshEnabledStatuses();
super.performDefaults();
}
- /*default*/ void refreshEnabledStatuses() {
+ /* default */void refreshEnabledStatuses() {
boolean isEncodingUnicode = convertUnicodeToEncoded.getSelection();
boolean isGroupKeyEnabled = groupKeys.getSelection();
boolean isAlignEqualsEnabled = alignEqualSigns.getSelection();
@@ -377,8 +377,8 @@
convertUnicodeUpperCase.setEnabled(isEncodingUnicode);
groupLevelDeep.setEnabled(isGroupKeyEnabled);
groupLineBreaks.setEnabled(isGroupKeyEnabled);
- groupAlignEqualSigns.setEnabled(
- isGroupKeyEnabled && isAlignEqualsEnabled);
+ groupAlignEqualSigns.setEnabled(isGroupKeyEnabled
+ && isAlignEqualsEnabled);
wrapCharLimit.setEnabled(isWrapEnabled);
wrapAlignEqualSigns.setEnabled(isWrapEnabled);
wrapIndentSpaces.setEnabled(isWrapEnabled && !isWrapAlignEqualsEnabled);
@@ -386,5 +386,5 @@
newLineTypes[i].setEnabled(isNewLineStyleForced);
}
}
-
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/GeneralPrefPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/GeneralPrefPage.java
index 194a671..7dc5c72 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/GeneralPrefPage.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/GeneralPrefPage.java
@@ -22,30 +22,31 @@
/**
* Plugin generic preference page.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
-public class GeneralPrefPage extends AbstractPrefPage {
-
+public class GeneralPrefPage extends AbstractPrefPage {
+
/* Preference fields. */
private Text keyGroupSeparator;
private Text filterLocales;
-
+
private Button convertEncodedToUnicode;
private Button supportNL;
-// private Button supportFragments;
-// private Button loadOnlyFragmentResources;
-
+ // private Button supportFragments;
+ // private Button loadOnlyFragmentResources;
+
private Button keyTreeHierarchical;
private Button keyTreeExpanded;
private Button fieldTabInserts;
-
-// private Button noTreeInEditor;
-
+
+ // private Button noTreeInEditor;
+
private Button setupRbeNatureAutomatically;
-
+
/**
* Constructor.
*/
@@ -55,111 +56,111 @@
/**
* @see org.eclipse.jface.preference.PreferencePage
- * #createContents(org.eclipse.swt.widgets.Composite)
+ * #createContents(org.eclipse.swt.widgets.Composite)
*/
protected Control createContents(Composite parent) {
MsgEditorPreferences prefs = MsgEditorPreferences.getInstance();
-
-// IPreferenceStore prefs = getPreferenceStore();
+
+ // IPreferenceStore prefs = getPreferenceStore();
Composite field = null;
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
-
+
// Key group separator
field = createFieldComposite(composite);
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.groupSep")); //$NON-NLS-1$
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.groupSep")); //$NON-NLS-1$
keyGroupSeparator = new Text(field, SWT.BORDER);
- keyGroupSeparator.setText(prefs.getSerializerConfig().getGroupLevelSeparator());
-// prefs.getString(MsgEditorPreferences.GROUP__LEVEL_SEPARATOR));
+ keyGroupSeparator.setText(prefs.getSerializerConfig()
+ .getGroupLevelSeparator());
+ // prefs.getString(MsgEditorPreferences.GROUP__LEVEL_SEPARATOR));
keyGroupSeparator.setTextLimit(2);
-
+
field = createFieldComposite(composite);
Label filterLocalesLabel = new Label(field, SWT.NONE);
- filterLocalesLabel.setText(
- MessagesEditorPlugin.getString("prefs.filterLocales.label")); //$NON-NLS-1$
- filterLocalesLabel.setToolTipText(
- MessagesEditorPlugin.getString("prefs.filterLocales.tooltip")); //$NON-NLS-1$
+ filterLocalesLabel.setText(MessagesEditorPlugin
+ .getString("prefs.filterLocales.label")); //$NON-NLS-1$
+ filterLocalesLabel.setToolTipText(MessagesEditorPlugin
+ .getString("prefs.filterLocales.tooltip")); //$NON-NLS-1$
filterLocales = new Text(field, SWT.BORDER);
filterLocales.setText(prefs.getFilterLocalesStringMatcher());
-// prefs.getString(MsgEditorPreferences.GROUP__LEVEL_SEPARATOR));
+ // prefs.getString(MsgEditorPreferences.GROUP__LEVEL_SEPARATOR));
filterLocales.setTextLimit(22);
setWidthInChars(filterLocales, 16);
-
// Convert encoded to unicode?
field = createFieldComposite(composite);
convertEncodedToUnicode = new Button(field, SWT.CHECK);
- convertEncodedToUnicode.setSelection(
- prefs.getSerializerConfig().isUnicodeEscapeEnabled());
-// prefs.getBoolean(MsgEditorPreferences.CONVERT_ENCODED_TO_UNICODE));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.convertEncoded")); //$NON-NLS-1$
+ convertEncodedToUnicode.setSelection(prefs.getSerializerConfig()
+ .isUnicodeEscapeEnabled());
+ // prefs.getBoolean(MsgEditorPreferences.CONVERT_ENCODED_TO_UNICODE));
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.convertEncoded")); //$NON-NLS-1$
// Support "NL" localization structure
field = createFieldComposite(composite);
supportNL = new Button(field, SWT.CHECK);
supportNL.setSelection(prefs.isNLSupportEnabled());
- //prefs.getBoolean(MsgEditorPreferences.SUPPORT_NL));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.supportNL")); //$NON-NLS-1$
+ // prefs.getBoolean(MsgEditorPreferences.SUPPORT_NL));
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.supportNL")); //$NON-NLS-1$
// Setup rbe validation builder on java projects automatically.
field = createFieldComposite(composite);
setupRbeNatureAutomatically = new Button(field, SWT.CHECK);
- setupRbeNatureAutomatically.setSelection(prefs.isBuilderSetupAutomatically());
- //prefs.getBoolean(MsgEditorPreferences.SUPPORT_NL));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.setupValidationBuilderAutomatically")); //$NON-NLS-1$
+ setupRbeNatureAutomatically.setSelection(prefs
+ .isBuilderSetupAutomatically());
+ // prefs.getBoolean(MsgEditorPreferences.SUPPORT_NL));
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.setupValidationBuilderAutomatically")); //$NON-NLS-1$
-// // Support loading resources from fragment
-// field = createFieldComposite(composite);
-// supportFragments = new Button(field, SWT.CHECK);
-// supportFragments.setSelection(prefs.isShowSupportEnabled());
-// new Label(field, SWT.NONE).setText(
-// MessagesEditorPlugin.getString("prefs.supportFragments")); //$NON-NLS-1$
-//
-// // Support loading resources from fragment
-// field = createFieldComposite(composite);
-// loadOnlyFragmentResources = new Button(field, SWT.CHECK);
-// loadOnlyFragmentResources.setSelection(
-// prefs.isLoadingOnlyFragmentResources());
-// //MsgEditorPreferences.getLoadOnlyFragmentResources());
-// new Label(field, SWT.NONE).setText(
-// MessagesEditorPlugin.getString("prefs.loadOnlyFragmentResources")); //$NON-NLS-1$
-
+ // // Support loading resources from fragment
+ // field = createFieldComposite(composite);
+ // supportFragments = new Button(field, SWT.CHECK);
+ // supportFragments.setSelection(prefs.isShowSupportEnabled());
+ // new Label(field, SWT.NONE).setText(
+ // MessagesEditorPlugin.getString("prefs.supportFragments")); //$NON-NLS-1$
+ //
+ // // Support loading resources from fragment
+ // field = createFieldComposite(composite);
+ // loadOnlyFragmentResources = new Button(field, SWT.CHECK);
+ // loadOnlyFragmentResources.setSelection(
+ // prefs.isLoadingOnlyFragmentResources());
+ // //MsgEditorPreferences.getLoadOnlyFragmentResources());
+ // new Label(field, SWT.NONE).setText(
+ // MessagesEditorPlugin.getString("prefs.loadOnlyFragmentResources")); //$NON-NLS-1$
+
// Default key tree mode (tree vs flat)
field = createFieldComposite(composite);
keyTreeHierarchical = new Button(field, SWT.CHECK);
- keyTreeHierarchical.setSelection(
- prefs.isKeyTreeHierarchical());
-// prefs.getBoolean(MsgEditorPreferences.KEY_TREE_HIERARCHICAL));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.keyTree.hierarchical"));//$NON-NLS-1$
+ keyTreeHierarchical.setSelection(prefs.isKeyTreeHierarchical());
+ // prefs.getBoolean(MsgEditorPreferences.KEY_TREE_HIERARCHICAL));
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.keyTree.hierarchical"));//$NON-NLS-1$
// Default key tree expand status (expanded vs collapsed)
field = createFieldComposite(composite);
keyTreeExpanded = new Button(field, SWT.CHECK);
keyTreeExpanded.setSelection(prefs.isKeyTreeExpanded());
-// prefs.getBoolean(MsgEditorPreferences.KEY_TREE_EXPANDED)); //$NON-NLS-1$
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.keyTree.expanded")); //$NON-NLS-1$
+ // prefs.getBoolean(MsgEditorPreferences.KEY_TREE_EXPANDED)); //$NON-NLS-1$
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.keyTree.expanded")); //$NON-NLS-1$
// Default tab key behaviour in text field
field = createFieldComposite(composite);
fieldTabInserts = new Button(field, SWT.CHECK);
fieldTabInserts.setSelection(prefs.isFieldTabInserts());
-// prefs.getBoolean(MsgEditorPreferences.FIELD_TAB_INSERTS));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.fieldTabInserts")); //$NON-NLS-1$
-
-// field = createFieldComposite(composite);
-// noTreeInEditor = new Button(field, SWT.CHECK);
-// noTreeInEditor.setSelection(prefs.isEditorTreeHidden());
-//// prefs.getBoolean(MsgEditorPreferences.EDITOR_TREE_HIDDEN)); //$NON-NLS-1$
-// new Label(field, SWT.NONE).setText(
-// MessagesEditorPlugin.getString("prefs.noTreeInEditor")); //$NON-NLS-1$
-
+ // prefs.getBoolean(MsgEditorPreferences.FIELD_TAB_INSERTS));
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.fieldTabInserts")); //$NON-NLS-1$
+
+ // field = createFieldComposite(composite);
+ // noTreeInEditor = new Button(field, SWT.CHECK);
+ // noTreeInEditor.setSelection(prefs.isEditorTreeHidden());
+ //// prefs.getBoolean(MsgEditorPreferences.EDITOR_TREE_HIDDEN)); //$NON-NLS-1$
+ // new Label(field, SWT.NONE).setText(
+ // MessagesEditorPlugin.getString("prefs.noTreeInEditor")); //$NON-NLS-1$
+
refreshEnabledStatuses();
return composite;
}
@@ -177,7 +178,8 @@
convertEncodedToUnicode.getSelection());
prefs.setValue(MsgEditorPreferences.NL_SUPPORT_ENABLED,
supportNL.getSelection());
- prefs.setValue(MsgEditorPreferences.ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS,
+ prefs.setValue(
+ MsgEditorPreferences.ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS,
setupRbeNatureAutomatically.getSelection());
prefs.setValue(MsgEditorPreferences.KEY_TREE_HIERARCHICAL,
keyTreeHierarchical.getSelection());
@@ -185,39 +187,41 @@
keyTreeExpanded.getSelection());
prefs.setValue(MsgEditorPreferences.FIELD_TAB_INSERTS,
fieldTabInserts.getSelection());
-// prefs.setValue(MsgEditorPreferences.EDITOR_TREE_HIDDEN,
-// noTreeInEditor.getSelection());
+ // prefs.setValue(MsgEditorPreferences.EDITOR_TREE_HIDDEN,
+ // noTreeInEditor.getSelection());
refreshEnabledStatuses();
return super.performOk();
}
-
-
+
/**
* @see org.eclipse.jface.preference.PreferencePage#performDefaults()
*/
protected void performDefaults() {
IPreferenceStore prefs = getPreferenceStore();
- keyGroupSeparator.setText(
- prefs.getDefaultString(MsgEditorPreferences.GROUP__LEVEL_SEPARATOR));
- filterLocales.setText(
- prefs.getDefaultString(MsgEditorPreferences.FILTER_LOCALES_STRING_MATCHERS));
- convertEncodedToUnicode.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.UNICODE_UNESCAPE_ENABLED));
- supportNL.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.NL_SUPPORT_ENABLED));
- keyTreeHierarchical.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.KEY_TREE_HIERARCHICAL));
- keyTreeHierarchical.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.KEY_TREE_EXPANDED));
- fieldTabInserts.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.FIELD_TAB_INSERTS));
- setupRbeNatureAutomatically.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS));
-
+ keyGroupSeparator.setText(prefs
+ .getDefaultString(MsgEditorPreferences.GROUP__LEVEL_SEPARATOR));
+ filterLocales
+ .setText(prefs
+ .getDefaultString(MsgEditorPreferences.FILTER_LOCALES_STRING_MATCHERS));
+ convertEncodedToUnicode
+ .setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.UNICODE_UNESCAPE_ENABLED));
+ supportNL.setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.NL_SUPPORT_ENABLED));
+ keyTreeHierarchical.setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.KEY_TREE_HIERARCHICAL));
+ keyTreeHierarchical.setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.KEY_TREE_EXPANDED));
+ fieldTabInserts.setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.FIELD_TAB_INSERTS));
+ setupRbeNatureAutomatically
+ .setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS));
+
refreshEnabledStatuses();
super.performDefaults();
}
-
+
private void refreshEnabledStatuses() {
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/MsgEditorPreferences.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/MsgEditorPreferences.java
index 43d789e..5576eed 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/MsgEditorPreferences.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/MsgEditorPreferences.java
@@ -40,176 +40,168 @@
/**
* Messages Editor preferences.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
-public final class MsgEditorPreferences
- implements /*IPropertiesSerializerConfig, IPropertiesDeserializerConfig,*/ IPropertyChangeListener {
-
- /** the corresponding validation message with such a preference should
- * not be generated */
- public static final int VALIDATION_MESSAGE_IGNORE = 0;
- /** the corresponding validation message with such a preference should
- * generate a marker with severity 'info' */
- public static final int VALIDATION_MESSAGE_INFO = 1;
- /** the corresponding validation message with such a preference should
- * generate a marker with severity 'warning' */
- public static final int VALIDATION_MESSAGE_WARNING = 2;
- /** the corresponding validation message with such a preference should
- * generate a marker with severity 'error' */
- public static final int VALIDATION_MESSAGE_ERROR = 3;
-
+public final class MsgEditorPreferences implements /*
+ * IPropertiesSerializerConfig,
+ * IPropertiesDeserializerConfig
+ * ,
+ */IPropertyChangeListener {
+
+ /**
+ * the corresponding validation message with such a preference should not be
+ * generated
+ */
+ public static final int VALIDATION_MESSAGE_IGNORE = 0;
+ /**
+ * the corresponding validation message with such a preference should
+ * generate a marker with severity 'info'
+ */
+ public static final int VALIDATION_MESSAGE_INFO = 1;
+ /**
+ * the corresponding validation message with such a preference should
+ * generate a marker with severity 'warning'
+ */
+ public static final int VALIDATION_MESSAGE_WARNING = 2;
+ /**
+ * the corresponding validation message with such a preference should
+ * generate a marker with severity 'error'
+ */
+ public static final int VALIDATION_MESSAGE_ERROR = 3;
+
/** Key group separator. */
- public static final String GROUP__LEVEL_SEPARATOR =
- "groupLevelSeparator"; //$NON-NLS-1$
+ public static final String GROUP__LEVEL_SEPARATOR = "groupLevelSeparator"; //$NON-NLS-1$
/** Should key tree be hiearchical by default. */
- public static final String KEY_TREE_HIERARCHICAL =
- "keyTreeHierarchical"; //$NON-NLS-1$
+ public static final String KEY_TREE_HIERARCHICAL = "keyTreeHierarchical"; //$NON-NLS-1$
/** Should key tree be expanded by default. */
- public static final String KEY_TREE_EXPANDED =
- "keyTreeExpanded"; //$NON-NLS-1$
-
+ public static final String KEY_TREE_EXPANDED = "keyTreeExpanded"; //$NON-NLS-1$
+
/** Should "Generated by" line be added to files. */
- public static final String SHOW_SUPPORT_ENABLED =
- "showSupportEnabled"; //$NON-NLS-1$
+ public static final String SHOW_SUPPORT_ENABLED = "showSupportEnabled"; //$NON-NLS-1$
/** Should Eclipse "nl" directory structure be supported. */
- public static final String NL_SUPPORT_ENABLED =
- "nLSupportEnabled"; //$NON-NLS-1$
+ public static final String NL_SUPPORT_ENABLED = "nLSupportEnabled"; //$NON-NLS-1$
/** Should resources also be loaded from fragments. */
public static final String SUPPORT_FRAGMENTS = "supportFragments"; //$NON-NLS-1$
- /**
- * Load only fragment resources when loading from fragments.
- * The default bundle is mostly located in the host plug-in.
+ /**
+ * Load only fragment resources when loading from fragments. The default
+ * bundle is mostly located in the host plug-in.
*/
- public static final String LOADING_ONLY_FRAGMENT_RESOURCES =
- "loadingOnlyFragmentResources";
-
+ public static final String LOADING_ONLY_FRAGMENT_RESOURCES = "loadingOnlyFragmentResources";
+
/** Should tab characters be inserted when tab key pressed on text field. */
- public static final String FIELD_TAB_INSERTS =
- "fieldTabInserts"; //$NON-NLS-1$
+ public static final String FIELD_TAB_INSERTS = "fieldTabInserts"; //$NON-NLS-1$
/** Should equal signs be aligned. */
- public static final String ALIGN_EQUALS_ENABLED =
- "alignEqualsEnabled"; //$NON-NLS-1$
+ public static final String ALIGN_EQUALS_ENABLED = "alignEqualsEnabled"; //$NON-NLS-1$
/** Should spaces be put around equal signs. */
- public static final String SPACES_AROUND_EQUALS_ENABLED =
- "spacesAroundEqualsEnabled"; //$NON-NLS-1$
+ public static final String SPACES_AROUND_EQUALS_ENABLED = "spacesAroundEqualsEnabled"; //$NON-NLS-1$
/** Should keys be grouped. */
- public static final String GROUP_KEYS_ENABLED =
- "groupKeysEnabled"; //$NON-NLS-1$
+ public static final String GROUP_KEYS_ENABLED = "groupKeysEnabled"; //$NON-NLS-1$
/** How many level deep should keys be grouped. */
- public static final String GROUP_LEVEL_DEEP =
- "groupLevelDeep"; //$NON-NLS-1$
+ public static final String GROUP_LEVEL_DEEP = "groupLevelDeep"; //$NON-NLS-1$
/** How many line breaks between key groups. */
- public static final String GROUP_SEP_BLANK_LINE_COUNT =
- "groupSepBlankLineCount"; //$NON-NLS-1$
+ public static final String GROUP_SEP_BLANK_LINE_COUNT = "groupSepBlankLineCount"; //$NON-NLS-1$
/** Should equal signs be aligned within groups. */
- public static final String GROUP_ALIGN_EQUALS_ENABLED =
- "groupAlignEqualsEnabled"; //$NON-NLS-1$
+ public static final String GROUP_ALIGN_EQUALS_ENABLED = "groupAlignEqualsEnabled"; //$NON-NLS-1$
/** Should lines be wrapped. */
- public static final String WRAP_LINES_ENABLED =
- "wrapLinesEnabled"; //$NON-NLS-1$
+ public static final String WRAP_LINES_ENABLED = "wrapLinesEnabled"; //$NON-NLS-1$
/** Maximum number of character after which we should wrap. */
public static final String WRAP_LINE_LENGTH = "wrapLineLength"; //$NON-NLS-1$
/** Align subsequent lines with equal signs. */
- public static final String WRAP_ALIGN_EQUALS_ENABLED =
- "wrapAlignEqualsEnabled"; //$NON-NLS-1$
+ public static final String WRAP_ALIGN_EQUALS_ENABLED = "wrapAlignEqualsEnabled"; //$NON-NLS-1$
/** Number of spaces to indent subsequent lines. */
- public static final String WRAP_INDENT_LENGTH =
- "wrapIndentLength"; //$NON-NLS-1$
-
+ public static final String WRAP_INDENT_LENGTH = "wrapIndentLength"; //$NON-NLS-1$
+
/** Should unicode values be converted to their encoded equivalent. */
- public static final String UNICODE_ESCAPE_ENABLED =
- "unicodeEscapeEnabled"; //$NON-NLS-1$
+ public static final String UNICODE_ESCAPE_ENABLED = "unicodeEscapeEnabled"; //$NON-NLS-1$
/** Should unicode values be converted to their encoded equivalent. */
- public static final String UNICODE_ESCAPE_UPPERCASE =
- "unicodeEscapeUppercase"; //$NON-NLS-1$
+ public static final String UNICODE_ESCAPE_UPPERCASE = "unicodeEscapeUppercase"; //$NON-NLS-1$
/** Should encoded values be converted to their unicode equivalent. */
- public static final String UNICODE_UNESCAPE_ENABLED =
- "unicodeUnescapeEnabled"; //$NON-NLS-1$
-
+ public static final String UNICODE_UNESCAPE_ENABLED = "unicodeUnescapeEnabled"; //$NON-NLS-1$
+
/** Impose a given new line type. */
- public static final String FORCE_NEW_LINE_TYPE =
- "forceNewLineType"; //$NON-NLS-1$
+ public static final String FORCE_NEW_LINE_TYPE = "forceNewLineType"; //$NON-NLS-1$
/** How new lines are represented in resource bundle. */
public static final String NEW_LINE_STYLE = "newLineStyle"; //$NON-NLS-1$
/** Should new lines character produce a line break in properties files. */
public static final String NEW_LINE_NICE = "newLineNice"; //$NON-NLS-1$
- /** Report missing values with given level of reporting: IGNORE, INFO, WARNING, ERROR. */
- public static final String REPORT_MISSING_VALUES_LEVEL =
- "detectMissingValuesLevel"; //$NON-NLS-1$
+ /**
+ * Report missing values with given level of reporting: IGNORE, INFO,
+ * WARNING, ERROR.
+ */
+ public static final String REPORT_MISSING_VALUES_LEVEL = "detectMissingValuesLevel"; //$NON-NLS-1$
/** Report duplicate values. */
- public static final String REPORT_DUPL_VALUES_LEVEL =
- "reportDuplicateValuesLevel"; //$NON-NLS-1$
+ public static final String REPORT_DUPL_VALUES_LEVEL = "reportDuplicateValuesLevel"; //$NON-NLS-1$
/** Report duplicate values. */
- public static final String REPORT_DUPL_VALUES_ONLY_IN_ROOT_LOCALE =
- "reportDuplicateValuesOnlyInRootLocale"; //$NON-NLS-1$
+ public static final String REPORT_DUPL_VALUES_ONLY_IN_ROOT_LOCALE = "reportDuplicateValuesOnlyInRootLocale"; //$NON-NLS-1$
/** Report similar values. */
- public static final String REPORT_SIM_VALUES_LEVEL =
- "reportSimilarValuesLevel"; //$NON-NLS-1$
+ public static final String REPORT_SIM_VALUES_LEVEL = "reportSimilarValuesLevel"; //$NON-NLS-1$
/** Report similar values: word compare. */
- public static final String REPORT_SIM_VALUES_WORD_COMPARE =
- "reportSimilarValuesWordCompare"; //$NON-NLS-1$
+ public static final String REPORT_SIM_VALUES_WORD_COMPARE = "reportSimilarValuesWordCompare"; //$NON-NLS-1$
/** Report similar values: levensthein distance. */
- public static final String REPORT_SIM_VALUES_LEVENSTHEIN =
- "reportSimilarValuesLevensthein"; //$NON-NLS-1$
+ public static final String REPORT_SIM_VALUES_LEVENSTHEIN = "reportSimilarValuesLevensthein"; //$NON-NLS-1$
/** Report similar values: precision. */
- public static final String REPORT_SIM_VALUES_PRECISION =
- "reportSimilarValuesPrecision"; //$NON-NLS-1$
-
+ public static final String REPORT_SIM_VALUES_PRECISION = "reportSimilarValuesPrecision"; //$NON-NLS-1$
+
/** Don't show the tree within the editor. */
- public static final String EDITOR_TREE_HIDDEN =
- "editorTreeHidden"; //$NON-NLS-1$
+ public static final String EDITOR_TREE_HIDDEN = "editorTreeHidden"; //$NON-NLS-1$
/** Keep empty fields. */
- public static final String KEEP_EMPTY_FIELDS =
- "keepEmptyFields"; //$NON-NLS-1$
-
+ public static final String KEEP_EMPTY_FIELDS = "keepEmptyFields"; //$NON-NLS-1$
+
/** Sort keys. */
public static final String SORT_KEYS = "sortKeys"; //$NON-NLS-1$
-
+
/** Display comment editor for default language. */
- public static final String DISPLAY_DEFAULT_COMMENT_FIELD =
- "displayCommentFieldNL"; //$NON-NLS-1$
- /** Display comment editor for all languages*/
- public static final String DISPLAY_LANG_COMMENT_FIELDS =
- "displayLangCommentFieldsNL"; //$NON-NLS-1$
-
- /** Locales filter and order defined as a comma separated list of string matchers */
+ public static final String DISPLAY_DEFAULT_COMMENT_FIELD = "displayCommentFieldNL"; //$NON-NLS-1$
+ /** Display comment editor for all languages */
+ public static final String DISPLAY_LANG_COMMENT_FIELDS = "displayLangCommentFieldsNL"; //$NON-NLS-1$
+
+ /**
+ * Locales filter and order defined as a comma separated list of string
+ * matchers
+ */
public static final String FILTER_LOCALES_STRING_MATCHERS = "localesFilterStringMatchers";
-
- /** When true the builder that validates translation files is
- * automatically added to java projects when the plugin is started
- * or when a new project is added. */
- public static final String ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS =
- "addMsgEditorBuilderToJavaProjects";
-
- /** holds what filter is activated. for the properties displayed in the editor. */
+
+ /**
+ * When true the builder that validates translation files is automatically
+ * added to java projects when the plugin is started or when a new project
+ * is added.
+ */
+ public static final String ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS = "addMsgEditorBuilderToJavaProjects";
+
+ /**
+ * holds what filter is activated. for the properties displayed in the
+ * editor.
+ */
public static final String PROPERTIES_DISPLAYED_FILTER = "propertiesFilter";
-
- /** true to enable the indexer false otherwise.
- * the indexer is used to generate list of suggestions in the translations.
- * this is currently experimental. */
+
+ /**
+ * true to enable the indexer false otherwise. the indexer is used to
+ * generate list of suggestions in the translations. this is currently
+ * experimental.
+ */
public static final String ENABLE_PROPERTIES_INDEXER = "enablePropertiesIndexer";
-
+
/** MsgEditorPreferences. */
- private static final Preferences PREFS =
- MessagesEditorPlugin.getDefault().getPluginPreferences();
-
- private static final MsgEditorPreferences INSTANCE =
- new MsgEditorPreferences();
-
+ private static final Preferences PREFS = MessagesEditorPlugin.getDefault()
+ .getPluginPreferences();
+
+ private static final MsgEditorPreferences INSTANCE = new MsgEditorPreferences();
+
private final IPropertiesSerializerConfig serializerConfig = new PropertiesSerializerConfig();
-
+
private final IPropertiesDeserializerConfig deserializerConfig = new PropertiesDeserializerConfig();
-
+
private StringMatcher[] cachedCompiledLocaleFilter;
-
+
/**
* Constructor.
*/
@@ -220,33 +212,36 @@
public static MsgEditorPreferences getInstance() {
return INSTANCE;
}
-
-
+
public IPropertiesSerializerConfig getSerializerConfig() {
- return serializerConfig;
- }
+ return serializerConfig;
+ }
- public IPropertiesDeserializerConfig getDeserializerConfig() {
- return deserializerConfig;
- }
+ public IPropertiesDeserializerConfig getDeserializerConfig() {
+ return deserializerConfig;
+ }
- /**
+ /**
* Gets whether pressing tab inserts a tab in a field.
+ *
* @return <code>true</code> if pressing tab inserts a tab in a field
*/
public boolean isFieldTabInserts() {
return PREFS.getBoolean(FIELD_TAB_INSERTS);
}
-
+
/**
* Gets whether key tree should be displayed in hiearchical way by default.
+ *
* @return <code>true</code> if hierarchical
*/
public boolean isKeyTreeHierarchical() {
return PREFS.getBoolean(KEY_TREE_HIERARCHICAL);
}
+
/**
* Gets whether key tree should be show expaned by default.
+ *
* @return <code>true</code> if expanded
*/
public boolean isKeyTreeExpanded() {
@@ -255,60 +250,65 @@
/**
* Gets whether to support Eclipse NL directory structure.
+ *
* @return <code>true</code> if supported
*/
public boolean isNLSupportEnabled() {
return PREFS.getBoolean(NL_SUPPORT_ENABLED);
}
-
+
/**
* Gets whether to support resources found in fragments.
+ *
* @return <code>true</code> if supported
*/
public boolean isLoadingOnlyFragmentResources() {
return PREFS.getBoolean(LOADING_ONLY_FRAGMENT_RESOURCES);
}
-
+
/**
* Gets whether to support resources found in fragments.
+ *
* @return <code>true</code> if supported
*/
public boolean getSupportFragments() {
return PREFS.getBoolean(SUPPORT_FRAGMENTS);
}
-
-// /**
-// * True iff the I18N editor page should contiain a comment field for the
-// * default language
-// *
-// * @return boolean
-// */
-// public static boolean getDisplayDefaultCommentField() {
-// return PREFS.getBoolean(DISPLAY_DEFAULT_COMMENT_FIELD);
-// }
-//
-// /**
-// * True iff the I18N editor page should contain a comment field for each
-// * individual language
-// *
-// * @return boolean
-// */
-// public static boolean getDisplayLangCommentFields() {
-// return PREFS.getBoolean(DISPLAY_LANG_COMMENT_FIELDS);
-// }
-//
+
+ // /**
+ // * True iff the I18N editor page should contiain a comment field for the
+ // * default language
+ // *
+ // * @return boolean
+ // */
+ // public static boolean getDisplayDefaultCommentField() {
+ // return PREFS.getBoolean(DISPLAY_DEFAULT_COMMENT_FIELD);
+ // }
+ //
+ // /**
+ // * True iff the I18N editor page should contain a comment field for each
+ // * individual language
+ // *
+ // * @return boolean
+ // */
+ // public static boolean getDisplayLangCommentFields() {
+ // return PREFS.getBoolean(DISPLAY_LANG_COMMENT_FIELDS);
+ // }
+ //
/**
- * @return the filter to apply on the displayed properties.
- * One of the {@link IMessagesEditorChangeListener}.SHOW_*
- * Byt default: show all.
+ * @return the filter to apply on the displayed properties. One of the
+ * {@link IMessagesEditorChangeListener}.SHOW_* Byt default: show
+ * all.
*/
public int getPropertiesFilter() {
return PREFS.getInt(PROPERTIES_DISPLAYED_FILTER);
}
+
/**
- * @param filter The filter to apply on the displayed properties.
- * One of the {@link IMessagesEditorChangeListener}.SHOW_*
+ * @param filter
+ * The filter to apply on the displayed properties. One of the
+ * {@link IMessagesEditorChangeListener}.SHOW_*
*/
public void setPropertiesFilter(int filter) {
PREFS.setValue(PROPERTIES_DISPLAYED_FILTER, filter);
@@ -317,6 +317,7 @@
/**
* Gets whether we want to overwrite system (or Eclipse) default new line
* type when generating file.
+ *
* @return <code>true</code> if overwriting
*/
public boolean getForceNewLineType() {
@@ -325,67 +326,76 @@
/**
* Gets whether to report keys with missing values.
+ *
* @return <code>true</code> if reporting
*/
public boolean getReportMissingValues() {
- return PREFS.getInt(REPORT_MISSING_VALUES_LEVEL) != VALIDATION_MESSAGE_IGNORE;
- //return PREFS.getBoolean(REPORT_MISSING_VALUES);
+ return PREFS.getInt(REPORT_MISSING_VALUES_LEVEL) != VALIDATION_MESSAGE_IGNORE;
+ // return PREFS.getBoolean(REPORT_MISSING_VALUES);
}
+
/**
* Returns the level of reporting for missing values.
+ *
* @return VALIDATION_MESSAGE_IGNORE or VALIDATION_MESSAGE_INFO or
- * VALIDATION_MESSAGE_WARNING or VALIDATION_MESSAGE_ERROR.
+ * VALIDATION_MESSAGE_WARNING or VALIDATION_MESSAGE_ERROR.
*/
public int getReportMissingValuesLevel() {
- return PREFS.getInt(REPORT_MISSING_VALUES_LEVEL);
+ return PREFS.getInt(REPORT_MISSING_VALUES_LEVEL);
}
-
-
+
/**
* Gets whether to report keys with duplicate values.
+ *
* @return <code>true</code> if reporting
*/
public boolean getReportDuplicateValues() {
return PREFS.getInt(REPORT_DUPL_VALUES_LEVEL) != VALIDATION_MESSAGE_IGNORE;
}
-
+
/**
* Returns the level of reporting for duplicate values.
+ *
* @return VALIDATION_MESSAGE_IGNORE or VALIDATION_MESSAGE_INFO or
- * VALIDATION_MESSAGE_WARNING or VALIDATION_MESSAGE_ERROR.
+ * VALIDATION_MESSAGE_WARNING or VALIDATION_MESSAGE_ERROR.
*/
public int getReportDuplicateValuesLevel() {
return PREFS.getInt(REPORT_DUPL_VALUES_LEVEL);
}
-
+
/**
* Gets whether to report keys with duplicate values.
- * @return <code>true</code> if reporting duplicate is applied
- * only for the root locale (aka default properties file.)
+ *
+ * @return <code>true</code> if reporting duplicate is applied only for the
+ * root locale (aka default properties file.)
*/
public boolean getReportDuplicateValuesOnlyInRootLocales() {
return PREFS.getBoolean(REPORT_DUPL_VALUES_ONLY_IN_ROOT_LOCALE);
}
-
+
/**
* Gets whether to report keys with similar values.
+ *
* @return <code>true</code> if reporting
*/
public boolean getReportSimilarValues() {
return PREFS.getInt(REPORT_SIM_VALUES_LEVEL) != VALIDATION_MESSAGE_IGNORE;
}
+
/**
* Returns the level of reporting for similar values.
+ *
* @return VALIDATION_MESSAGE_IGNORE or VALIDATION_MESSAGE_INFO or
- * VALIDATION_MESSAGE_WARNING or VALIDATION_MESSAGE_ERROR.
+ * VALIDATION_MESSAGE_WARNING or VALIDATION_MESSAGE_ERROR.
*/
public int getReportSimilarValuesLevel() {
- return PREFS.getInt(REPORT_SIM_VALUES_LEVEL);
+ return PREFS.getInt(REPORT_SIM_VALUES_LEVEL);
}
/**
* Gets whether to use the "word compare" method when reporting similar
* values.
+ *
* @return <code>true</code> if using "word compare" method
*/
public boolean getReportSimilarValuesWordCompare() {
@@ -393,8 +403,8 @@
}
/**
- * Gets whether to use the Levensthein method when reporting similar
- * values.
+ * Gets whether to use the Levensthein method when reporting similar values.
+ *
* @return <code>true</code> if using Levensthein method
*/
public boolean getReportSimilarValuesLevensthein() {
@@ -403,7 +413,8 @@
/**
* Gets the minimum precision level to use for determining when to report
- * similarities.
+ * similarities.
+ *
* @return precision
*/
public double getReportSimilarValuesPrecision() {
@@ -412,14 +423,16 @@
/**
* Gets whether a tree shall be displayed within the editor or not.
+ *
* @return <code>true</code> A tree shall not be displayed.
*/
public boolean isEditorTreeHidden() {
return PREFS.getBoolean(EDITOR_TREE_HIDDEN);
}
-
+
/**
* Gets whether to keep empty fields.
+ *
* @return <code>true</code> if empty fields are to be kept.
*/
public boolean getKeepEmptyFields() {
@@ -428,304 +441,322 @@
/**
* @return a comma separated list of locales-string-matchers.
- * <p>
- * Note: StringMatcher is an internal API duplicated in many different places of eclipse.
- * The only project that decided to make it public is GMF (org.eclipse.gmf.runtime.common.core.util)
- * Although they have been request to make it public since 2001:
- * http://dev.eclipse.org/newslists/news.eclipse.tools/msg00666.html
- * </p>
- * <p>
- * We choose org.eclipse.ui.internal.misc in the org.eclipse.ui.workbench
- * plugin as it is part of RCP; the most common one.
- * </p>
+ * <p>
+ * Note: StringMatcher is an internal API duplicated in many
+ * different places of eclipse. The only project that decided to
+ * make it public is GMF (org.eclipse.gmf.runtime.common.core.util)
+ * Although they have been request to make it public since 2001:
+ * http://dev.eclipse.org/newslists/news.eclipse.tools/msg00666.html
+ * </p>
+ * <p>
+ * We choose org.eclipse.ui.internal.misc in the
+ * org.eclipse.ui.workbench plugin as it is part of RCP; the most
+ * common one.
+ * </p>
* @see org.eclipse.ui.internal.misc.StringMatcher
*/
public String getFilterLocalesStringMatcher() {
- return PREFS.getString(FILTER_LOCALES_STRING_MATCHERS);
+ return PREFS.getString(FILTER_LOCALES_STRING_MATCHERS);
}
+
/**
* @return The StringMatchers compiled from #getFilterLocalesStringMatcher()
*/
public synchronized StringMatcher[] getFilterLocalesStringMatchers() {
- if (cachedCompiledLocaleFilter != null) {
- return cachedCompiledLocaleFilter;
- }
-
- String pref = PREFS.getString(FILTER_LOCALES_STRING_MATCHERS);
- StringTokenizer tokenizer = new StringTokenizer(pref, ";, ", false);
- cachedCompiledLocaleFilter = new StringMatcher[tokenizer.countTokens()];
- int ii = 0;
- while (tokenizer.hasMoreTokens()) {
- StringMatcher pattern = new StringMatcher(tokenizer.nextToken().trim(), true, false);
- cachedCompiledLocaleFilter[ii] = pattern;
- ii++;
- }
- return cachedCompiledLocaleFilter;
+ if (cachedCompiledLocaleFilter != null) {
+ return cachedCompiledLocaleFilter;
+ }
+
+ String pref = PREFS.getString(FILTER_LOCALES_STRING_MATCHERS);
+ StringTokenizer tokenizer = new StringTokenizer(pref, ";, ", false);
+ cachedCompiledLocaleFilter = new StringMatcher[tokenizer.countTokens()];
+ int ii = 0;
+ while (tokenizer.hasMoreTokens()) {
+ StringMatcher pattern = new StringMatcher(tokenizer.nextToken()
+ .trim(), true, false);
+ cachedCompiledLocaleFilter[ii] = pattern;
+ ii++;
+ }
+ return cachedCompiledLocaleFilter;
}
-
+
/**
- * Gets whether the rbe nature and rbe builder are automatically setup
- * on java projects in the workspace.
- * @return <code>true</code> Setup automatically the rbe builder
- * on java projects.
+ * Gets whether the rbe nature and rbe builder are automatically setup on
+ * java projects in the workspace.
+ *
+ * @return <code>true</code> Setup automatically the rbe builder on java
+ * projects.
*/
public boolean isBuilderSetupAutomatically() {
return PREFS.getBoolean(ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS);
}
-
+
/**
- * Notified when the value of the filter locales preferences changes.
- *
- * @param event the property change event object describing which
- * property changed and how
- */
- public void propertyChange(Preferences.PropertyChangeEvent event) {
- if (FILTER_LOCALES_STRING_MATCHERS.equals(event.getProperty())) {
- onLocalFilterChange();
- } else if (ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS.equals(event.getProperty())) {
- onAddValidationBuilderChange();
- }
- }
-
- /**
- * Called when the locales filter value is changed.
- * <p>
- * Takes care of reloading the opened editors and calling the full-build
- * of the rbeBuilder on all project that use it.
- * </p>
- */
- private void onLocalFilterChange() {
- cachedCompiledLocaleFilter = null;
-
- //first: refresh the editors.
- //look at the opened editors and reload them if possible
- //otherwise, save them, close them and re-open them.
- IWorkbenchPage[] pages =
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPages();
- for (int i = 0; i < pages.length; i++) {
- IEditorReference[] edRefs = pages[i].getEditorReferences();
- for (int j = 0; j < edRefs.length; j++) {
- IEditorReference ref = edRefs[j];
- IEditorPart edPart = ref.getEditor(false);
- if (edPart != null && edPart instanceof MessagesEditor) {
- //the editor was loaded. reload it:
- MessagesEditor meToReload = (MessagesEditor)edPart;
- meToReload.reloadDisplayedContents();
- }
- }
- }
-
- //second: clean and build all the projects that have the rbe builder.
- //Calls the builder for a clean and build on all projects of the workspace.
- try {
- IProject[] projs = ResourcesPlugin.getWorkspace().getRoot().getProjects();
- for (int i = 0; i < projs.length; i++) {
- if (projs[i].isAccessible()) {
- ICommand[] builders = projs[i].getDescription().getBuildSpec();
- for (int j = 0; j < builders.length; j++) {
- if (Builder.BUILDER_ID.equals(builders[j].getBuilderName())) {
- projs[i].build(IncrementalProjectBuilder.FULL_BUILD,
- Builder.BUILDER_ID, null, new NullProgressMonitor());
- break;
- }
- }
- }
- }
- } catch (CoreException ce) {
- IStatus status= new Status(IStatus.ERROR, MessagesEditorPlugin.PLUGIN_ID, IStatus.OK,
- ce.getMessage(), ce);
- MessagesEditorPlugin.getDefault().getLog().log(status);
- }
- }
-
- /**
- * Called when the value of the setting up automatically the validation builder to
- * projects is changed.
- * <p>
- * When changed to true, call the static method that goes through
- * the projects accessible in the workspace and if they have a java nature,
- * make sure they also have the rbe nature and rbe builder.
- * </p>
- * <p>
- * When changed to false, make a dialog offering the user to remove all setup
- * builders from the projects where it can be found.
- * </p>
- */
- private void onAddValidationBuilderChange() {
- if (isBuilderSetupAutomatically()) {
- ToggleNatureAction.addOrRemoveNatureOnAllJavaProjects(true);
- } else {
- boolean res =
- MessageDialog.openQuestion(
- PlatformUI.getWorkbench().getDisplay().getActiveShell(),
- MessagesEditorPlugin.getString("prefs.removeAlreadyInstalledValidators.title"),
- MessagesEditorPlugin.getString("prefs.removeAlreadyInstalledValidators.text"));
- if (res) {
- ToggleNatureAction.addOrRemoveNatureOnAllJavaProjects(false);
- }
- }
- }
-
- //###########################################################################################
- //###############################PropertiesSerializerConfig##################################
- //###########################################################################################
-
-// /**
-// * Gets whether to escape unicode characters when generating file.
-// * @return <code>true</code> if escaping
-// */
-// public boolean isUnicodeEscapeEnabled() {
-// return PREFS.getBoolean(UNICODE_ESCAPE_ENABLED);
-// }
-//
-// /**
-// * Gets the new line type to use when overwriting system (or Eclipse)
-// * default new line type when generating file. Use constants to this
-// * effect.
-// * @return new line type
-// */
-// public int getNewLineStyle() {
-// return PREFS.getInt(NEW_LINE_STYLE);
-// }
-//
-// /**
-// * Gets how many blank lines should separate groups when generating file.
-// * @return how many blank lines between groups
-// */
-// public int getGroupSepBlankLineCount() {
-// return PREFS.getInt(GROUP_SEP_BLANK_LINE_COUNT);
-// }
-//
-// /**
-// * Gets whether to print "Generated By..." comment when generating file.
-// * @return <code>true</code> if we print it
-// */
-// public boolean isShowSupportEnabled() {
-// return PREFS.getBoolean(SHOW_SUPPORT_ENABLED);
-// }
-//
-// /**
-// * Gets whether keys should be grouped when generating file.
-// * @return <code>true</code> if keys should be grouped
-// */
-// public boolean isGroupKeysEnabled() {
-// return PREFS.getBoolean(GROUP_KEYS_ENABLED);
-// }
-//
-// /**
-// * Gets whether escaped unicode "alpha" characters should be uppercase
-// * when generating file.
-// * @return <code>true</code> if uppercase
-// */
-// public boolean isUnicodeEscapeUppercase() {
-// return PREFS.getBoolean(UNICODE_ESCAPE_UPPERCASE);
-// }
-//
-// /**
-// * Gets the number of character after which lines should be wrapped when
-// * generating file.
-// * @return number of characters
-// */
-// public int getWrapLineLength() {
-// return PREFS.getInt(WRAP_LINE_LENGTH);
-// }
-//
-// /**
-// * Gets whether lines should be wrapped if too big when generating file.
-// * @return <code>true</code> if wrapped
-// */
-// public boolean isWrapLinesEnabled() {
-// return PREFS.getBoolean(WRAP_LINES_ENABLED);
-// }
-//
-// /**
-// * Gets whether wrapped lines should be aligned with equal sign when
-// * generating file.
-// * @return <code>true</code> if aligned
-// */
-// public boolean isWrapAlignEqualsEnabled() {
-// return PREFS.getBoolean(WRAP_ALIGN_EQUALS_ENABLED);
-// }
-//
-// /**
-// * Gets the number of spaces to use for indentation of wrapped lines when
-// * generating file.
-// * @return number of spaces
-// */
-// public int getWrapIndentLength() {
-// return PREFS.getInt(WRAP_INDENT_LENGTH);
-// }
-//
-// /**
-// * Gets whether there should be spaces around equals signs when generating
-// * file.
-// * @return <code>true</code> there if should be spaces around equals signs
-// */
-// public boolean isSpacesAroundEqualsEnabled() {
-// return PREFS.getBoolean(SPACES_AROUND_EQUALS_ENABLED);
-// }
-//
-// /**
-// * Gets whether new lines are escaped or printed as is when generating file.
-// * @return <code>true</code> if printed as is.
-// */
-// public boolean isNewLineNice() {
-// return PREFS.getBoolean(NEW_LINE_NICE);
-// }
-//
-// /**
-// * Gets how many level deep keys should be grouped when generating file.
-// * @return how many level deep
-// */
-// public int getGroupLevelDepth() {
-// return PREFS.getInt(GROUP_LEVEL_DEEP);
-// }
-//
-// /**
-// * Gets key group separator.
-// * @return key group separator.
-// */
-// public String getGroupLevelSeparator() {
-// return PREFS.getString(GROUP__LEVEL_SEPARATOR);
-// }
-//
-// /**
-// * Gets whether equals signs should be aligned when generating file.
-// * @return <code>true</code> if equals signs should be aligned
-// */
-// public boolean isAlignEqualsEnabled() {
-// return PREFS.getBoolean(ALIGN_EQUALS_ENABLED);
-// }
-//
-// /**
-// * Gets whether equal signs should be aligned within each groups when
-// * generating file.
-// * @return <code>true</code> if equal signs should be aligned within groups
-// */
-// public boolean isGroupAlignEqualsEnabled() {
-// return PREFS.getBoolean(GROUP_ALIGN_EQUALS_ENABLED);
-// }
-//
-// /**
-// * Gets whether to sort keys upon serializing them.
-// * @return <code>true</code> if keys are to be sorted.
-// */
-// public boolean isKeySortingEnabled() {
-// return PREFS.getBoolean(SORT_KEYS);
-// }
-
- //###########################################################################################
- //###############################PropertiesSerializerConfig##################################
- //###########################################################################################
-
-
-// /**
-// * Gets whether to convert encoded strings to unicode characters when
-// * reading file.
-// * @return <code>true</code> if converting
-// */
-// public boolean isUnicodeUnescapeEnabled() {
-// return PREFS.getBoolean(UNICODE_UNESCAPE_ENABLED);
-// }
-
+ * Notified when the value of the filter locales preferences changes.
+ *
+ * @param event
+ * the property change event object describing which property
+ * changed and how
+ */
+ public void propertyChange(Preferences.PropertyChangeEvent event) {
+ if (FILTER_LOCALES_STRING_MATCHERS.equals(event.getProperty())) {
+ onLocalFilterChange();
+ } else if (ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS.equals(event
+ .getProperty())) {
+ onAddValidationBuilderChange();
+ }
+ }
+
+ /**
+ * Called when the locales filter value is changed.
+ * <p>
+ * Takes care of reloading the opened editors and calling the full-build of
+ * the rbeBuilder on all project that use it.
+ * </p>
+ */
+ private void onLocalFilterChange() {
+ cachedCompiledLocaleFilter = null;
+
+ // first: refresh the editors.
+ // look at the opened editors and reload them if possible
+ // otherwise, save them, close them and re-open them.
+ IWorkbenchPage[] pages = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getPages();
+ for (int i = 0; i < pages.length; i++) {
+ IEditorReference[] edRefs = pages[i].getEditorReferences();
+ for (int j = 0; j < edRefs.length; j++) {
+ IEditorReference ref = edRefs[j];
+ IEditorPart edPart = ref.getEditor(false);
+ if (edPart != null && edPart instanceof MessagesEditor) {
+ // the editor was loaded. reload it:
+ MessagesEditor meToReload = (MessagesEditor) edPart;
+ meToReload.reloadDisplayedContents();
+ }
+ }
+ }
+
+ // second: clean and build all the projects that have the rbe builder.
+ // Calls the builder for a clean and build on all projects of the
+ // workspace.
+ try {
+ IProject[] projs = ResourcesPlugin.getWorkspace().getRoot()
+ .getProjects();
+ for (int i = 0; i < projs.length; i++) {
+ if (projs[i].isAccessible()) {
+ ICommand[] builders = projs[i].getDescription()
+ .getBuildSpec();
+ for (int j = 0; j < builders.length; j++) {
+ if (Builder.BUILDER_ID.equals(builders[j]
+ .getBuilderName())) {
+ projs[i].build(
+ IncrementalProjectBuilder.FULL_BUILD,
+ Builder.BUILDER_ID, null,
+ new NullProgressMonitor());
+ break;
+ }
+ }
+ }
+ }
+ } catch (CoreException ce) {
+ IStatus status = new Status(IStatus.ERROR,
+ MessagesEditorPlugin.PLUGIN_ID, IStatus.OK,
+ ce.getMessage(), ce);
+ MessagesEditorPlugin.getDefault().getLog().log(status);
+ }
+ }
+
+ /**
+ * Called when the value of the setting up automatically the validation
+ * builder to projects is changed.
+ * <p>
+ * When changed to true, call the static method that goes through the
+ * projects accessible in the workspace and if they have a java nature, make
+ * sure they also have the rbe nature and rbe builder.
+ * </p>
+ * <p>
+ * When changed to false, make a dialog offering the user to remove all
+ * setup builders from the projects where it can be found.
+ * </p>
+ */
+ private void onAddValidationBuilderChange() {
+ if (isBuilderSetupAutomatically()) {
+ ToggleNatureAction.addOrRemoveNatureOnAllJavaProjects(true);
+ } else {
+ boolean res = MessageDialog
+ .openQuestion(
+ PlatformUI.getWorkbench().getDisplay()
+ .getActiveShell(),
+ MessagesEditorPlugin
+ .getString("prefs.removeAlreadyInstalledValidators.title"),
+ MessagesEditorPlugin
+ .getString("prefs.removeAlreadyInstalledValidators.text"));
+ if (res) {
+ ToggleNatureAction.addOrRemoveNatureOnAllJavaProjects(false);
+ }
+ }
+ }
+
+ // ###########################################################################################
+ // ###############################PropertiesSerializerConfig##################################
+ // ###########################################################################################
+
+ // /**
+ // * Gets whether to escape unicode characters when generating file.
+ // * @return <code>true</code> if escaping
+ // */
+ // public boolean isUnicodeEscapeEnabled() {
+ // return PREFS.getBoolean(UNICODE_ESCAPE_ENABLED);
+ // }
+ //
+ // /**
+ // * Gets the new line type to use when overwriting system (or Eclipse)
+ // * default new line type when generating file. Use constants to this
+ // * effect.
+ // * @return new line type
+ // */
+ // public int getNewLineStyle() {
+ // return PREFS.getInt(NEW_LINE_STYLE);
+ // }
+ //
+ // /**
+ // * Gets how many blank lines should separate groups when generating file.
+ // * @return how many blank lines between groups
+ // */
+ // public int getGroupSepBlankLineCount() {
+ // return PREFS.getInt(GROUP_SEP_BLANK_LINE_COUNT);
+ // }
+ //
+ // /**
+ // * Gets whether to print "Generated By..." comment when generating file.
+ // * @return <code>true</code> if we print it
+ // */
+ // public boolean isShowSupportEnabled() {
+ // return PREFS.getBoolean(SHOW_SUPPORT_ENABLED);
+ // }
+ //
+ // /**
+ // * Gets whether keys should be grouped when generating file.
+ // * @return <code>true</code> if keys should be grouped
+ // */
+ // public boolean isGroupKeysEnabled() {
+ // return PREFS.getBoolean(GROUP_KEYS_ENABLED);
+ // }
+ //
+ // /**
+ // * Gets whether escaped unicode "alpha" characters should be uppercase
+ // * when generating file.
+ // * @return <code>true</code> if uppercase
+ // */
+ // public boolean isUnicodeEscapeUppercase() {
+ // return PREFS.getBoolean(UNICODE_ESCAPE_UPPERCASE);
+ // }
+ //
+ // /**
+ // * Gets the number of character after which lines should be wrapped when
+ // * generating file.
+ // * @return number of characters
+ // */
+ // public int getWrapLineLength() {
+ // return PREFS.getInt(WRAP_LINE_LENGTH);
+ // }
+ //
+ // /**
+ // * Gets whether lines should be wrapped if too big when generating file.
+ // * @return <code>true</code> if wrapped
+ // */
+ // public boolean isWrapLinesEnabled() {
+ // return PREFS.getBoolean(WRAP_LINES_ENABLED);
+ // }
+ //
+ // /**
+ // * Gets whether wrapped lines should be aligned with equal sign when
+ // * generating file.
+ // * @return <code>true</code> if aligned
+ // */
+ // public boolean isWrapAlignEqualsEnabled() {
+ // return PREFS.getBoolean(WRAP_ALIGN_EQUALS_ENABLED);
+ // }
+ //
+ // /**
+ // * Gets the number of spaces to use for indentation of wrapped lines when
+ // * generating file.
+ // * @return number of spaces
+ // */
+ // public int getWrapIndentLength() {
+ // return PREFS.getInt(WRAP_INDENT_LENGTH);
+ // }
+ //
+ // /**
+ // * Gets whether there should be spaces around equals signs when generating
+ // * file.
+ // * @return <code>true</code> there if should be spaces around equals signs
+ // */
+ // public boolean isSpacesAroundEqualsEnabled() {
+ // return PREFS.getBoolean(SPACES_AROUND_EQUALS_ENABLED);
+ // }
+ //
+ // /**
+ // * Gets whether new lines are escaped or printed as is when generating
+ // file.
+ // * @return <code>true</code> if printed as is.
+ // */
+ // public boolean isNewLineNice() {
+ // return PREFS.getBoolean(NEW_LINE_NICE);
+ // }
+ //
+ // /**
+ // * Gets how many level deep keys should be grouped when generating file.
+ // * @return how many level deep
+ // */
+ // public int getGroupLevelDepth() {
+ // return PREFS.getInt(GROUP_LEVEL_DEEP);
+ // }
+ //
+ // /**
+ // * Gets key group separator.
+ // * @return key group separator.
+ // */
+ // public String getGroupLevelSeparator() {
+ // return PREFS.getString(GROUP__LEVEL_SEPARATOR);
+ // }
+ //
+ // /**
+ // * Gets whether equals signs should be aligned when generating file.
+ // * @return <code>true</code> if equals signs should be aligned
+ // */
+ // public boolean isAlignEqualsEnabled() {
+ // return PREFS.getBoolean(ALIGN_EQUALS_ENABLED);
+ // }
+ //
+ // /**
+ // * Gets whether equal signs should be aligned within each groups when
+ // * generating file.
+ // * @return <code>true</code> if equal signs should be aligned within
+ // groups
+ // */
+ // public boolean isGroupAlignEqualsEnabled() {
+ // return PREFS.getBoolean(GROUP_ALIGN_EQUALS_ENABLED);
+ // }
+ //
+ // /**
+ // * Gets whether to sort keys upon serializing them.
+ // * @return <code>true</code> if keys are to be sorted.
+ // */
+ // public boolean isKeySortingEnabled() {
+ // return PREFS.getBoolean(SORT_KEYS);
+ // }
+
+ // ###########################################################################################
+ // ###############################PropertiesSerializerConfig##################################
+ // ###########################################################################################
+
+ // /**
+ // * Gets whether to convert encoded strings to unicode characters when
+ // * reading file.
+ // * @return <code>true</code> if converting
+ // */
+ // public boolean isUnicodeUnescapeEnabled() {
+ // return PREFS.getBoolean(UNICODE_UNESCAPE_ENABLED);
+ // }
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PreferenceInitializer.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PreferenceInitializer.java
index e2ad589..1c1c8ec 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PreferenceInitializer.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PreferenceInitializer.java
@@ -17,10 +17,10 @@
/**
* Initializes default preferences.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
-public class PreferenceInitializer extends
- AbstractPreferenceInitializer {
+public class PreferenceInitializer extends AbstractPreferenceInitializer {
/**
* Constructor.
@@ -34,30 +34,33 @@
* #initializeDefaultPreferences()
*/
public void initializeDefaultPreferences() {
- Preferences prefs = MessagesEditorPlugin.getDefault().getPluginPreferences();
+ Preferences prefs = MessagesEditorPlugin.getDefault()
+ .getPluginPreferences();
- //General
+ // General
prefs.setDefault(MsgEditorPreferences.UNICODE_UNESCAPE_ENABLED, true);
prefs.setDefault(MsgEditorPreferences.FIELD_TAB_INSERTS, true);
prefs.setDefault(MsgEditorPreferences.KEY_TREE_HIERARCHICAL, true);
prefs.setDefault(MsgEditorPreferences.KEY_TREE_EXPANDED, true);
prefs.setDefault(MsgEditorPreferences.SUPPORT_FRAGMENTS, true);
prefs.setDefault(MsgEditorPreferences.NL_SUPPORT_ENABLED, true);
- prefs.setDefault(MsgEditorPreferences.LOADING_ONLY_FRAGMENT_RESOURCES, false);
+ prefs.setDefault(MsgEditorPreferences.LOADING_ONLY_FRAGMENT_RESOURCES,
+ false);
prefs.setDefault(MsgEditorPreferences.PROPERTIES_DISPLAYED_FILTER,
- IMessagesEditorChangeListener.SHOW_ALL);
-
- //Formatting
+ IMessagesEditorChangeListener.SHOW_ALL);
+
+ // Formatting
prefs.setDefault(MsgEditorPreferences.UNICODE_ESCAPE_ENABLED, true);
prefs.setDefault(MsgEditorPreferences.UNICODE_ESCAPE_UPPERCASE, true);
-
- prefs.setDefault(MsgEditorPreferences.SPACES_AROUND_EQUALS_ENABLED, true);
-
+
+ prefs.setDefault(MsgEditorPreferences.SPACES_AROUND_EQUALS_ENABLED,
+ true);
+
prefs.setDefault(MsgEditorPreferences.GROUP__LEVEL_SEPARATOR, "."); //$NON-NLS-1$
prefs.setDefault(MsgEditorPreferences.ALIGN_EQUALS_ENABLED, true);
prefs.setDefault(MsgEditorPreferences.SHOW_SUPPORT_ENABLED, true);
prefs.setDefault(MsgEditorPreferences.KEY_TREE_HIERARCHICAL, true);
-
+
prefs.setDefault(MsgEditorPreferences.GROUP_KEYS_ENABLED, true);
prefs.setDefault(MsgEditorPreferences.GROUP_LEVEL_DEEP, 1);
prefs.setDefault(MsgEditorPreferences.GROUP_SEP_BLANK_LINE_COUNT, 1);
@@ -66,34 +69,41 @@
prefs.setDefault(MsgEditorPreferences.WRAP_LINE_LENGTH, 80);
prefs.setDefault(MsgEditorPreferences.WRAP_INDENT_LENGTH, 8);
- prefs.setDefault(MsgEditorPreferences.NEW_LINE_STYLE,
+ prefs.setDefault(
+ MsgEditorPreferences.NEW_LINE_STYLE,
MsgEditorPreferences.getInstance().getSerializerConfig().NEW_LINE_UNIX);
prefs.setDefault(MsgEditorPreferences.KEEP_EMPTY_FIELDS, false);
prefs.setDefault(MsgEditorPreferences.SORT_KEYS, true);
-
+
// Reporting/Performance
prefs.setDefault(MsgEditorPreferences.REPORT_MISSING_VALUES_LEVEL,
- MsgEditorPreferences.VALIDATION_MESSAGE_ERROR);
+ MsgEditorPreferences.VALIDATION_MESSAGE_ERROR);
prefs.setDefault(MsgEditorPreferences.REPORT_DUPL_VALUES_LEVEL,
- MsgEditorPreferences.VALIDATION_MESSAGE_WARNING);
- prefs.setDefault(MsgEditorPreferences.REPORT_DUPL_VALUES_ONLY_IN_ROOT_LOCALE, true);
- prefs.setDefault(MsgEditorPreferences.REPORT_SIM_VALUES_WORD_COMPARE, true);
- prefs.setDefault(MsgEditorPreferences.REPORT_SIM_VALUES_PRECISION, 0.75d);
-
+ MsgEditorPreferences.VALIDATION_MESSAGE_WARNING);
+ prefs.setDefault(
+ MsgEditorPreferences.REPORT_DUPL_VALUES_ONLY_IN_ROOT_LOCALE,
+ true);
+ prefs.setDefault(MsgEditorPreferences.REPORT_SIM_VALUES_WORD_COMPARE,
+ true);
+ prefs.setDefault(MsgEditorPreferences.REPORT_SIM_VALUES_PRECISION,
+ 0.75d);
+
prefs.setDefault(MsgEditorPreferences.EDITOR_TREE_HIDDEN, false);
-
- //locales filter: by default: don't filter locales.
- prefs.setDefault(MsgEditorPreferences.FILTER_LOCALES_STRING_MATCHERS, "*"); //$NON-NLS-1$
+
+ // locales filter: by default: don't filter locales.
+ prefs.setDefault(MsgEditorPreferences.FILTER_LOCALES_STRING_MATCHERS,
+ "*"); //$NON-NLS-1$
prefs.addPropertyChangeListener(MsgEditorPreferences.getInstance());
-
- //setup the i18n validation nature and its associated builder
- //on all java projects when the plugin is started
- //an when the editor is opened.
- prefs.setDefault(MsgEditorPreferences.ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS, true); //$NON-NLS-1$
+
+ // setup the i18n validation nature and its associated builder
+ // on all java projects when the plugin is started
+ // an when the editor is opened.
+ prefs.setDefault(
+ MsgEditorPreferences.ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS,
+ true); //$NON-NLS-1$
prefs.addPropertyChangeListener(MsgEditorPreferences.getInstance());
-
-
+
}
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesDeserializerConfig.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesDeserializerConfig.java
index 56b8fc1..bbff98f 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesDeserializerConfig.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesDeserializerConfig.java
@@ -22,19 +22,21 @@
* @author Alexej Strelzow
*/
public class PropertiesDeserializerConfig implements
- IPropertiesDeserializerConfig { // Moved from MsgEditorPreferences, to make it more flexible.
+ IPropertiesDeserializerConfig { // Moved from MsgEditorPreferences, to
+ // make it more flexible.
/** MsgEditorPreferences. */
- private static final Preferences PREFS =
- MessagesEditorPlugin.getDefault().getPluginPreferences();
+ private static final Preferences PREFS = MessagesEditorPlugin.getDefault()
+ .getPluginPreferences();
PropertiesDeserializerConfig() {
- ConfigurationManager.getInstance().setDeserializerConfig(this);
+ ConfigurationManager.getInstance().setDeserializerConfig(this);
}
-
+
/**
* Gets whether to convert encoded strings to unicode characters when
* reading file.
+ *
* @return <code>true</code> if converting
*/
public boolean isUnicodeUnescapeEnabled() {
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesSerializerConfig.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesSerializerConfig.java
index fd3b339..c13e695 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesSerializerConfig.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesSerializerConfig.java
@@ -22,18 +22,19 @@
* @author Alexej Strelzow
*/
public class PropertiesSerializerConfig implements IPropertiesSerializerConfig {
- // Moved from MsgEditorPreferences, to make it more flexible.
+ // Moved from MsgEditorPreferences, to make it more flexible.
/** MsgEditorPreferences. */
- private static final Preferences PREFS =
- MessagesEditorPlugin.getDefault().getPluginPreferences();
-
+ private static final Preferences PREFS = MessagesEditorPlugin.getDefault()
+ .getPluginPreferences();
+
PropertiesSerializerConfig() {
- ConfigurationManager.getInstance().setSerializerConfig(this);
+ ConfigurationManager.getInstance().setSerializerConfig(this);
}
-
+
/**
* Gets whether to escape unicode characters when generating file.
+ *
* @return <code>true</code> if escaping
*/
public boolean isUnicodeEscapeEnabled() {
@@ -42,8 +43,8 @@
/**
* Gets the new line type to use when overwriting system (or Eclipse)
- * default new line type when generating file. Use constants to this
- * effect.
+ * default new line type when generating file. Use constants to this effect.
+ *
* @return new line type
*/
public int getNewLineStyle() {
@@ -52,6 +53,7 @@
/**
* Gets how many blank lines should separate groups when generating file.
+ *
* @return how many blank lines between groups
*/
public int getGroupSepBlankLineCount() {
@@ -60,6 +62,7 @@
/**
* Gets whether to print "Generated By..." comment when generating file.
+ *
* @return <code>true</code> if we print it
*/
public boolean isShowSupportEnabled() {
@@ -68,6 +71,7 @@
/**
* Gets whether keys should be grouped when generating file.
+ *
* @return <code>true</code> if keys should be grouped
*/
public boolean isGroupKeysEnabled() {
@@ -75,8 +79,9 @@
}
/**
- * Gets whether escaped unicode "alpha" characters should be uppercase
- * when generating file.
+ * Gets whether escaped unicode "alpha" characters should be uppercase when
+ * generating file.
+ *
* @return <code>true</code> if uppercase
*/
public boolean isUnicodeEscapeUppercase() {
@@ -86,6 +91,7 @@
/**
* Gets the number of character after which lines should be wrapped when
* generating file.
+ *
* @return number of characters
*/
public int getWrapLineLength() {
@@ -94,6 +100,7 @@
/**
* Gets whether lines should be wrapped if too big when generating file.
+ *
* @return <code>true</code> if wrapped
*/
public boolean isWrapLinesEnabled() {
@@ -103,6 +110,7 @@
/**
* Gets whether wrapped lines should be aligned with equal sign when
* generating file.
+ *
* @return <code>true</code> if aligned
*/
public boolean isWrapAlignEqualsEnabled() {
@@ -112,6 +120,7 @@
/**
* Gets the number of spaces to use for indentation of wrapped lines when
* generating file.
+ *
* @return number of spaces
*/
public int getWrapIndentLength() {
@@ -119,16 +128,19 @@
}
/**
- * Gets whether there should be spaces around equals signs when generating
+ * Gets whether there should be spaces around equals signs when generating
* file.
+ *
* @return <code>true</code> there if should be spaces around equals signs
*/
public boolean isSpacesAroundEqualsEnabled() {
- return PREFS.getBoolean(MsgEditorPreferences.SPACES_AROUND_EQUALS_ENABLED);
+ return PREFS
+ .getBoolean(MsgEditorPreferences.SPACES_AROUND_EQUALS_ENABLED);
}
/**
* Gets whether new lines are escaped or printed as is when generating file.
+ *
* @return <code>true</code> if printed as is.
*/
public boolean isNewLineNice() {
@@ -137,6 +149,7 @@
/**
* Gets how many level deep keys should be grouped when generating file.
+ *
* @return how many level deep
*/
public int getGroupLevelDepth() {
@@ -145,6 +158,7 @@
/**
* Gets key group separator.
+ *
* @return key group separator.
*/
public String getGroupLevelSeparator() {
@@ -153,6 +167,7 @@
/**
* Gets whether equals signs should be aligned when generating file.
+ *
* @return <code>true</code> if equals signs should be aligned
*/
public boolean isAlignEqualsEnabled() {
@@ -162,14 +177,17 @@
/**
* Gets whether equal signs should be aligned within each groups when
* generating file.
+ *
* @return <code>true</code> if equal signs should be aligned within groups
*/
public boolean isGroupAlignEqualsEnabled() {
- return PREFS.getBoolean(MsgEditorPreferences.GROUP_ALIGN_EQUALS_ENABLED);
+ return PREFS
+ .getBoolean(MsgEditorPreferences.GROUP_ALIGN_EQUALS_ENABLED);
}
/**
* Gets whether to sort keys upon serializing them.
+ *
* @return <code>true</code> if keys are to be sorted.
*/
public boolean isKeySortingEnabled() {
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/ReportingPrefPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/ReportingPrefPage.java
index 97a3973..28a1447 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/ReportingPrefPage.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/ReportingPrefPage.java
@@ -26,17 +26,18 @@
/**
* Plugin preference page for reporting/performance options.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public class ReportingPrefPage extends AbstractPrefPage {
-
+
/* Preference fields. */
private Combo reportMissingVals;
private Combo reportDuplVals;
private Combo reportSimVals;
private Text reportSimPrecision;
private Button[] reportSimValsMode = new Button[2];
-
+
/**
* Constructor.
*/
@@ -45,120 +46,123 @@
}
/**
- * @see org.eclipse.jface.preference.PreferencePage#createContents(
- * org.eclipse.swt.widgets.Composite)
+ * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
*/
protected Control createContents(Composite parent) {
IPreferenceStore prefs = getPreferenceStore();
Composite field = null;
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
-
- new Label(composite, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.perform.intro1")); //$NON-NLS-1$
- new Label(composite, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.perform.intro2")); //$NON-NLS-1$
+
+ new Label(composite, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.perform.intro1")); //$NON-NLS-1$
+ new Label(composite, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.perform.intro2")); //$NON-NLS-1$
new Label(composite, SWT.NONE).setText(" "); //$NON-NLS-1$
-
+
// Report missing values?
field = createFieldComposite(composite);
- GridData gridData = new GridData();
- gridData.grabExcessHorizontalSpace = true;
- field.setLayoutData(gridData);
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.perform.missingVals")); //$NON-NLS-1$
+ GridData gridData = new GridData();
+ gridData.grabExcessHorizontalSpace = true;
+ field.setLayoutData(gridData);
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.perform.missingVals")); //$NON-NLS-1$
reportMissingVals = new Combo(field, SWT.READ_ONLY);
populateCombo(reportMissingVals,
- prefs.getInt(MsgEditorPreferences.REPORT_MISSING_VALUES_LEVEL));
-// reportMissingVals.setSelection(
-// prefs.getBoolean(MsgEditorPreferences.REPORT_MISSING_VALUES));
+ prefs.getInt(MsgEditorPreferences.REPORT_MISSING_VALUES_LEVEL));
+ // reportMissingVals.setSelection(
+ // prefs.getBoolean(MsgEditorPreferences.REPORT_MISSING_VALUES));
// Report duplicate values?
field = createFieldComposite(composite);
- gridData = new GridData();
- gridData.grabExcessHorizontalSpace = true;
- field.setLayoutData(gridData);
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.perform.duplVals")); //$NON-NLS-1$
+ gridData = new GridData();
+ gridData.grabExcessHorizontalSpace = true;
+ field.setLayoutData(gridData);
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.perform.duplVals")); //$NON-NLS-1$
reportDuplVals = new Combo(field, SWT.READ_ONLY);
populateCombo(reportDuplVals,
- prefs.getInt(MsgEditorPreferences.REPORT_DUPL_VALUES_LEVEL));
-
+ prefs.getInt(MsgEditorPreferences.REPORT_DUPL_VALUES_LEVEL));
+
// Report similar values?
field = createFieldComposite(composite);
- gridData = new GridData();
- gridData.grabExcessHorizontalSpace = true;
- field.setLayoutData(gridData);
+ gridData = new GridData();
+ gridData.grabExcessHorizontalSpace = true;
+ field.setLayoutData(gridData);
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.perform.simVals")); //$NON-NLS-1$
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.perform.simVals")); //$NON-NLS-1$
reportSimVals = new Combo(field, SWT.READ_ONLY);
populateCombo(reportSimVals,
- prefs.getInt(MsgEditorPreferences.REPORT_SIM_VALUES_LEVEL));
+ prefs.getInt(MsgEditorPreferences.REPORT_SIM_VALUES_LEVEL));
reportSimVals.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
refreshEnabledStatuses();
}
});
-
+
Composite simValModeGroup = new Composite(composite, SWT.NONE);
GridLayout gridLayout = new GridLayout(2, false);
gridLayout.marginWidth = indentPixels;
gridLayout.marginHeight = 0;
gridLayout.verticalSpacing = 0;
simValModeGroup.setLayout(gridLayout);
-
+
// Report similar values: word count
reportSimValsMode[0] = new Button(simValModeGroup, SWT.RADIO);
- reportSimValsMode[0].setSelection(prefs.getBoolean(
- MsgEditorPreferences.REPORT_SIM_VALUES_WORD_COMPARE));
- new Label(simValModeGroup, SWT.NONE).setText(MessagesEditorPlugin.getString(
- "prefs.perform.simVals.wordCount")); //$NON-NLS-1$
-
+ reportSimValsMode[0]
+ .setSelection(prefs
+ .getBoolean(MsgEditorPreferences.REPORT_SIM_VALUES_WORD_COMPARE));
+ new Label(simValModeGroup, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.perform.simVals.wordCount")); //$NON-NLS-1$
+
// Report similar values: Levensthein
reportSimValsMode[1] = new Button(simValModeGroup, SWT.RADIO);
- reportSimValsMode[1].setSelection(prefs.getBoolean(
- MsgEditorPreferences.REPORT_SIM_VALUES_LEVENSTHEIN));
- new Label(simValModeGroup, SWT.NONE).setText(MessagesEditorPlugin.getString(
- "prefs.perform.simVals.levensthein")); //$NON-NLS-1$
-
+ reportSimValsMode[1]
+ .setSelection(prefs
+ .getBoolean(MsgEditorPreferences.REPORT_SIM_VALUES_LEVENSTHEIN));
+ new Label(simValModeGroup, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.perform.simVals.levensthein")); //$NON-NLS-1$
+
// Report similar values: precision level
field = createFieldComposite(composite, indentPixels);
- new Label(field, SWT.NONE).setText(MessagesEditorPlugin.getString(
- "prefs.perform.simVals.precision")); //$NON-NLS-1$
+ new Label(field, SWT.NONE).setText(MessagesEditorPlugin
+ .getString("prefs.perform.simVals.precision")); //$NON-NLS-1$
reportSimPrecision = new Text(field, SWT.BORDER);
- reportSimPrecision.setText(
- prefs.getString(MsgEditorPreferences.REPORT_SIM_VALUES_PRECISION));
+ reportSimPrecision.setText(prefs
+ .getString(MsgEditorPreferences.REPORT_SIM_VALUES_PRECISION));
reportSimPrecision.setTextLimit(6);
setWidthInChars(reportSimPrecision, 6);
reportSimPrecision.addKeyListener(new DoubleTextValidatorKeyListener(
- MessagesEditorPlugin.getString(
- "prefs.perform.simVals.precision.error"), //$NON-NLS-1$
+ MessagesEditorPlugin
+ .getString("prefs.perform.simVals.precision.error"), //$NON-NLS-1$
0, 1));
-
+
refreshEnabledStatuses();
-
+
return composite;
}
/**
* Creates the items in the combo and select the item that matches the
* current value.
+ *
* @param combo
* @param selectedLevel
*/
private void populateCombo(Combo combo, int selectedLevel) {
- combo.add(MessagesEditorPlugin.getString("prefs.perform.message.ignore"));
- combo.add(MessagesEditorPlugin.getString("prefs.perform.message.info"));
- combo.add(MessagesEditorPlugin.getString("prefs.perform.message.warning"));
- combo.add(MessagesEditorPlugin.getString("prefs.perform.message.error"));
- combo.select(selectedLevel);
- GridData gridData = new GridData();
- gridData.grabExcessHorizontalSpace = true;
- gridData.horizontalAlignment = SWT.RIGHT;
- combo.setLayoutData(gridData);
+ combo.add(MessagesEditorPlugin
+ .getString("prefs.perform.message.ignore"));
+ combo.add(MessagesEditorPlugin.getString("prefs.perform.message.info"));
+ combo.add(MessagesEditorPlugin
+ .getString("prefs.perform.message.warning"));
+ combo.add(MessagesEditorPlugin.getString("prefs.perform.message.error"));
+ combo.select(selectedLevel);
+ GridData gridData = new GridData();
+ gridData.grabExcessHorizontalSpace = true;
+ gridData.horizontalAlignment = SWT.RIGHT;
+ combo.setLayoutData(gridData);
}
-
/**
* @see org.eclipse.jface.preference.IPreferencePage#performOk()
@@ -180,37 +184,39 @@
refreshEnabledStatuses();
return super.performOk();
}
-
-
+
/**
* @see org.eclipse.jface.preference.PreferencePage#performDefaults()
*/
protected void performDefaults() {
IPreferenceStore prefs = getPreferenceStore();
- reportMissingVals.select(prefs.getDefaultInt(
- MsgEditorPreferences.REPORT_MISSING_VALUES_LEVEL));
- reportDuplVals.select(prefs.getDefaultInt(
- MsgEditorPreferences.REPORT_DUPL_VALUES_LEVEL));
- reportSimVals.select(prefs.getDefaultInt(
- MsgEditorPreferences.REPORT_SIM_VALUES_LEVEL));
- reportSimValsMode[0].setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.REPORT_SIM_VALUES_WORD_COMPARE));
- reportSimValsMode[1].setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.REPORT_SIM_VALUES_LEVENSTHEIN));
- reportSimPrecision.setText(Double.toString(prefs.getDefaultDouble(
- MsgEditorPreferences.REPORT_SIM_VALUES_PRECISION)));
+ reportMissingVals
+ .select(prefs
+ .getDefaultInt(MsgEditorPreferences.REPORT_MISSING_VALUES_LEVEL));
+ reportDuplVals.select(prefs
+ .getDefaultInt(MsgEditorPreferences.REPORT_DUPL_VALUES_LEVEL));
+ reportSimVals.select(prefs
+ .getDefaultInt(MsgEditorPreferences.REPORT_SIM_VALUES_LEVEL));
+ reportSimValsMode[0]
+ .setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.REPORT_SIM_VALUES_WORD_COMPARE));
+ reportSimValsMode[1]
+ .setSelection(prefs
+ .getDefaultBoolean(MsgEditorPreferences.REPORT_SIM_VALUES_LEVENSTHEIN));
+ reportSimPrecision
+ .setText(Double.toString(prefs
+ .getDefaultDouble(MsgEditorPreferences.REPORT_SIM_VALUES_PRECISION)));
refreshEnabledStatuses();
super.performDefaults();
}
- /*default*/ void refreshEnabledStatuses() {
- boolean isReportingSimilar = reportSimVals.getSelectionIndex()
- != MsgEditorPreferences.VALIDATION_MESSAGE_IGNORE;
+ /* default */void refreshEnabledStatuses() {
+ boolean isReportingSimilar = reportSimVals.getSelectionIndex() != MsgEditorPreferences.VALIDATION_MESSAGE_IGNORE;
for (int i = 0; i < reportSimValsMode.length; i++) {
reportSimValsMode[i].setEnabled(isReportingSimilar);
}
reportSimPrecision.setEnabled(isReportingSimilar);
}
-
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyArguments.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyArguments.java
index f22ce92..ba64796 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyArguments.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyArguments.java
@@ -19,63 +19,64 @@
*/
public class RenameKeyArguments extends RefactoringArguments {
- private String fNewName;
+ private String fNewName;
- private boolean fRenameChildKeys;
+ private boolean fRenameChildKeys;
- private boolean fUpdateReferences;
+ private boolean fUpdateReferences;
- /**
- * Creates new rename arguments.
- *
- * @param newName
- * the new name of the element to be renamed
- * @param renameChildKeys
- * <code>true</code> if child keys are to be renamed;
- * <code>false</code> otherwise
- * @param updateReferences
- * <code>true</code> if reference updating is requested;
- * <code>false</code> otherwise
- */
- public RenameKeyArguments(String newName, boolean renameChildKeys, boolean updateReferences) {
- Assert.isNotNull(newName);
- fNewName= newName;
- fRenameChildKeys = renameChildKeys;
- fUpdateReferences= updateReferences;
- }
+ /**
+ * Creates new rename arguments.
+ *
+ * @param newName
+ * the new name of the element to be renamed
+ * @param renameChildKeys
+ * <code>true</code> if child keys are to be renamed;
+ * <code>false</code> otherwise
+ * @param updateReferences
+ * <code>true</code> if reference updating is requested;
+ * <code>false</code> otherwise
+ */
+ public RenameKeyArguments(String newName, boolean renameChildKeys,
+ boolean updateReferences) {
+ Assert.isNotNull(newName);
+ fNewName = newName;
+ fRenameChildKeys = renameChildKeys;
+ fUpdateReferences = updateReferences;
+ }
- /**
- * Returns the new element name.
- *
- * @return the new element name
- */
- public String getNewName() {
- return fNewName;
- }
+ /**
+ * Returns the new element name.
+ *
+ * @return the new element name
+ */
+ public String getNewName() {
+ return fNewName;
+ }
- /**
- * Returns whether child keys are to be renamed or not.
- *
- * @return returns <code>true</code> if child keys are to be renamed;
- * <code>false</code> otherwise
- */
- public boolean getRenameChildKeys() {
- return fRenameChildKeys;
- }
+ /**
+ * Returns whether child keys are to be renamed or not.
+ *
+ * @return returns <code>true</code> if child keys are to be renamed;
+ * <code>false</code> otherwise
+ */
+ public boolean getRenameChildKeys() {
+ return fRenameChildKeys;
+ }
- /**
- * Returns whether reference updating is requested or not.
- *
- * @return returns <code>true</code> if reference updating is requested;
- * <code>false</code> otherwise
- */
- public boolean getUpdateReferences() {
- return fUpdateReferences;
- }
+ /**
+ * Returns whether reference updating is requested or not.
+ *
+ * @return returns <code>true</code> if reference updating is requested;
+ * <code>false</code> otherwise
+ */
+ public boolean getUpdateReferences() {
+ return fUpdateReferences;
+ }
- public String toString() {
- return "rename to " + fNewName //$NON-NLS-1$
- + (fRenameChildKeys ? " (rename child keys)" : " (don't rename child keys)") //$NON-NLS-1$//$NON-NLS-2$
- + (fUpdateReferences ? " (update references)" : " (don't update references)"); //$NON-NLS-1$//$NON-NLS-2$
- }
+ public String toString() {
+ return "rename to " + fNewName //$NON-NLS-1$
+ + (fRenameChildKeys ? " (rename child keys)" : " (don't rename child keys)") //$NON-NLS-1$//$NON-NLS-2$
+ + (fUpdateReferences ? " (update references)" : " (don't update references)"); //$NON-NLS-1$//$NON-NLS-2$
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyChange.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyChange.java
index e017dad..f30272e 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyChange.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyChange.java
@@ -27,132 +27,157 @@
*/
public class RenameKeyChange extends Change {
- private final MessagesBundleGroup fMessagesBundleGroup;
+ private final MessagesBundleGroup fMessagesBundleGroup;
- private final String fNewName;
+ private final String fNewName;
- private final boolean fRenameChildKeys;
+ private final boolean fRenameChildKeys;
- private final KeyTreeNode fKeyTreeNode;
+ private final KeyTreeNode fKeyTreeNode;
- private ChangeDescriptor fDescriptor;
+ private ChangeDescriptor fDescriptor;
- /**
- * Creates the change.
- *
- * @param keyTreeNode the node in the model to rename
- * @param newName the new name. Must not be empty
- * @param renameChildKeys true if child keys are also to be renamed, false if just this one key is to be renamed
- */
- protected RenameKeyChange(MessagesBundleGroup messageBundleGroup, KeyTreeNode keyTreeNode, String newName, boolean renameChildKeys) {
- if (keyTreeNode == null || newName == null || newName.length() == 0) {
- throw new IllegalArgumentException();
- }
+ /**
+ * Creates the change.
+ *
+ * @param keyTreeNode
+ * the node in the model to rename
+ * @param newName
+ * the new name. Must not be empty
+ * @param renameChildKeys
+ * true if child keys are also to be renamed, false if just this
+ * one key is to be renamed
+ */
+ protected RenameKeyChange(MessagesBundleGroup messageBundleGroup,
+ KeyTreeNode keyTreeNode, String newName, boolean renameChildKeys) {
+ if (keyTreeNode == null || newName == null || newName.length() == 0) {
+ throw new IllegalArgumentException();
+ }
- fMessagesBundleGroup = messageBundleGroup;
- fKeyTreeNode= keyTreeNode;
- fNewName= newName;
- fRenameChildKeys = renameChildKeys;
- fDescriptor= null;
- }
+ fMessagesBundleGroup = messageBundleGroup;
+ fKeyTreeNode = keyTreeNode;
+ fNewName = newName;
+ fRenameChildKeys = renameChildKeys;
+ fDescriptor = null;
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.Change#getDescriptor()
- */
- public ChangeDescriptor getDescriptor() {
- return fDescriptor;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ltk.core.refactoring.Change#getDescriptor()
+ */
+ public ChangeDescriptor getDescriptor() {
+ return fDescriptor;
+ }
- /**
- * Sets the change descriptor to be returned by {@link Change#getDescriptor()}.
- *
- * @param descriptor the change descriptor
- */
- public void setDescriptor(ChangeDescriptor descriptor) {
- fDescriptor= descriptor;
- }
+ /**
+ * Sets the change descriptor to be returned by
+ * {@link Change#getDescriptor()}.
+ *
+ * @param descriptor
+ * the change descriptor
+ */
+ public void setDescriptor(ChangeDescriptor descriptor) {
+ fDescriptor = descriptor;
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.Change#getName()
- */
- public String getName() {
- return MessageFormat.format("Rename {0} to {1}", new Object [] { fKeyTreeNode.getMessageKey(), fNewName});
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ltk.core.refactoring.Change#getName()
+ */
+ public String getName() {
+ return MessageFormat.format("Rename {0} to {1}", new Object[] {
+ fKeyTreeNode.getMessageKey(), fNewName });
+ }
- /**
- * Returns the new name.
- *
- * @return return the new name
- */
- public String getNewName() {
- return fNewName;
- }
+ /**
+ * Returns the new name.
+ *
+ * @return return the new name
+ */
+ public String getNewName() {
+ return fNewName;
+ }
- /**
- * This implementation of {@link Change#isValid(IProgressMonitor)} tests the modified resource using the validation method
- * specified by {@link #setValidationMethod(int)}.
- */
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException, OperationCanceledException {
- pm.beginTask("", 2); //$NON-NLS-1$
- try {
- RefactoringStatus result = new RefactoringStatus();
- return result;
- } finally {
- pm.done();
- }
- }
+ /**
+ * This implementation of {@link Change#isValid(IProgressMonitor)} tests the
+ * modified resource using the validation method specified by
+ * {@link #setValidationMethod(int)}.
+ */
+ public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException,
+ OperationCanceledException {
+ pm.beginTask("", 2); //$NON-NLS-1$
+ try {
+ RefactoringStatus result = new RefactoringStatus();
+ return result;
+ } finally {
+ pm.done();
+ }
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.Change#initializeValidationData(org.eclipse.core.runtime.IProgressMonitor)
- */
- public void initializeValidationData(IProgressMonitor pm) {
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ltk.core.refactoring.Change#initializeValidationData(org.
+ * eclipse.core.runtime.IProgressMonitor)
+ */
+ public void initializeValidationData(IProgressMonitor pm) {
+ }
- public Object getModifiedElement() {
- return "what is this for?";
- }
+ public Object getModifiedElement() {
+ return "what is this for?";
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.Change#perform(org.eclipse.core.runtime.IProgressMonitor)
- */
- public Change perform(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask("Rename resource bundle key", 1);
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ltk.core.refactoring.Change#perform(org.eclipse.core.runtime
+ * .IProgressMonitor)
+ */
+ public Change perform(IProgressMonitor pm) throws CoreException {
+ try {
+ pm.beginTask("Rename resource bundle key", 1);
- // Find the root - we will need this later
- KeyTreeNode root = (KeyTreeNode) fKeyTreeNode.getParent();
- while (root.getName() != null) {
- root = (KeyTreeNode) root.getParent();
- }
-
- if (fRenameChildKeys) {
- String key = fKeyTreeNode.getMessageKey();
- String keyPrefix = fKeyTreeNode.getMessageKey() + ".";
- Collection<KeyTreeNode> branchNodes = fKeyTreeNode.getBranch();
- for (KeyTreeNode branchNode : branchNodes) {
- String oldKey = branchNode.getMessageKey();
- if (oldKey.equals(key) || oldKey.startsWith(keyPrefix)) {
- String newKey = fNewName + oldKey.substring(key.length());
- fMessagesBundleGroup.renameMessageKeys(oldKey, newKey);
- }
- }
- } else {
- fMessagesBundleGroup.renameMessageKeys(fKeyTreeNode.getMessageKey(), fNewName);
- }
-
- String oldName= fKeyTreeNode.getMessageKey();
-
- // Find the node that was created with the new name
- String segments [] = fNewName.split("\\.");
- KeyTreeNode renamedKey = root;
- for (String segment : segments) {
- renamedKey = (KeyTreeNode) renamedKey.getChild(segment);
- }
-
- assert(renamedKey != null);
- return new RenameKeyChange(fMessagesBundleGroup, renamedKey, oldName, fRenameChildKeys);
- } finally {
- pm.done();
- }
- }
+ // Find the root - we will need this later
+ KeyTreeNode root = (KeyTreeNode) fKeyTreeNode.getParent();
+ while (root.getName() != null) {
+ root = (KeyTreeNode) root.getParent();
+ }
+
+ if (fRenameChildKeys) {
+ String key = fKeyTreeNode.getMessageKey();
+ String keyPrefix = fKeyTreeNode.getMessageKey() + ".";
+ Collection<KeyTreeNode> branchNodes = fKeyTreeNode.getBranch();
+ for (KeyTreeNode branchNode : branchNodes) {
+ String oldKey = branchNode.getMessageKey();
+ if (oldKey.equals(key) || oldKey.startsWith(keyPrefix)) {
+ String newKey = fNewName
+ + oldKey.substring(key.length());
+ fMessagesBundleGroup.renameMessageKeys(oldKey, newKey);
+ }
+ }
+ } else {
+ fMessagesBundleGroup.renameMessageKeys(
+ fKeyTreeNode.getMessageKey(), fNewName);
+ }
+
+ String oldName = fKeyTreeNode.getMessageKey();
+
+ // Find the node that was created with the new name
+ String segments[] = fNewName.split("\\.");
+ KeyTreeNode renamedKey = root;
+ for (String segment : segments) {
+ renamedKey = (KeyTreeNode) renamedKey.getChild(segment);
+ }
+
+ assert (renamedKey != null);
+ return new RenameKeyChange(fMessagesBundleGroup, renamedKey,
+ oldName, fRenameChildKeys);
+ } finally {
+ pm.done();
+ }
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyDescriptor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyDescriptor.java
index dad86fa..168b618 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyDescriptor.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyDescriptor.java
@@ -32,109 +32,119 @@
*/
public final class RenameKeyDescriptor extends RefactoringDescriptor {
- public static final String ID = "org.eclipse.babel.editor.refactoring.renameKey"; //$NON-NLS-1$
+ public static final String ID = "org.eclipse.babel.editor.refactoring.renameKey"; //$NON-NLS-1$
- /** The name attribute */
- private String fNewName;
+ /** The name attribute */
+ private String fNewName;
- private KeyTreeNode fKeyNode;
-
- private MessagesBundleGroup fMessagesBundleGroup;
-
- /** Configures if references will be updated */
- private boolean fRenameChildKeys;
+ private KeyTreeNode fKeyNode;
- /**
- * Creates a new refactoring descriptor.
- * <p>
- * Clients should not instantiated this class but use {@link RefactoringCore#getRefactoringContribution(String)}
- * with {@link #ID} to get the contribution that can create the descriptor.
- * </p>
- */
- public RenameKeyDescriptor() {
- super(ID, null, "N/A", null, RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE);
- fNewName = null;
- }
+ private MessagesBundleGroup fMessagesBundleGroup;
- /**
- * Sets the new name to rename the resource to.
- *
- * @param name
- * the non-empty new name to set
- */
- public void setNewName(final String name) {
- Assert.isNotNull(name);
- Assert.isLegal(!"".equals(name), "Name must not be empty"); //$NON-NLS-1$//$NON-NLS-2$
- fNewName = name;
- }
+ /** Configures if references will be updated */
+ private boolean fRenameChildKeys;
- /**
- * Returns the new name to rename the resource to.
- *
- * @return
- * the new name to rename the resource to
- */
- public String getNewName() {
- return fNewName;
- }
+ /**
+ * Creates a new refactoring descriptor.
+ * <p>
+ * Clients should not instantiated this class but use
+ * {@link RefactoringCore#getRefactoringContribution(String)} with
+ * {@link #ID} to get the contribution that can create the descriptor.
+ * </p>
+ */
+ public RenameKeyDescriptor() {
+ super(ID, null, "N/A", null, RefactoringDescriptor.STRUCTURAL_CHANGE
+ | RefactoringDescriptor.MULTI_CHANGE);
+ fNewName = null;
+ }
- /**
- * Sets the project name of this refactoring.
- * <p>
- * Note: If the resource to be renamed is of type {@link IResource#PROJECT},
- * clients are required to to set the project name to <code>null</code>.
- * </p>
- * <p>
- * The default is to associate the refactoring with the workspace.
- * </p>
- *
- * @param project
- * the non-empty project name to set, or <code>null</code> for
- * the workspace
- *
- * @see #getProject()
- */
-// public void setProject(final String project) {
-// super.setProject(project);
-// }
+ /**
+ * Sets the new name to rename the resource to.
+ *
+ * @param name
+ * the non-empty new name to set
+ */
+ public void setNewName(final String name) {
+ Assert.isNotNull(name);
+ Assert.isLegal(!"".equals(name), "Name must not be empty"); //$NON-NLS-1$//$NON-NLS-2$
+ fNewName = name;
+ }
- /**
- * If set to <code>true</code>, this rename will also rename child keys. The default is to rename child keys.
- *
- * @param renameChildKeys <code>true</code> if this rename will rename child keys
- */
- public void setRenameChildKeys(boolean renameChildKeys) {
- fRenameChildKeys = renameChildKeys;
- }
+ /**
+ * Returns the new name to rename the resource to.
+ *
+ * @return the new name to rename the resource to
+ */
+ public String getNewName() {
+ return fNewName;
+ }
- public void setRenameChildKeys(KeyTreeNode keyNode, MessagesBundleGroup messagesBundleGroup) {
- this.fKeyNode = keyNode;
- this.fMessagesBundleGroup = messagesBundleGroup;
- }
+ /**
+ * Sets the project name of this refactoring.
+ * <p>
+ * Note: If the resource to be renamed is of type {@link IResource#PROJECT},
+ * clients are required to to set the project name to <code>null</code>.
+ * </p>
+ * <p>
+ * The default is to associate the refactoring with the workspace.
+ * </p>
+ *
+ * @param project
+ * the non-empty project name to set, or <code>null</code> for
+ * the workspace
+ *
+ * @see #getProject()
+ */
+ // public void setProject(final String project) {
+ // super.setProject(project);
+ // }
- /**
- * Returns if this rename will also rename child keys
- *
- * @return returns <code>true</code> if this rename will rename child keys
- */
- public boolean isRenameChildKeys() {
- return fRenameChildKeys;
- }
+ /**
+ * If set to <code>true</code>, this rename will also rename child keys. The
+ * default is to rename child keys.
+ *
+ * @param renameChildKeys
+ * <code>true</code> if this rename will rename child keys
+ */
+ public void setRenameChildKeys(boolean renameChildKeys) {
+ fRenameChildKeys = renameChildKeys;
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.RefactoringDescriptor#createRefactoring(org.eclipse.ltk.core.refactoring.RefactoringStatus)
- */
- public Refactoring createRefactoring(RefactoringStatus status) throws CoreException {
+ public void setRenameChildKeys(KeyTreeNode keyNode,
+ MessagesBundleGroup messagesBundleGroup) {
+ this.fKeyNode = keyNode;
+ this.fMessagesBundleGroup = messagesBundleGroup;
+ }
- String newName= getNewName();
- if (newName == null || newName.length() == 0) {
- status.addFatalError("The rename resource bundle key refactoring can not be performed as the new name is invalid");
- return null;
- }
- RenameKeyProcessor processor = new RenameKeyProcessor(fKeyNode, fMessagesBundleGroup);
- processor.setNewResourceName(newName);
- processor.setRenameChildKeys(fRenameChildKeys);
+ /**
+ * Returns if this rename will also rename child keys
+ *
+ * @return returns <code>true</code> if this rename will rename child keys
+ */
+ public boolean isRenameChildKeys() {
+ return fRenameChildKeys;
+ }
- return new RenameRefactoring(processor);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ltk.core.refactoring.RefactoringDescriptor#createRefactoring
+ * (org.eclipse.ltk.core.refactoring.RefactoringStatus)
+ */
+ public Refactoring createRefactoring(RefactoringStatus status)
+ throws CoreException {
+
+ String newName = getNewName();
+ if (newName == null || newName.length() == 0) {
+ status.addFatalError("The rename resource bundle key refactoring can not be performed as the new name is invalid");
+ return null;
+ }
+ RenameKeyProcessor processor = new RenameKeyProcessor(fKeyNode,
+ fMessagesBundleGroup);
+ processor.setNewResourceName(newName);
+ processor.setRenameChildKeys(fRenameChildKeys);
+
+ return new RenameRefactoring(processor);
+ }
}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyProcessor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyProcessor.java
index 0151d5c..d477287 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyProcessor.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyProcessor.java
@@ -31,221 +31,281 @@
import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
/**
- * A rename processor for {@link IResource}. The processor will rename the resource and
- * load rename participants if references should be renamed as well.
- *
+ * A rename processor for {@link IResource}. The processor will rename the
+ * resource and load rename participants if references should be renamed as
+ * well.
+ *
* @since 3.4
*/
public class RenameKeyProcessor extends RenameProcessor {
- private KeyTreeNode fKeyNode;
+ private KeyTreeNode fKeyNode;
- private MessagesBundleGroup fMessageBundleGroup;
+ private MessagesBundleGroup fMessageBundleGroup;
- private String fNewResourceName;
+ private String fNewResourceName;
- private boolean fRenameChildKeys;
+ private boolean fRenameChildKeys;
- private RenameKeyArguments fRenameArguments; // set after checkFinalConditions
+ private RenameKeyArguments fRenameArguments; // set after
+ // checkFinalConditions
- /**
- * Creates a new rename resource processor.
- *
- * @param keyNode the resource to rename.
- * @param messagesBundleGroup
- */
- public RenameKeyProcessor(KeyTreeNode keyNode, MessagesBundleGroup messagesBundleGroup) {
- if (keyNode == null) {
- throw new IllegalArgumentException("key node must not be null"); //$NON-NLS-1$
- }
+ /**
+ * Creates a new rename resource processor.
+ *
+ * @param keyNode
+ * the resource to rename.
+ * @param messagesBundleGroup
+ */
+ public RenameKeyProcessor(KeyTreeNode keyNode,
+ MessagesBundleGroup messagesBundleGroup) {
+ if (keyNode == null) {
+ throw new IllegalArgumentException("key node must not be null"); //$NON-NLS-1$
+ }
- fKeyNode = keyNode;
- fMessageBundleGroup = messagesBundleGroup;
- fRenameArguments= null;
- fRenameChildKeys= true;
- setNewResourceName(keyNode.getMessageKey()); // Initialize new name
- }
+ fKeyNode = keyNode;
+ fMessageBundleGroup = messagesBundleGroup;
+ fRenameArguments = null;
+ fRenameChildKeys = true;
+ setNewResourceName(keyNode.getMessageKey()); // Initialize new name
+ }
- /**
- * Returns the new key node
- *
- * @return the new key node
- */
- public KeyTreeNode getNewKeyTreeNode() {
- return fKeyNode;
- }
+ /**
+ * Returns the new key node
+ *
+ * @return the new key node
+ */
+ public KeyTreeNode getNewKeyTreeNode() {
+ return fKeyNode;
+ }
- /**
- * Returns the new resource name
- *
- * @return the new resource name
- */
- public String getNewResourceName() {
- return fNewResourceName;
- }
+ /**
+ * Returns the new resource name
+ *
+ * @return the new resource name
+ */
+ public String getNewResourceName() {
+ return fNewResourceName;
+ }
- /**
- * Sets the new resource name
- *
- * @param newName the new resource name
- */
- public void setNewResourceName(String newName) {
- Assert.isNotNull(newName);
- fNewResourceName= newName;
- }
+ /**
+ * Sets the new resource name
+ *
+ * @param newName
+ * the new resource name
+ */
+ public void setNewResourceName(String newName) {
+ Assert.isNotNull(newName);
+ fNewResourceName = newName;
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#checkInitialConditions(org.eclipse.core.runtime.IProgressMonitor)
- */
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- /*
- * This method allows fatal and non-fatal problems to be shown to
- * the user. Currently there are none so we return null to indicate
- * this.
- */
- return null;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#
+ * checkInitialConditions(org.eclipse.core.runtime.IProgressMonitor)
+ */
+ public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
+ throws CoreException {
+ /*
+ * This method allows fatal and non-fatal problems to be shown to the
+ * user. Currently there are none so we return null to indicate this.
+ */
+ return null;
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#checkFinalConditions(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext)
- */
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
- pm.beginTask("", 1); //$NON-NLS-1$
- try {
- fRenameArguments = new RenameKeyArguments(getNewResourceName(), fRenameChildKeys, false);
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#
+ * checkFinalConditions(org.eclipse.core.runtime.IProgressMonitor,
+ * org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext)
+ */
+ public RefactoringStatus checkFinalConditions(IProgressMonitor pm,
+ CheckConditionsContext context) throws CoreException {
+ pm.beginTask("", 1); //$NON-NLS-1$
+ try {
+ fRenameArguments = new RenameKeyArguments(getNewResourceName(),
+ fRenameChildKeys, false);
- ResourceChangeChecker checker = (ResourceChangeChecker) context.getChecker(ResourceChangeChecker.class);
- IResourceChangeDescriptionFactory deltaFactory = checker.getDeltaFactory();
+ ResourceChangeChecker checker = (ResourceChangeChecker) context
+ .getChecker(ResourceChangeChecker.class);
+ IResourceChangeDescriptionFactory deltaFactory = checker
+ .getDeltaFactory();
- // TODO figure out what we want to do here....
-// ResourceModifications.buildMoveDelta(deltaFactory, fKeyNode, fRenameArguments);
+ // TODO figure out what we want to do here....
+ // ResourceModifications.buildMoveDelta(deltaFactory, fKeyNode,
+ // fRenameArguments);
- return new RefactoringStatus();
- } finally {
- pm.done();
- }
- }
+ return new RefactoringStatus();
+ } finally {
+ pm.done();
+ }
+ }
- /**
- * Validates if the a name is valid. This method does not change the name settings on the refactoring. It is intended to be used
- * in a wizard to validate user input.
- *
- * @param newName the name to validate
- * @return returns the resulting status of the validation
- */
- public RefactoringStatus validateNewElementName(String newName) {
- Assert.isNotNull(newName);
+ /**
+ * Validates if the a name is valid. This method does not change the name
+ * settings on the refactoring. It is intended to be used in a wizard to
+ * validate user input.
+ *
+ * @param newName
+ * the name to validate
+ * @return returns the resulting status of the validation
+ */
+ public RefactoringStatus validateNewElementName(String newName) {
+ Assert.isNotNull(newName);
- if (newName.length() == 0) {
- return RefactoringStatus.createFatalErrorStatus("New name for key must be entered");
- }
- if (newName.startsWith(".")) {
- return RefactoringStatus.createFatalErrorStatus("Key cannot start with a '.'");
- }
- if (newName.endsWith(".")) {
- return RefactoringStatus.createFatalErrorStatus("Key cannot end with a '.'");
- }
-
- String [] parts = newName.split("\\.");
- for (String part : parts) {
- if (part.length() == 0) {
- return RefactoringStatus.createFatalErrorStatus("Key cannot contain an empty part between two periods");
- }
- if (!part.matches("([A-Z]|[a-z]|[0-9])*")) {
- return RefactoringStatus.createFatalErrorStatus("Key can contain only letters, digits, and periods");
- }
- }
-
- if (fMessageBundleGroup.isMessageKey(newName)) {
- return RefactoringStatus.createFatalErrorStatus(MessagesEditorPlugin.getString("dialog.error.exists"));
- }
+ if (newName.length() == 0) {
+ return RefactoringStatus
+ .createFatalErrorStatus("New name for key must be entered");
+ }
+ if (newName.startsWith(".")) {
+ return RefactoringStatus
+ .createFatalErrorStatus("Key cannot start with a '.'");
+ }
+ if (newName.endsWith(".")) {
+ return RefactoringStatus
+ .createFatalErrorStatus("Key cannot end with a '.'");
+ }
- return new RefactoringStatus();
- }
+ String[] parts = newName.split("\\.");
+ for (String part : parts) {
+ if (part.length() == 0) {
+ return RefactoringStatus
+ .createFatalErrorStatus("Key cannot contain an empty part between two periods");
+ }
+ if (!part.matches("([A-Z]|[a-z]|[0-9])*")) {
+ return RefactoringStatus
+ .createFatalErrorStatus("Key can contain only letters, digits, and periods");
+ }
+ }
- protected RenameKeyDescriptor createDescriptor() {
- RenameKeyDescriptor descriptor= new RenameKeyDescriptor();
- descriptor.setDescription(MessageFormat.format("Rename resource bundle key ''{0}''", fKeyNode.getMessageKey()));
- descriptor.setComment(MessageFormat.format("Rename resource ''{0}'' to ''{1}''", new Object[] { fKeyNode.getMessageKey(), fNewResourceName }));
- descriptor.setFlags(RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE | RefactoringDescriptor.BREAKING_CHANGE);
- descriptor.setNewName(getNewResourceName());
- descriptor.setRenameChildKeys(fRenameChildKeys);
- return descriptor;
- }
+ if (fMessageBundleGroup.isMessageKey(newName)) {
+ return RefactoringStatus
+ .createFatalErrorStatus(MessagesEditorPlugin
+ .getString("dialog.error.exists"));
+ }
+ return new RefactoringStatus();
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#createChange(org.eclipse.core.runtime.IProgressMonitor)
- */
- public Change createChange(IProgressMonitor pm) throws CoreException {
- pm.beginTask("", 1); //$NON-NLS-1$
- try {
- RenameKeyChange change = new RenameKeyChange(fMessageBundleGroup, getNewKeyTreeNode(), fNewResourceName, fRenameChildKeys);
- change.setDescriptor(new RefactoringChangeDescriptor(createDescriptor()));
- return change;
- } finally {
- pm.done();
- }
- }
+ protected RenameKeyDescriptor createDescriptor() {
+ RenameKeyDescriptor descriptor = new RenameKeyDescriptor();
+ descriptor
+ .setDescription(MessageFormat.format(
+ "Rename resource bundle key ''{0}''",
+ fKeyNode.getMessageKey()));
+ descriptor.setComment(MessageFormat.format(
+ "Rename resource ''{0}'' to ''{1}''",
+ new Object[] { fKeyNode.getMessageKey(), fNewResourceName }));
+ descriptor.setFlags(RefactoringDescriptor.STRUCTURAL_CHANGE
+ | RefactoringDescriptor.MULTI_CHANGE
+ | RefactoringDescriptor.BREAKING_CHANGE);
+ descriptor.setNewName(getNewResourceName());
+ descriptor.setRenameChildKeys(fRenameChildKeys);
+ return descriptor;
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getElements()
- */
- public Object[] getElements() {
- return new Object[] { fKeyNode };
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#
+ * createChange(org.eclipse.core.runtime.IProgressMonitor)
+ */
+ public Change createChange(IProgressMonitor pm) throws CoreException {
+ pm.beginTask("", 1); //$NON-NLS-1$
+ try {
+ RenameKeyChange change = new RenameKeyChange(fMessageBundleGroup,
+ getNewKeyTreeNode(), fNewResourceName, fRenameChildKeys);
+ change.setDescriptor(new RefactoringChangeDescriptor(
+ createDescriptor()));
+ return change;
+ } finally {
+ pm.done();
+ }
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getIdentifier()
- */
- public String getIdentifier() {
- return "org.eclipse.babel.editor.refactoring.renameKeyProcessor"; //$NON-NLS-1$
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#
+ * getElements()
+ */
+ public Object[] getElements() {
+ return new Object[] { fKeyNode };
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getProcessorName()
- */
- public String getProcessorName() {
- return "Rename Resource Bundle Key";
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#
+ * getIdentifier()
+ */
+ public String getIdentifier() {
+ return "org.eclipse.babel.editor.refactoring.renameKeyProcessor"; //$NON-NLS-1$
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#isApplicable()
- */
- public boolean isApplicable() {
- if (this.fKeyNode == null)
- return false;
- return true;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#
+ * getProcessorName()
+ */
+ public String getProcessorName() {
+ return "Rename Resource Bundle Key";
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#loadParticipants(org.eclipse.ltk.core.refactoring.RefactoringStatus, org.eclipse.ltk.core.refactoring.participants.SharableParticipants)
- */
- public RefactoringParticipant[] loadParticipants(RefactoringStatus status, SharableParticipants shared) throws CoreException {
- // TODO: figure out participants to return here
- return new RefactoringParticipant[0];
-
-// String[] affectedNatures= ResourceProcessors.computeAffectedNatures(fResource);
-// return ParticipantManager.loadRenameParticipants(status, this, fResource, fRenameArguments, null, affectedNatures, shared);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#
+ * isApplicable()
+ */
+ public boolean isApplicable() {
+ if (this.fKeyNode == null)
+ return false;
+ return true;
+ }
- /**
- * Returns <code>true</code> if the refactoring processor also renames the child keys
- *
- * @return <code>true</code> if the refactoring processor also renames the child keys
- */
- public boolean getRenameChildKeys() {
- return fRenameChildKeys;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#
+ * loadParticipants(org.eclipse.ltk.core.refactoring.RefactoringStatus,
+ * org.eclipse.ltk.core.refactoring.participants.SharableParticipants)
+ */
+ public RefactoringParticipant[] loadParticipants(RefactoringStatus status,
+ SharableParticipants shared) throws CoreException {
+ // TODO: figure out participants to return here
+ return new RefactoringParticipant[0];
- /**
- * Specifies if the refactoring processor also updates the child keys.
- * The default behaviour is to update the child keys.
- *
- * @param renameChildKeys <code>true</code> if the refactoring processor should also rename the child keys
- */
- public void setRenameChildKeys(boolean renameChildKeys) {
- fRenameChildKeys = renameChildKeys;
- }
+ // String[] affectedNatures=
+ // ResourceProcessors.computeAffectedNatures(fResource);
+ // return ParticipantManager.loadRenameParticipants(status, this,
+ // fResource, fRenameArguments, null, affectedNatures, shared);
+ }
+
+ /**
+ * Returns <code>true</code> if the refactoring processor also renames the
+ * child keys
+ *
+ * @return <code>true</code> if the refactoring processor also renames the
+ * child keys
+ */
+ public boolean getRenameChildKeys() {
+ return fRenameChildKeys;
+ }
+
+ /**
+ * Specifies if the refactoring processor also updates the child keys. The
+ * default behaviour is to update the child keys.
+ *
+ * @param renameChildKeys
+ * <code>true</code> if the refactoring processor should also
+ * rename the child keys
+ */
+ public void setRenameChildKeys(boolean renameChildKeys) {
+ fRenameChildKeys = renameChildKeys;
+ }
}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyWizard.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyWizard.java
index cefc6fa..8cad851 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyWizard.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyWizard.java
@@ -33,131 +33,157 @@
*/
public class RenameKeyWizard extends RefactoringWizard {
- /**
- * Creates a {@link RenameKeyWizard}.
- *
- * @param resource
- * the bundle key to rename
- * @param refactoring
- */
- public RenameKeyWizard(KeyTreeNode resource, RenameKeyProcessor refactoring) {
- super(new RenameRefactoring(refactoring), DIALOG_BASED_USER_INTERFACE);
- setDefaultPageTitle("Rename Resource Bundle Key");
- setWindowTitle("Rename Resource Bundle Key");
- }
+ /**
+ * Creates a {@link RenameKeyWizard}.
+ *
+ * @param resource
+ * the bundle key to rename
+ * @param refactoring
+ */
+ public RenameKeyWizard(KeyTreeNode resource, RenameKeyProcessor refactoring) {
+ super(new RenameRefactoring(refactoring), DIALOG_BASED_USER_INTERFACE);
+ setDefaultPageTitle("Rename Resource Bundle Key");
+ setWindowTitle("Rename Resource Bundle Key");
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ltk.ui.refactoring.RefactoringWizard#addUserInputPages()
- */
- protected void addUserInputPages() {
- RenameKeyProcessor processor = (RenameKeyProcessor) getRefactoring().getAdapter(RenameKeyProcessor.class);
- addPage(new RenameResourceRefactoringConfigurationPage(processor));
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ltk.ui.refactoring.RefactoringWizard#addUserInputPages()
+ */
+ protected void addUserInputPages() {
+ RenameKeyProcessor processor = (RenameKeyProcessor) getRefactoring()
+ .getAdapter(RenameKeyProcessor.class);
+ addPage(new RenameResourceRefactoringConfigurationPage(processor));
+ }
- private static class RenameResourceRefactoringConfigurationPage extends UserInputWizardPage {
+ private static class RenameResourceRefactoringConfigurationPage extends
+ UserInputWizardPage {
- private final RenameKeyProcessor fRefactoringProcessor;
- private Text fNameField;
+ private final RenameKeyProcessor fRefactoringProcessor;
+ private Text fNameField;
- public RenameResourceRefactoringConfigurationPage(RenameKeyProcessor processor) {
- super("RenameResourceRefactoringInputPage"); //$NON-NLS-1$
- fRefactoringProcessor= processor;
- }
+ public RenameResourceRefactoringConfigurationPage(
+ RenameKeyProcessor processor) {
+ super("RenameResourceRefactoringInputPage"); //$NON-NLS-1$
+ fRefactoringProcessor = processor;
+ }
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- composite.setFont(parent.getFont());
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt
+ * .widgets.Composite)
+ */
+ public void createControl(Composite parent) {
+ Composite composite = new Composite(parent, SWT.NONE);
+ composite.setLayout(new GridLayout(2, false));
+ composite
+ .setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ composite.setFont(parent.getFont());
- Label label = new Label(composite, SWT.NONE);
- label.setText("New name:");
- label.setLayoutData(new GridData());
+ Label label = new Label(composite, SWT.NONE);
+ label.setText("New name:");
+ label.setLayoutData(new GridData());
- fNameField = new Text(composite, SWT.BORDER);
- fNameField.setText(fRefactoringProcessor.getNewResourceName());
- fNameField.setFont(composite.getFont());
- fNameField.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false));
- fNameField.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- validatePage();
- }
- });
+ fNameField = new Text(composite, SWT.BORDER);
+ fNameField.setText(fRefactoringProcessor.getNewResourceName());
+ fNameField.setFont(composite.getFont());
+ fNameField.setLayoutData(new GridData(GridData.FILL,
+ GridData.BEGINNING, true, false));
+ fNameField.addModifyListener(new ModifyListener() {
+ public void modifyText(ModifyEvent e) {
+ validatePage();
+ }
+ });
- final Button includeChildKeysCheckbox = new Button(composite, SWT.CHECK);
- if (fRefactoringProcessor.getNewKeyTreeNode().isUsedAsKey()) {
- if (fRefactoringProcessor.getNewKeyTreeNode().getChildren().length == 0) {
- // This is an actual key with no child keys.
- includeChildKeysCheckbox.setSelection(false);
- includeChildKeysCheckbox.setEnabled(false);
- } else {
- // This is both an actual key and it has child keys, so we
- // let the user choose whether to also rename the child keys.
- includeChildKeysCheckbox.setSelection(fRefactoringProcessor.getRenameChildKeys());
- includeChildKeysCheckbox.setEnabled(true);
- }
- } else {
- // This is no an actual key, just a containing node, so the option
- // to rename child keys must be set (otherwise this rename would not
- // do anything).
- includeChildKeysCheckbox.setSelection(true);
- includeChildKeysCheckbox.setEnabled(false);
- }
-
- includeChildKeysCheckbox.setText("Also rename child keys (other keys with this key as a prefix)");
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
- includeChildKeysCheckbox.setLayoutData(gd);
- includeChildKeysCheckbox.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- fRefactoringProcessor.setRenameChildKeys(includeChildKeysCheckbox.getSelection());
- }
- });
-
- fNameField.selectAll();
- setPageComplete(false);
- setControl(composite);
- }
+ final Button includeChildKeysCheckbox = new Button(composite,
+ SWT.CHECK);
+ if (fRefactoringProcessor.getNewKeyTreeNode().isUsedAsKey()) {
+ if (fRefactoringProcessor.getNewKeyTreeNode().getChildren().length == 0) {
+ // This is an actual key with no child keys.
+ includeChildKeysCheckbox.setSelection(false);
+ includeChildKeysCheckbox.setEnabled(false);
+ } else {
+ // This is both an actual key and it has child keys, so we
+ // let the user choose whether to also rename the child
+ // keys.
+ includeChildKeysCheckbox.setSelection(fRefactoringProcessor
+ .getRenameChildKeys());
+ includeChildKeysCheckbox.setEnabled(true);
+ }
+ } else {
+ // This is no an actual key, just a containing node, so the
+ // option
+ // to rename child keys must be set (otherwise this rename would
+ // not
+ // do anything).
+ includeChildKeysCheckbox.setSelection(true);
+ includeChildKeysCheckbox.setEnabled(false);
+ }
- public void setVisible(boolean visible) {
- if (visible) {
- fNameField.setFocus();
- }
- super.setVisible(visible);
- }
+ includeChildKeysCheckbox
+ .setText("Also rename child keys (other keys with this key as a prefix)");
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = 2;
+ includeChildKeysCheckbox.setLayoutData(gd);
+ includeChildKeysCheckbox
+ .addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ fRefactoringProcessor
+ .setRenameChildKeys(includeChildKeysCheckbox
+ .getSelection());
+ }
+ });
- protected final void validatePage() {
- String text= fNameField.getText();
- RefactoringStatus status= fRefactoringProcessor.validateNewElementName(text);
- setPageComplete(status);
- }
+ fNameField.selectAll();
+ setPageComplete(false);
+ setControl(composite);
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ltk.ui.refactoring.UserInputWizardPage#performFinish()
- */
- protected boolean performFinish() {
- initializeRefactoring();
- storeSettings();
- return super.performFinish();
- }
+ public void setVisible(boolean visible) {
+ if (visible) {
+ fNameField.setFocus();
+ }
+ super.setVisible(visible);
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ltk.ui.refactoring.UserInputWizardPage#getNextPage()
- */
- public IWizardPage getNextPage() {
- initializeRefactoring();
- storeSettings();
- return super.getNextPage();
- }
+ protected final void validatePage() {
+ String text = fNameField.getText();
+ RefactoringStatus status = fRefactoringProcessor
+ .validateNewElementName(text);
+ setPageComplete(status);
+ }
- private void storeSettings() {
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ltk.ui.refactoring.UserInputWizardPage#performFinish()
+ */
+ protected boolean performFinish() {
+ initializeRefactoring();
+ storeSettings();
+ return super.performFinish();
+ }
- private void initializeRefactoring() {
- fRefactoringProcessor.setNewResourceName(fNameField.getText());
- }
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ltk.ui.refactoring.UserInputWizardPage#getNextPage()
+ */
+ public IWizardPage getNextPage() {
+ initializeRefactoring();
+ storeSettings();
+ return super.getNextPage();
+ }
+
+ private void storeSettings() {
+ }
+
+ private void initializeRefactoring() {
+ fRefactoringProcessor.setNewResourceName(fNameField.getText());
+ }
+ }
}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/EclipsePropertiesEditorResource.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/EclipsePropertiesEditorResource.java
index 59e57ac..3f41e67 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/EclipsePropertiesEditorResource.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/EclipsePropertiesEditorResource.java
@@ -22,128 +22,133 @@
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.editors.text.TextEditor;
-
/**
* Editor which contains file content being edited, which may not be saved yet
* which may not take effect in a IResource (which make a difference with
* markers).
+ *
* @author Pascal Essiembre
- *
+ *
*/
public class EclipsePropertiesEditorResource extends AbstractPropertiesResource {
private TextEditor textEditor;
- /** label of the location of the resource edited here.
- * When null, try to locate the resource and use it to return that label. */
+ /**
+ * label of the location of the resource edited here. When null, try to
+ * locate the resource and use it to return that label.
+ */
private String _resourceLocationLabel;
-
+
/**
* Constructor.
- * @param locale the resource locale
- * @param serializer resource serializer
- * @param deserializer resource deserializer
- * @param textEditor the editor
+ *
+ * @param locale
+ * the resource locale
+ * @param serializer
+ * resource serializer
+ * @param deserializer
+ * resource deserializer
+ * @param textEditor
+ * the editor
*/
- public EclipsePropertiesEditorResource(
- Locale locale,
+ public EclipsePropertiesEditorResource(Locale locale,
PropertiesSerializer serializer,
- PropertiesDeserializer deserializer,
- TextEditor textEditor) {
+ PropertiesDeserializer deserializer, TextEditor textEditor) {
super(locale, serializer, deserializer);
this.textEditor = textEditor;
- //FIXME: [hugues] this should happen only once at the plugin level?
- //for now it does nothing. Remove it all?
-// IResourceChangeListener rcl = new IResourceChangeListener() {
-// public void resourceChanged(IResourceChangeEvent event) {
-// IResource resource = event.getResource();
-// System.out.println("RESOURCE CHANGED:" + resource);
-// if (resource != null && resource.getFileExtension().equals("escript")) {
-// // run the compiler
-// }
-// }
-// };
-// ResourcesPlugin.getWorkspace().addResourceChangeListener(rcl);
-
+ // FIXME: [hugues] this should happen only once at the plugin level?
+ // for now it does nothing. Remove it all?
+ // IResourceChangeListener rcl = new IResourceChangeListener() {
+ // public void resourceChanged(IResourceChangeEvent event) {
+ // IResource resource = event.getResource();
+ // System.out.println("RESOURCE CHANGED:" + resource);
+ // if (resource != null &&
+ // resource.getFileExtension().equals("escript")) {
+ // // run the compiler
+ // }
+ // }
+ // };
+ // ResourcesPlugin.getWorkspace().addResourceChangeListener(rcl);
+
// [alst] do we really need this? It causes an endless loop!
-// IDocument document = textEditor.getDocumentProvider().getDocument(
-// textEditor.getEditorInput());
-// System.out.println("DOCUMENT:" + document);
-// document.addDocumentListener(new IDocumentListener() {
-// public void documentAboutToBeChanged(DocumentEvent event) {
-// //do nothing
-// System.out.println("DOCUMENT ABOUT to CHANGE:");
-// }
-// public void documentChanged(DocumentEvent event) {
-// System.out.println("DOCUMENT CHANGED:");
-//// fireResourceChange(EclipsePropertiesEditorResource.this);
-// }
-// });
-
-// IDocumentProvider docProvider = textEditor.getDocumentProvider();
-//// PropertiesFileDocumentProvider
-// // textEditor.getEditorInput().
-//
-//// textEditor.sets
-//
-// docProvider.addElementStateListener(new IElementStateListener() {
-// public void elementContentAboutToBeReplaced(Object element) {
-// System.out.println("about:" + element);
-// }
-// public void elementContentReplaced(Object element) {
-// System.out.println("replaced:" + element);
-// }
-// public void elementDeleted(Object element) {
-// System.out.println("deleted:" + element);
-// }
-// public void elementDirtyStateChanged(Object element, boolean isDirty) {
-// System.out.println("dirty:" + element + " " + isDirty);
-// }
-// public void elementMoved(Object originalElement, Object movedElement) {
-// System.out.println("moved from:" + originalElement
-// + " to " + movedElement);
-// }
-// });
-
-
-// textEditor.addPropertyListener(new IPropertyListener() {
-// public void propertyChanged(Object source, int propId) {
-// System.out.println(
-// "text editor changed. source:"
-// + source
-// + " propId: " + propId);
-// fireResourceChange(EclipsePropertiesEditorResource.this);
-// }
-// });
+ // IDocument document = textEditor.getDocumentProvider().getDocument(
+ // textEditor.getEditorInput());
+ // System.out.println("DOCUMENT:" + document);
+ // document.addDocumentListener(new IDocumentListener() {
+ // public void documentAboutToBeChanged(DocumentEvent event) {
+ // //do nothing
+ // System.out.println("DOCUMENT ABOUT to CHANGE:");
+ // }
+ // public void documentChanged(DocumentEvent event) {
+ // System.out.println("DOCUMENT CHANGED:");
+ // // fireResourceChange(EclipsePropertiesEditorResource.this);
+ // }
+ // });
+
+ // IDocumentProvider docProvider = textEditor.getDocumentProvider();
+ // // PropertiesFileDocumentProvider
+ // // textEditor.getEditorInput().
+ //
+ // // textEditor.sets
+ //
+ // docProvider.addElementStateListener(new IElementStateListener() {
+ // public void elementContentAboutToBeReplaced(Object element) {
+ // System.out.println("about:" + element);
+ // }
+ // public void elementContentReplaced(Object element) {
+ // System.out.println("replaced:" + element);
+ // }
+ // public void elementDeleted(Object element) {
+ // System.out.println("deleted:" + element);
+ // }
+ // public void elementDirtyStateChanged(Object element, boolean isDirty)
+ // {
+ // System.out.println("dirty:" + element + " " + isDirty);
+ // }
+ // public void elementMoved(Object originalElement, Object movedElement)
+ // {
+ // System.out.println("moved from:" + originalElement
+ // + " to " + movedElement);
+ // }
+ // });
+
+ // textEditor.addPropertyListener(new IPropertyListener() {
+ // public void propertyChanged(Object source, int propId) {
+ // System.out.println(
+ // "text editor changed. source:"
+ // + source
+ // + " propId: " + propId);
+ // fireResourceChange(EclipsePropertiesEditorResource.this);
+ // }
+ // });
}
/**
* @see org.eclipse.babel.core.bundle.resource.TextResource#getText()
*/
public String getText() {
- return textEditor.getDocumentProvider().getDocument(
- textEditor.getEditorInput()).get();
+ return textEditor.getDocumentProvider()
+ .getDocument(textEditor.getEditorInput()).get();
}
/**
- * @see org.eclipse.babel.core.bundle.resource.TextResource#setText(
- * java.lang.String)
+ * @see org.eclipse.babel.core.bundle.resource.TextResource#setText(java.lang.String)
*/
public void setText(final String content) {
- /*
- * We may come in from an event from another thread, so ensure
- * we are on the UI thread. This may not be the best place to do
- * this???
- */
- // [alst] muss 2x speichern wenn async exec
-// Display.getDefault().asyncExec(new Runnable() {
-// public void run() {
- if (DirtyHack.isEditorModificationEnabled()) {
- textEditor.getDocumentProvider()
- .getDocument(textEditor.getEditorInput()).set(content);
- }
-// }
-// });
+ /*
+ * We may come in from an event from another thread, so ensure we are on
+ * the UI thread. This may not be the best place to do this???
+ */
+ // [alst] muss 2x speichern wenn async exec
+ // Display.getDefault().asyncExec(new Runnable() {
+ // public void run() {
+ if (DirtyHack.isEditorModificationEnabled()) {
+ textEditor.getDocumentProvider()
+ .getDocument(textEditor.getEditorInput()).set(content);
+ }
+ // }
+ // });
}
/**
@@ -152,7 +157,7 @@
public Object getSource() {
return textEditor;
}
-
+
public IResource getResource() {
IEditorInput input = textEditor.getEditorInput();
if (input instanceof IFileEditorInput) {
@@ -160,35 +165,35 @@
}
return null;
}
-
+
/**
* @return The resource location label. or null if unknown.
*/
public String getResourceLocationLabel() {
- if (_resourceLocationLabel != null) {
- return _resourceLocationLabel;
- }
- IResource resource = getResource();
- if (resource != null) {
- return resource.getFullPath().toString();
- }
- return null;
- }
-
- /**
- * @param resourceLocationLabel The label of the location of the edited resource.
- */
- public void setResourceLocationLabel(String resourceLocationLabel) {
- _resourceLocationLabel = resourceLocationLabel;
- }
-
- /**
- * Called before this object will be discarded.
- * Nothing to do: we were not listening to changes to this file ourselves.
- */
- public void dispose() {
- //nothing to do.
+ if (_resourceLocationLabel != null) {
+ return _resourceLocationLabel;
+ }
+ IResource resource = getResource();
+ if (resource != null) {
+ return resource.getFullPath().toString();
+ }
+ return null;
}
-
+ /**
+ * @param resourceLocationLabel
+ * The label of the location of the edited resource.
+ */
+ public void setResourceLocationLabel(String resourceLocationLabel) {
+ _resourceLocationLabel = resourceLocationLabel;
+ }
+
+ /**
+ * Called before this object will be discarded. Nothing to do: we were not
+ * listening to changes to this file ourselves.
+ */
+ public void dispose() {
+ // nothing to do.
+ }
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/FileMarkerStrategy.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/FileMarkerStrategy.java
index b03521a..c0a0b00 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/FileMarkerStrategy.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/FileMarkerStrategy.java
@@ -22,79 +22,79 @@
/**
* @author Pascal Essiembre
- *
+ *
*/
public class FileMarkerStrategy implements IValidationMarkerStrategy {
-
/**
- * @see org.eclipse.babel.editor.resource.validator.IValidationMarkerStrategy#markFailed(org.eclipse.core.resources.IResource, org.eclipse.babel.core.bundle.checks.IBundleEntryCheck)
+ * @see org.eclipse.babel.editor.resource.validator.IValidationMarkerStrategy#markFailed(org.eclipse.core.resources.IResource,
+ * org.eclipse.babel.core.bundle.checks.IBundleEntryCheck)
*/
public void markFailed(ValidationFailureEvent event) {
if (event.getCheck() instanceof MissingValueCheck) {
- MessagesBundle bundle = (MessagesBundle) event.getBundleGroup().getMessagesBundle(event.getLocale());
+ MessagesBundle bundle = (MessagesBundle) event.getBundleGroup()
+ .getMessagesBundle(event.getLocale());
addMarker((IResource) bundle.getResource().getSource(),
-// addMarker(event.getResource(),
- event.getKey(),
- "Key \"" + event.getKey() //$NON-NLS-1$
- + "\" is missing a value.", //$NON-NLS-1$
- getSeverity(MsgEditorPreferences.getInstance()
- .getReportMissingValuesLevel()));
-
+ // addMarker(event.getResource(),
+ event.getKey(), "Key \"" + event.getKey() //$NON-NLS-1$
+ + "\" is missing a value.", //$NON-NLS-1$
+ getSeverity(MsgEditorPreferences.getInstance()
+ .getReportMissingValuesLevel()));
+
} else if (event.getCheck() instanceof DuplicateValueCheck) {
- String duplicates = BabelUtils.join(
- ((DuplicateValueCheck) event.getCheck())
+ String duplicates = BabelUtils
+ .join(((DuplicateValueCheck) event.getCheck())
.getDuplicateKeys(), ", ");
- MessagesBundle bundle = (MessagesBundle) event.getBundleGroup().getMessagesBundle(event.getLocale());
+ MessagesBundle bundle = (MessagesBundle) event.getBundleGroup()
+ .getMessagesBundle(event.getLocale());
addMarker((IResource) bundle.getResource().getSource(),
-// addMarker(event.getResource(),
- event.getKey(),
- "Key \"" + event.getKey() //$NON-NLS-1$
- + "\" duplicates " + duplicates, //$NON-NLS-1$
- getSeverity(MsgEditorPreferences.getInstance()
- .getReportDuplicateValuesLevel()));
+ // addMarker(event.getResource(),
+ event.getKey(), "Key \"" + event.getKey() //$NON-NLS-1$
+ + "\" duplicates " + duplicates, //$NON-NLS-1$
+ getSeverity(MsgEditorPreferences.getInstance()
+ .getReportDuplicateValuesLevel()));
}
}
- private void addMarker(
- IResource resource,
- String key,
- String message, //int lineNumber,
+ private void addMarker(IResource resource, String key, String message, // int
+ // lineNumber,
int severity) {
try {
- //TODO move MARKER_TYPE elsewhere.
- IMarker marker = resource.createMarker(MessagesEditorPlugin.MARKER_TYPE);
+ // TODO move MARKER_TYPE elsewhere.
+ IMarker marker = resource
+ .createMarker(MessagesEditorPlugin.MARKER_TYPE);
marker.setAttribute(IMarker.MESSAGE, message);
marker.setAttribute(IMarker.SEVERITY, severity);
marker.setAttribute(IMarker.LOCATION, key);
-// if (lineNumber == -1) {
-// lineNumber = 1;
-// }
-// marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
+ // if (lineNumber == -1) {
+ // lineNumber = 1;
+ // }
+ // marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
} catch (CoreException e) {
throw new RuntimeException("Cannot add marker.", e); //$NON-NLS-1$
}
}
/**
- * Translates the validation level as defined in
- * MsgEditorPreferences.VALIDATION_MESSAGE_* to the corresponding value
- * for the marker attribute IMarke.SEVERITY.
+ * Translates the validation level as defined in
+ * MsgEditorPreferences.VALIDATION_MESSAGE_* to the corresponding value for
+ * the marker attribute IMarke.SEVERITY.
+ *
* @param msgValidationLevel
* @return The value for the marker attribute IMarker.SEVERITY.
*/
private static int getSeverity(int msgValidationLevel) {
- switch (msgValidationLevel) {
- case MsgEditorPreferences.VALIDATION_MESSAGE_ERROR:
- return IMarker.SEVERITY_ERROR;
- case MsgEditorPreferences.VALIDATION_MESSAGE_WARNING:
- return IMarker.SEVERITY_WARNING;
- case MsgEditorPreferences.VALIDATION_MESSAGE_INFO:
- return IMarker.SEVERITY_INFO;
- case MsgEditorPreferences.VALIDATION_MESSAGE_IGNORE:
- default:
- return IMarker.SEVERITY_INFO;//why are we here?
- }
+ switch (msgValidationLevel) {
+ case MsgEditorPreferences.VALIDATION_MESSAGE_ERROR:
+ return IMarker.SEVERITY_ERROR;
+ case MsgEditorPreferences.VALIDATION_MESSAGE_WARNING:
+ return IMarker.SEVERITY_WARNING;
+ case MsgEditorPreferences.VALIDATION_MESSAGE_INFO:
+ return IMarker.SEVERITY_INFO;
+ case MsgEditorPreferences.VALIDATION_MESSAGE_IGNORE:
+ default:
+ return IMarker.SEVERITY_INFO;// why are we here?
+ }
}
-
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/IValidationMarkerStrategy.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/IValidationMarkerStrategy.java
index 29ff6ad..0866573 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/IValidationMarkerStrategy.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/IValidationMarkerStrategy.java
@@ -10,10 +10,9 @@
******************************************************************************/
package org.eclipse.babel.editor.resource.validator;
-
/**
* @author Pascal Essiembre
- *
+ *
*/
public interface IValidationMarkerStrategy {
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/MessagesBundleGroupValidator.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/MessagesBundleGroupValidator.java
index 00dfe71..f585f36 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/MessagesBundleGroupValidator.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/MessagesBundleGroupValidator.java
@@ -17,53 +17,49 @@
import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
import org.eclipse.babel.editor.preferences.MsgEditorPreferences;
-
/**
* @author Pascal Essiembre
- *
+ *
*/
-public class MessagesBundleGroupValidator {
-
- //TODO Re-think... ??
+public class MessagesBundleGroupValidator {
- public static void validate(
- MessagesBundleGroup messagesBundleGroup,
- Locale locale,
- IValidationMarkerStrategy markerStrategy) {
- //TODO check if there is a matching EclipsePropertiesEditorResource already open.
- //else, create MessagesBundle from PropertiesIFileResource
-
- DuplicateValueCheck duplicateCheck =
- MsgEditorPreferences.getInstance().getReportDuplicateValues()
- ? new DuplicateValueCheck()
- : null;
- String[] keys = messagesBundleGroup.getMessageKeys();
- for (int i = 0; i < keys.length; i++) {
- String key = keys[i];
+ // TODO Re-think... ??
+
+ public static void validate(MessagesBundleGroup messagesBundleGroup,
+ Locale locale, IValidationMarkerStrategy markerStrategy) {
+ // TODO check if there is a matching EclipsePropertiesEditorResource
+ // already open.
+ // else, create MessagesBundle from PropertiesIFileResource
+
+ DuplicateValueCheck duplicateCheck = MsgEditorPreferences.getInstance()
+ .getReportDuplicateValues() ? new DuplicateValueCheck() : null;
+ String[] keys = messagesBundleGroup.getMessageKeys();
+ for (int i = 0; i < keys.length; i++) {
+ String key = keys[i];
if (MsgEditorPreferences.getInstance().getReportMissingValues()) {
- if (MissingValueCheck.MISSING_KEY.checkKey(
- messagesBundleGroup,
- messagesBundleGroup.getMessage(key, locale))) {
- markerStrategy.markFailed(new ValidationFailureEvent(
- messagesBundleGroup, locale, key,
- MissingValueCheck.MISSING_KEY));
- }
+ if (MissingValueCheck.MISSING_KEY.checkKey(messagesBundleGroup,
+ messagesBundleGroup.getMessage(key, locale))) {
+ markerStrategy.markFailed(new ValidationFailureEvent(
+ messagesBundleGroup, locale, key,
+ MissingValueCheck.MISSING_KEY));
+ }
}
if (duplicateCheck != null) {
- if (!MsgEditorPreferences.getInstance().getReportDuplicateValuesOnlyInRootLocales()
- || (locale == null || locale.toString().length() == 0)) {
- //either the locale is the root locale either
- //we report duplicated on all the locales anyways.
- if (duplicateCheck.checkKey(
- messagesBundleGroup,
- messagesBundleGroup.getMessage(key, locale))) {
- markerStrategy.markFailed(new ValidationFailureEvent(
- messagesBundleGroup, locale, key, duplicateCheck));
- }
- duplicateCheck.reset();
- }
+ if (!MsgEditorPreferences.getInstance()
+ .getReportDuplicateValuesOnlyInRootLocales()
+ || (locale == null || locale.toString().length() == 0)) {
+ // either the locale is the root locale either
+ // we report duplicated on all the locales anyways.
+ if (duplicateCheck.checkKey(messagesBundleGroup,
+ messagesBundleGroup.getMessage(key, locale))) {
+ markerStrategy.markFailed(new ValidationFailureEvent(
+ messagesBundleGroup, locale, key,
+ duplicateCheck));
+ }
+ duplicateCheck.reset();
+ }
}
}
}
-
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/ValidationFailureEvent.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/ValidationFailureEvent.java
index 723b411..bd79bf1 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/ValidationFailureEvent.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/ValidationFailureEvent.java
@@ -15,56 +15,60 @@
import org.eclipse.babel.core.message.checks.IMessageCheck;
import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
-
/**
* @author Pascal Essiembre
- *
+ *
*/
public class ValidationFailureEvent {
private final MessagesBundleGroup messagesBundleGroup;
private final Locale locale;
private final String key;
-// private final IResource resource;
+ // private final IResource resource;
private final IMessageCheck check;
+
/**
* @param messagesBundleGroup
* @param locale
* @param key
* @param resource
- * @param check not null
+ * @param check
+ * not null
*/
- /*default*/ ValidationFailureEvent(
- final MessagesBundleGroup messagesBundleGroup,
- final Locale locale,
+ /* default */ValidationFailureEvent(
+ final MessagesBundleGroup messagesBundleGroup, final Locale locale,
final String key,
-// final IResource resource,
+ // final IResource resource,
final IMessageCheck check) {
super();
this.messagesBundleGroup = messagesBundleGroup;
this.locale = locale;
this.key = key;
-// this.resource = resource;
+ // this.resource = resource;
this.check = check;
}
+
/**
* @return the messagesBundleGroup
*/
public MessagesBundleGroup getBundleGroup() {
return messagesBundleGroup;
}
+
/**
* @return the check, never null
*/
public IMessageCheck getCheck() {
return check;
}
+
/**
* @return the key
*/
public String getKey() {
return key;
}
+
/**
* @return the locale
*/
@@ -72,6 +76,4 @@
return locale;
}
-
-
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/IKeyTreeContributor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/IKeyTreeContributor.java
index 0a503b0..3ba1a29 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/IKeyTreeContributor.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/IKeyTreeContributor.java
@@ -15,9 +15,9 @@
public interface IKeyTreeContributor {
- void contribute(final TreeViewer treeViewer);
+ void contribute(final TreeViewer treeViewer);
- IKeyTreeNode getKeyTreeNode(String key);
+ IKeyTreeNode getKeyTreeNode(String key);
- IKeyTreeNode[] getRootKeyItems();
+ IKeyTreeNode[] getRootKeyItems();
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AbstractTreeAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AbstractTreeAction.java
index bbfbda1..46e71a5 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AbstractTreeAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AbstractTreeAction.java
@@ -20,71 +20,72 @@
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.widgets.Shell;
-
/**
* @author Pascal Essiembre
- *
+ *
*/
public abstract class AbstractTreeAction extends Action {
-// private static final KeyTreeNode[] EMPTY_TREE_NODES = new KeyTreeNode[]{};
-
+ // private static final KeyTreeNode[] EMPTY_TREE_NODES = new
+ // KeyTreeNode[]{};
+
protected final TreeViewer treeViewer;
protected final MessagesEditor editor;
-
+
/**
*
*/
- public AbstractTreeAction(
- MessagesEditor editor, TreeViewer treeViewer) {
+ public AbstractTreeAction(MessagesEditor editor, TreeViewer treeViewer) {
super();
this.treeViewer = treeViewer;
this.editor = editor;
}
+
/**
*
*/
- public AbstractTreeAction(
- MessagesEditor editor, TreeViewer treeViewer, int style) {
+ public AbstractTreeAction(MessagesEditor editor, TreeViewer treeViewer,
+ int style) {
super("", style);
this.treeViewer = treeViewer;
this.editor = editor;
}
protected KeyTreeNode getNodeSelection() {
- IStructuredSelection selection =
- (IStructuredSelection) treeViewer.getSelection();
+ IStructuredSelection selection = (IStructuredSelection) treeViewer
+ .getSelection();
return (KeyTreeNode) selection.getFirstElement();
}
+
protected KeyTreeNode[] getBranchNodes(KeyTreeNode node) {
return ((AbstractKeyTreeModel) treeViewer.getInput()).getBranch(node);
-//
-// Set childNodes = new TreeSet();
-// childNodes.add(node);
-// Object[] nodes = getContentProvider().getChildren(node);
-// for (int i = 0; i < nodes.length; i++) {
-// childNodes.addAll(
-// Arrays.asList(getBranchNodes((KeyTreeNode) nodes[i])));
-// }
-// return (KeyTreeNode[]) childNodes.toArray(EMPTY_TREE_NODES);
+ //
+ // Set childNodes = new TreeSet();
+ // childNodes.add(node);
+ // Object[] nodes = getContentProvider().getChildren(node);
+ // for (int i = 0; i < nodes.length; i++) {
+ // childNodes.addAll(
+ // Arrays.asList(getBranchNodes((KeyTreeNode) nodes[i])));
+ // }
+ // return (KeyTreeNode[]) childNodes.toArray(EMPTY_TREE_NODES);
}
protected ITreeContentProvider getContentProvider() {
return (ITreeContentProvider) treeViewer.getContentProvider();
}
-
+
protected MessagesBundleGroup getBundleGroup() {
return editor.getBundleGroup();
}
-
+
protected TreeViewer getTreeViewer() {
return treeViewer;
}
-
+
protected MessagesEditor getEditor() {
return editor;
}
-
+
protected Shell getShell() {
return treeViewer.getTree().getShell();
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AddKeyAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AddKeyAction.java
index b143210..d55bf21 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AddKeyAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AddKeyAction.java
@@ -30,10 +30,10 @@
*
*/
public AddKeyAction(MessagesEditor editor, TreeViewer treeViewer) {
- super(editor, treeViewer);
- setText(MessagesEditorPlugin.getString("key.add") + " ..."); //$NON-NLS-1$
- setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_ADD));
- setToolTipText("TODO put something here"); // TODO put tooltip
+ super(editor, treeViewer);
+ setText(MessagesEditorPlugin.getString("key.add") + " ..."); //$NON-NLS-1$
+ setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_ADD));
+ setToolTipText("TODO put something here"); // TODO put tooltip
}
/**
@@ -41,26 +41,26 @@
*/
@Override
public void run() {
- KeyTreeNode node = getNodeSelection();
- String key = node.getMessageKey();
- String msgHead = MessagesEditorPlugin.getString("dialog.add.head");
- String msgBody = MessagesEditorPlugin.getString("dialog.add.body");
- InputDialog dialog = new InputDialog(getShell(), msgHead, msgBody, key,
- new IInputValidator() {
- public String isValid(String newText) {
- if (getBundleGroup().isMessageKey(newText)) {
- return MessagesEditorPlugin
- .getString("dialog.error.exists");
- }
- return null;
- }
- });
- dialog.open();
- if (dialog.getReturnCode() == Window.OK) {
- String inputKey = dialog.getValue();
- MessagesBundleGroup messagesBundleGroup = getBundleGroup();
- messagesBundleGroup.addMessages(inputKey);
- }
+ KeyTreeNode node = getNodeSelection();
+ String key = node.getMessageKey();
+ String msgHead = MessagesEditorPlugin.getString("dialog.add.head");
+ String msgBody = MessagesEditorPlugin.getString("dialog.add.body");
+ InputDialog dialog = new InputDialog(getShell(), msgHead, msgBody, key,
+ new IInputValidator() {
+ public String isValid(String newText) {
+ if (getBundleGroup().isMessageKey(newText)) {
+ return MessagesEditorPlugin
+ .getString("dialog.error.exists");
+ }
+ return null;
+ }
+ });
+ dialog.open();
+ if (dialog.getReturnCode() == Window.OK) {
+ String inputKey = dialog.getValue();
+ MessagesBundleGroup messagesBundleGroup = getBundleGroup();
+ messagesBundleGroup.addMessages(inputKey);
+ }
}
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/CollapseAllAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/CollapseAllAction.java
index b8e18cf..7707356 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/CollapseAllAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/CollapseAllAction.java
@@ -17,7 +17,7 @@
/**
* @author Pascal Essiembre
- *
+ *
*/
public class CollapseAllAction extends AbstractTreeAction {
@@ -28,9 +28,9 @@
public CollapseAllAction(MessagesEditor editor, TreeViewer treeViewer) {
super(editor, treeViewer);
setText(MessagesEditorPlugin.getString("key.collapseAll")); //$NON-NLS-1$
- setImageDescriptor(
- UIUtils.getImageDescriptor(UIUtils.IMAGE_COLLAPSE_ALL));
- setToolTipText("Collapse all"); //TODO put tooltip
+ setImageDescriptor(UIUtils
+ .getImageDescriptor(UIUtils.IMAGE_COLLAPSE_ALL));
+ setToolTipText("Collapse all"); // TODO put tooltip
}
/**
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/DeleteKeyAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/DeleteKeyAction.java
index c38c791..d28cb5c 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/DeleteKeyAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/DeleteKeyAction.java
@@ -22,7 +22,7 @@
/**
* @author Pascal Essiembre
- *
+ *
*/
public class DeleteKeyAction extends AbstractTreeAction {
@@ -32,17 +32,17 @@
public DeleteKeyAction(MessagesEditor editor, TreeViewer treeViewer) {
super(editor, treeViewer);
setText(MessagesEditorPlugin.getString("key.delete")); //$NON-NLS-1$
- setImageDescriptor(
- PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
- ISharedImages.IMG_TOOL_DELETE));
- setToolTipText("TODO put something here"); //TODO put tooltip
-// setActionDefinitionId("org.eclilpse.babel.editor.editor.tree.delete");
-// setActionDefinitionId("org.eclipse.ui.edit.delete");
-// editor.getSite().getKeyBindingService().registerAction(this);
+ setImageDescriptor(PlatformUI.getWorkbench().getSharedImages()
+ .getImageDescriptor(ISharedImages.IMG_TOOL_DELETE));
+ setToolTipText("TODO put something here"); // TODO put tooltip
+ // setActionDefinitionId("org.eclilpse.babel.editor.editor.tree.delete");
+ // setActionDefinitionId("org.eclipse.ui.edit.delete");
+ // editor.getSite().getKeyBindingService().registerAction(this);
}
-
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
@@ -51,18 +51,18 @@
String msgHead = null;
String msgBody = null;
if (getContentProvider().hasChildren(node)) {
- msgHead = MessagesEditorPlugin.getString(
- "dialog.delete.head.multiple"); //$NON-NLS-1$
+ msgHead = MessagesEditorPlugin
+ .getString("dialog.delete.head.multiple"); //$NON-NLS-1$
msgBody = MessagesEditorPlugin.getString(
"dialog.delete.body.multiple", key);//$NON-NLS-1$
} else {
- msgHead = MessagesEditorPlugin.getString(
- "dialog.delete.head.single"); //$NON-NLS-1$
+ msgHead = MessagesEditorPlugin
+ .getString("dialog.delete.head.single"); //$NON-NLS-1$
msgBody = MessagesEditorPlugin.getString(
"dialog.delete.body.single", key); //$NON-NLS-1$
}
- MessageBox msgBox = new MessageBox(
- getShell(), SWT.ICON_QUESTION|SWT.OK|SWT.CANCEL);
+ MessageBox msgBox = new MessageBox(getShell(), SWT.ICON_QUESTION
+ | SWT.OK | SWT.CANCEL);
msgBox.setMessage(msgBody);
msgBox.setText(msgHead);
if (msgBox.open() == SWT.OK) {
@@ -70,10 +70,10 @@
KeyTreeNode[] nodesToDelete = getBranchNodes(node);
for (int i = 0; i < nodesToDelete.length; i++) {
KeyTreeNode nodeToDelete = nodesToDelete[i];
- messagesBundleGroup.removeMessages(nodeToDelete.getMessageKey());
+ messagesBundleGroup
+ .removeMessages(nodeToDelete.getMessageKey());
}
}
}
-
-
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/ExpandAllAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/ExpandAllAction.java
index ed9018d..1a87db8 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/ExpandAllAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/ExpandAllAction.java
@@ -17,7 +17,7 @@
/**
* @author Pascal Essiembre
- *
+ *
*/
public class ExpandAllAction extends AbstractTreeAction {
@@ -28,9 +28,8 @@
public ExpandAllAction(MessagesEditor editor, TreeViewer treeViewer) {
super(editor, treeViewer);
setText(MessagesEditorPlugin.getString("key.expandAll")); //$NON-NLS-1$
- setImageDescriptor(
- UIUtils.getImageDescriptor(UIUtils.IMAGE_EXPAND_ALL));
- setToolTipText("Expand All"); //TODO put tooltip
+ setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_EXPAND_ALL));
+ setToolTipText("Expand All"); // TODO put tooltip
}
/**
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/FlatModelAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/FlatModelAction.java
index 942adb5..09070a6 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/FlatModelAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/FlatModelAction.java
@@ -20,7 +20,7 @@
/**
* @author Pascal Essiembre
- *
+ *
*/
public class FlatModelAction extends AbstractTreeAction {
@@ -31,18 +31,19 @@
public FlatModelAction(MessagesEditor editor, TreeViewer treeViewer) {
super(editor, treeViewer, IAction.AS_RADIO_BUTTON);
setText(MessagesEditorPlugin.getString("key.layout.flat")); //$NON-NLS-1$
- setImageDescriptor(
- UIUtils.getImageDescriptor(UIUtils.IMAGE_LAYOUT_FLAT));
- setDisabledImageDescriptor(
- UIUtils.getImageDescriptor(UIUtils.IMAGE_LAYOUT_FLAT));
- setToolTipText("Display in a list"); //TODO put tooltip
+ setImageDescriptor(UIUtils
+ .getImageDescriptor(UIUtils.IMAGE_LAYOUT_FLAT));
+ setDisabledImageDescriptor(UIUtils
+ .getImageDescriptor(UIUtils.IMAGE_LAYOUT_FLAT));
+ setToolTipText("Display in a list"); // TODO put tooltip
}
/**
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
- KeyTreeContentProvider contentProvider = (KeyTreeContentProvider)treeViewer.getContentProvider();
- contentProvider.setTreeType(TreeType.Flat);
+ KeyTreeContentProvider contentProvider = (KeyTreeContentProvider) treeViewer
+ .getContentProvider();
+ contentProvider.setTreeType(TreeType.Flat);
}
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/RenameKeyAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/RenameKeyAction.java
index a55b755..add1ff9 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/RenameKeyAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/RenameKeyAction.java
@@ -30,10 +30,10 @@
*
*/
public RenameKeyAction(MessagesEditor editor, TreeViewer treeViewer) {
- super(editor, treeViewer);
- setText(MessagesEditorPlugin.getString("key.rename") + " ..."); //$NON-NLS-1$
- setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_RENAME));
- setToolTipText("TODO put something here"); // TODO put tooltip
+ super(editor, treeViewer);
+ setText(MessagesEditorPlugin.getString("key.rename") + " ..."); //$NON-NLS-1$
+ setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_RENAME));
+ setToolTipText("TODO put something here"); // TODO put tooltip
}
/**
@@ -41,19 +41,19 @@
*/
@Override
public void run() {
- KeyTreeNode node = getNodeSelection();
+ KeyTreeNode node = getNodeSelection();
- // Rename single item
- RenameKeyProcessor refactoring = new RenameKeyProcessor(node,
- getBundleGroup());
+ // Rename single item
+ RenameKeyProcessor refactoring = new RenameKeyProcessor(node,
+ getBundleGroup());
- RefactoringWizard wizard = new RenameKeyWizard(node, refactoring);
- try {
- RefactoringWizardOpenOperation operation = new RefactoringWizardOpenOperation(
- wizard);
- operation.run(getShell(), "Introduce Indirection");
- } catch (InterruptedException exception) {
- // Do nothing
- }
+ RefactoringWizard wizard = new RenameKeyWizard(node, refactoring);
+ try {
+ RefactoringWizardOpenOperation operation = new RefactoringWizardOpenOperation(
+ wizard);
+ operation.run(getShell(), "Introduce Indirection");
+ } catch (InterruptedException exception) {
+ // Do nothing
+ }
}
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/TreeModelAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/TreeModelAction.java
index 5bf94cc..756b2ae 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/TreeModelAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/TreeModelAction.java
@@ -20,7 +20,7 @@
/**
* @author Pascal Essiembre
- *
+ *
*/
public class TreeModelAction extends AbstractTreeAction {
@@ -31,9 +31,9 @@
public TreeModelAction(MessagesEditor editor, TreeViewer treeViewer) {
super(editor, treeViewer, IAction.AS_RADIO_BUTTON);
setText(MessagesEditorPlugin.getString("key.layout.tree")); //$NON-NLS-1$
- setImageDescriptor(
- UIUtils.getImageDescriptor(UIUtils.IMAGE_LAYOUT_HIERARCHICAL));
- setToolTipText("Display as in a Tree"); //TODO put tooltip
+ setImageDescriptor(UIUtils
+ .getImageDescriptor(UIUtils.IMAGE_LAYOUT_HIERARCHICAL));
+ setToolTipText("Display as in a Tree"); // TODO put tooltip
setChecked(true);
}
@@ -41,7 +41,8 @@
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
- KeyTreeContentProvider contentProvider = (KeyTreeContentProvider)treeViewer.getContentProvider();
- contentProvider.setTreeType(TreeType.Tree);
+ KeyTreeContentProvider contentProvider = (KeyTreeContentProvider) treeViewer
+ .getContentProvider();
+ contentProvider.setTreeType(TreeType.Tree);
}
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContentProvider.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContentProvider.java
index 4c03fa4..e85e7c9 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContentProvider.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContentProvider.java
@@ -22,19 +22,19 @@
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
-
/**
* Content provider for key tree viewer.
+ *
* @author Pascal Essiembre
*/
public class KeyTreeContentProvider implements ITreeContentProvider {
private AbstractKeyTreeModel keyTreeModel;
- private Viewer viewer;
+ private Viewer viewer;
private TreeType treeType;
-
+
/**
- * @param treeType
+ * @param treeType
*
*/
public KeyTreeContentProvider(TreeType treeType) {
@@ -42,103 +42,102 @@
}
/**
- * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(
- * java.lang.Object)
+ * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
*/
public Object[] getChildren(Object parentElement) {
KeyTreeNode parentNode = (KeyTreeNode) parentElement;
switch (treeType) {
case Tree:
- return keyTreeModel.getChildren(parentNode);
+ return keyTreeModel.getChildren(parentNode);
case Flat:
- return new KeyTreeNode[0];
- default:
- // Should not happen
- return new KeyTreeNode[0];
+ return new KeyTreeNode[0];
+ default:
+ // Should not happen
+ return new KeyTreeNode[0];
}
}
/**
* @see org.eclipse.jface.viewers.ITreeContentProvider#
- * getParent(java.lang.Object)
+ * getParent(java.lang.Object)
*/
public Object getParent(Object element) {
KeyTreeNode node = (KeyTreeNode) element;
switch (treeType) {
case Tree:
- return keyTreeModel.getParent(node);
+ return keyTreeModel.getParent(node);
case Flat:
- return keyTreeModel;
- default:
- // Should not happen
- return null;
+ return keyTreeModel;
+ default:
+ // Should not happen
+ return null;
}
}
/**
* @see org.eclipse.jface.viewers.ITreeContentProvider#
- * hasChildren(java.lang.Object)
+ * hasChildren(java.lang.Object)
*/
public boolean hasChildren(Object element) {
switch (treeType) {
case Tree:
return keyTreeModel.getChildren((KeyTreeNode) element).length > 0;
case Flat:
- return false;
- default:
- // Should not happen
- return false;
+ return false;
+ default:
+ // Should not happen
+ return false;
}
}
/**
* @see org.eclipse.jface.viewers.IStructuredContentProvider#
- * getElements(java.lang.Object)
+ * getElements(java.lang.Object)
*/
public Object[] getElements(Object inputElement) {
- switch (treeType) {
+ switch (treeType) {
case Tree:
return keyTreeModel.getRootNodes();
case Flat:
- final Collection<IKeyTreeNode> actualKeys = new ArrayList<IKeyTreeNode>();
- IKeyTreeVisitor visitor = new IKeyTreeVisitor() {
- public void visitKeyTreeNode(IKeyTreeNode node) {
- if (node.isUsedAsKey()) {
- actualKeys.add(node);
- }
- }
- };
- keyTreeModel.accept(visitor, keyTreeModel.getRootNode());
- return actualKeys.toArray();
+ final Collection<IKeyTreeNode> actualKeys = new ArrayList<IKeyTreeNode>();
+ IKeyTreeVisitor visitor = new IKeyTreeVisitor() {
+ public void visitKeyTreeNode(IKeyTreeNode node) {
+ if (node.isUsedAsKey()) {
+ actualKeys.add(node);
+ }
+ }
+ };
+ keyTreeModel.accept(visitor, keyTreeModel.getRootNode());
+ return actualKeys.toArray();
default:
- // Should not happen
- return new KeyTreeNode[0];
+ // Should not happen
+ return new KeyTreeNode[0];
}
}
/**
* @see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
- public void dispose() {}
+ public void dispose() {
+ }
/**
- * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(
- * org.eclipse.jface.viewers.Viewer,
- * java.lang.Object, java.lang.Object)
+ * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer,
+ * java.lang.Object, java.lang.Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
this.viewer = (TreeViewer) viewer;
this.keyTreeModel = (AbstractKeyTreeModel) newInput;
}
- public TreeType getTreeType() {
- return treeType;
- }
+ public TreeType getTreeType() {
+ return treeType;
+ }
- public void setTreeType(TreeType treeType) {
- if (this.treeType != treeType) {
- this.treeType = treeType;
- viewer.refresh();
- }
- }
+ public void setTreeType(TreeType treeType) {
+ if (this.treeType != treeType) {
+ this.treeType = treeType;
+ viewer.refresh();
+ }
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContributor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContributor.java
index a9f7e21..ace9d7b 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContributor.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContributor.java
@@ -48,14 +48,14 @@
/**
* @author Pascal Essiembre
- *
+ *
*/
public class KeyTreeContributor implements IKeyTreeContributor {
- private MessagesEditor editor;
+ private MessagesEditor editor;
private AbstractKeyTreeModel treeModel;
private TreeType treeType;
-
+
/**
*
*/
@@ -70,152 +70,154 @@
*
*/
public void contribute(final TreeViewer treeViewer) {
-
- KeyTreeContentProvider contentProvider = new KeyTreeContentProvider(treeType);
- treeViewer.setContentProvider(contentProvider);
- ColumnViewerToolTipSupport.enableFor (treeViewer);
- treeViewer.setLabelProvider(new KeyTreeLabelProvider(editor, treeModel, contentProvider));
+
+ KeyTreeContentProvider contentProvider = new KeyTreeContentProvider(
+ treeType);
+ treeViewer.setContentProvider(contentProvider);
+ ColumnViewerToolTipSupport.enableFor(treeViewer);
+ treeViewer.setLabelProvider(new KeyTreeLabelProvider(editor, treeModel,
+ contentProvider));
if (treeViewer.getInput() == null)
treeViewer.setUseHashlookup(true);
-
+
ViewerFilter onlyUnusedAndMissingKeysFilter = new OnlyUnsuedAndMissingKey();
- ViewerFilter[] filters = {onlyUnusedAndMissingKeysFilter};
+ ViewerFilter[] filters = { onlyUnusedAndMissingKeysFilter };
treeViewer.setFilters(filters);
-// IKeyBindingService service = editor.getSite().getKeyBindingService();
-// service.setScopes(new String[]{"org.eclilpse.babel.editor.editor.tree"});
-
+ // IKeyBindingService service = editor.getSite().getKeyBindingService();
+ // service.setScopes(new
+ // String[]{"org.eclilpse.babel.editor.editor.tree"});
+
contributeActions(treeViewer);
contributeKeySync(treeViewer);
-
+
contributeModelChanges(treeViewer);
contributeDoubleClick(treeViewer);
contributeMarkers(treeViewer);
-
+
// Set input model
treeViewer.setInput(treeModel);
treeViewer.expandAll();
}
private class OnlyUnsuedAndMissingKey extends ViewerFilter implements
- AbstractKeyTreeModel.IKeyTreeNodeLeafFilter {
+ AbstractKeyTreeModel.IKeyTreeNodeLeafFilter {
/*
* (non-Javadoc)
*
- * @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer,
- * java.lang.Object, java.lang.Object)
+ * @see
+ * org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers
+ * .Viewer, java.lang.Object, java.lang.Object)
*/
public boolean select(Viewer viewer, Object parentElement,
Object element) {
- if (editor.isShowOnlyUnusedAndMissingKeys() == IMessagesEditorChangeListener.SHOW_ALL
- || !(element instanceof KeyTreeNode)) {
- //no filtering. the element is displayed by default.
- return true;
- }
- if (editor.getI18NPage() != null && editor.getI18NPage().isKeyTreeVisible()) {
- return editor.getKeyTreeModel().isBranchFiltered(this, (KeyTreeNode)element);
- } else {
- return isFilteredLeaf((KeyTreeNode)element);
- }
+ if (editor.isShowOnlyUnusedAndMissingKeys() == IMessagesEditorChangeListener.SHOW_ALL
+ || !(element instanceof KeyTreeNode)) {
+ // no filtering. the element is displayed by default.
+ return true;
+ }
+ if (editor.getI18NPage() != null
+ && editor.getI18NPage().isKeyTreeVisible()) {
+ return editor.getKeyTreeModel().isBranchFiltered(this,
+ (KeyTreeNode) element);
+ } else {
+ return isFilteredLeaf((KeyTreeNode) element);
+ }
}
-
- /**
- * @param node
- * @return true if this node should be in the filter. Does not navigate the tree
- * of KeyTreeNode. false unless the node is a missing or unused key.
- */
- public boolean isFilteredLeaf(IKeyTreeNode node) {
- MessagesEditorMarkers markers = KeyTreeContributor.this.editor.getMarkers();
- String key = node.getMessageKey();
- boolean missingOrUnused = markers.isMissingOrUnusedKey(key);
- if (!missingOrUnused) {
- return false;
- }
- switch (editor.isShowOnlyUnusedAndMissingKeys()) {
- case IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED:
- return missingOrUnused;
- case IMessagesEditorChangeListener.SHOW_ONLY_MISSING:
- return !markers.isUnusedKey(key, missingOrUnused);
- case IMessagesEditorChangeListener.SHOW_ONLY_UNUSED:
- return markers.isUnusedKey(key, missingOrUnused);
- default:
- return false;
- }
- }
-
- }
+ /**
+ * @param node
+ * @return true if this node should be in the filter. Does not navigate
+ * the tree of KeyTreeNode. false unless the node is a missing
+ * or unused key.
+ */
+ public boolean isFilteredLeaf(IKeyTreeNode node) {
+ MessagesEditorMarkers markers = KeyTreeContributor.this.editor
+ .getMarkers();
+ String key = node.getMessageKey();
+ boolean missingOrUnused = markers.isMissingOrUnusedKey(key);
+ if (!missingOrUnused) {
+ return false;
+ }
+ switch (editor.isShowOnlyUnusedAndMissingKeys()) {
+ case IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED:
+ return missingOrUnused;
+ case IMessagesEditorChangeListener.SHOW_ONLY_MISSING:
+ return !markers.isUnusedKey(key, missingOrUnused);
+ case IMessagesEditorChangeListener.SHOW_ONLY_UNUSED:
+ return markers.isUnusedKey(key, missingOrUnused);
+ default:
+ return false;
+ }
+ }
+
+ }
/**
* Contributes markers.
- * @param treeViewer tree viewer
+ *
+ * @param treeViewer
+ * tree viewer
*/
private void contributeMarkers(final TreeViewer treeViewer) {
editor.getMarkers().addObserver(new Observer() {
public void update(Observable o, Object arg) {
- Display.getDefault().asyncExec(new Runnable(){
- public void run() {
- treeViewer.refresh();
- }
- });
+ Display.getDefault().asyncExec(new Runnable() {
+ public void run() {
+ treeViewer.refresh();
+ }
+ });
}
});
-// editor.addChangeListener(new MessagesEditorChangeAdapter() {
-// public void editorDisposed() {
-// editor.getMarkers().clear();
-// }
-// });
+ // editor.addChangeListener(new MessagesEditorChangeAdapter() {
+ // public void editorDisposed() {
+ // editor.getMarkers().clear();
+ // }
+ // });
-
-
-
-
-
-
-
-// final IMarkerListener markerListener = new IMarkerListener() {
-// public void markerAdded(IMarker marker) {
-// PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable () {
-// public void run() {
-// if (!PlatformUI.getWorkbench().getDisplay().isDisposed()) {
-// treeViewer.refresh(true);
-// }
-// }
-// });
-// }
-// public void markerRemoved(IMarker marker) {
-// PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable () {
-// public void run() {
-// if (!PlatformUI.getWorkbench().getDisplay().isDisposed()) {
-// treeViewer.refresh(true);
-// }
-// }
-// });
-// }
-// };
-// editor.getMarkerManager().addMarkerListener(markerListener);
-// editor.addChangeListener(new MessagesEditorChangeAdapter() {
-// public void editorDisposed() {
-// editor.getMarkerManager().removeMarkerListener(markerListener);
-// }
-// });
+ // final IMarkerListener markerListener = new IMarkerListener() {
+ // public void markerAdded(IMarker marker) {
+ // PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable () {
+ // public void run() {
+ // if (!PlatformUI.getWorkbench().getDisplay().isDisposed()) {
+ // treeViewer.refresh(true);
+ // }
+ // }
+ // });
+ // }
+ // public void markerRemoved(IMarker marker) {
+ // PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable () {
+ // public void run() {
+ // if (!PlatformUI.getWorkbench().getDisplay().isDisposed()) {
+ // treeViewer.refresh(true);
+ // }
+ // }
+ // });
+ // }
+ // };
+ // editor.getMarkerManager().addMarkerListener(markerListener);
+ // editor.addChangeListener(new MessagesEditorChangeAdapter() {
+ // public void editorDisposed() {
+ // editor.getMarkerManager().removeMarkerListener(markerListener);
+ // }
+ // });
}
-
-
/**
* Contributes double-click support, expanding/collapsing nodes.
- * @param treeViewer tree viewer
+ *
+ * @param treeViewer
+ * tree viewer
*/
private void contributeDoubleClick(final TreeViewer treeViewer) {
treeViewer.getTree().addMouseListener(new MouseAdapter() {
public void mouseDoubleClick(MouseEvent event) {
- IStructuredSelection selection =
- (IStructuredSelection) treeViewer.getSelection();
+ IStructuredSelection selection = (IStructuredSelection) treeViewer
+ .getSelection();
Object element = selection.getFirstElement();
if (treeViewer.isExpandable(element)) {
if (treeViewer.getExpandedState(element)) {
@@ -230,57 +232,65 @@
/**
* Contributes key synchronization between editor and tree selected keys.
- * @param treeViewer tree viewer
+ *
+ * @param treeViewer
+ * tree viewer
*/
private void contributeModelChanges(final TreeViewer treeViewer) {
final IKeyTreeModelListener keyTreeListener = new IKeyTreeModelListener() {
- //TODO be smarter about refreshes.
+ // TODO be smarter about refreshes.
public void nodeAdded(KeyTreeNode node) {
- Display.getDefault().asyncExec(new Runnable(){
- public void run() {
- treeViewer.refresh(true);
- }
- });
+ Display.getDefault().asyncExec(new Runnable() {
+ public void run() {
+ treeViewer.refresh(true);
+ }
+ });
};
-// public void nodeChanged(KeyTreeNode node) {
-// treeViewer.refresh(true);
-// };
+
+ // public void nodeChanged(KeyTreeNode node) {
+ // treeViewer.refresh(true);
+ // };
public void nodeRemoved(KeyTreeNode node) {
- Display.getDefault().asyncExec(new Runnable(){
- public void run() {
- treeViewer.refresh(true);
- }
- });
+ Display.getDefault().asyncExec(new Runnable() {
+ public void run() {
+ treeViewer.refresh(true);
+ }
+ });
};
};
treeModel.addKeyTreeModelListener(keyTreeListener);
editor.addChangeListener(new MessagesEditorChangeAdapter() {
- public void keyTreeModelChanged(AbstractKeyTreeModel oldModel, AbstractKeyTreeModel newModel) {
+ public void keyTreeModelChanged(AbstractKeyTreeModel oldModel,
+ AbstractKeyTreeModel newModel) {
oldModel.removeKeyTreeModelListener(keyTreeListener);
newModel.addKeyTreeModelListener(keyTreeListener);
treeViewer.setInput(newModel);
treeViewer.refresh();
}
- public void showOnlyUnusedAndMissingChanged(int hideEverythingElse) {
- treeViewer.refresh();
+
+ public void showOnlyUnusedAndMissingChanged(int hideEverythingElse) {
+ treeViewer.refresh();
}
});
}
/**
* Contributes key synchronization between editor and tree selected keys.
- * @param treeViewer tree viewer
+ *
+ * @param treeViewer
+ * tree viewer
*/
private void contributeKeySync(final TreeViewer treeViewer) {
// changes in tree selected key update the editor
treeViewer.getTree().addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
- IStructuredSelection selection =
- (IStructuredSelection) treeViewer.getSelection();
+ IStructuredSelection selection = (IStructuredSelection) treeViewer
+ .getSelection();
if (selection != null && selection.getFirstElement() != null) {
- KeyTreeNode node =
- (KeyTreeNode) selection.getFirstElement();
- System.out.println("viewer key/hash:" + node.getMessageKey() + "/" + node.hashCode());
+ KeyTreeNode node = (KeyTreeNode) selection
+ .getFirstElement();
+ System.out.println("viewer key/hash:"
+ + node.getMessageKey() + "/" + node.hashCode());
editor.setSelectedKey(node.getMessageKey());
} else {
editor.setSelectedKey(null);
@@ -290,35 +300,35 @@
// changes in editor selected key updates the tree
editor.addChangeListener(new MessagesEditorChangeAdapter() {
public void selectedKeyChanged(String oldKey, String newKey) {
- ITreeContentProvider provider =
- (ITreeContentProvider) treeViewer.getContentProvider();
+ ITreeContentProvider provider = (ITreeContentProvider) treeViewer
+ .getContentProvider();
if (provider != null) { // alst workaround
- KeyTreeNode node = findKeyTreeNode(
- provider, provider.getElements(null), newKey);
-
- // String[] test = newKey.split("\\.");
- // treeViewer.setSelection(new StructuredSelection(test), true);
-
-
- if (node != null) {
- treeViewer.setSelection(new StructuredSelection(node),
- true);
- treeViewer.getTree().showSelection();
- }
+ KeyTreeNode node = findKeyTreeNode(provider,
+ provider.getElements(null), newKey);
+
+ // String[] test = newKey.split("\\.");
+ // treeViewer.setSelection(new StructuredSelection(test),
+ // true);
+
+ if (node != null) {
+ treeViewer.setSelection(new StructuredSelection(node),
+ true);
+ treeViewer.getTree().showSelection();
+ }
}
}
});
}
-
-
/**
* Contributes actions to the tree.
- * @param treeViewer tree viewer
+ *
+ * @param treeViewer
+ * tree viewer
*/
private void contributeActions(final TreeViewer treeViewer) {
Tree tree = treeViewer.getTree();
-
+
// Add menu
MenuManager menuManager = new MenuManager();
Menu menu = menuManager.createContextMenu(tree);
@@ -332,10 +342,10 @@
// Rename
final IAction renameAction = new RenameKeyAction(editor, treeViewer);
menuManager.add(renameAction);
-
+
menuManager.update(true);
tree.setMenu(menu);
-
+
// Bind actions to tree
tree.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
@@ -347,9 +357,9 @@
}
});
}
-
- private KeyTreeNode findKeyTreeNode(
- ITreeContentProvider provider, Object[] nodes, String key) {
+
+ private KeyTreeNode findKeyTreeNode(ITreeContentProvider provider,
+ Object[] nodes, String key) {
for (int i = 0; i < nodes.length; i++) {
KeyTreeNode node = (KeyTreeNode) nodes[i];
if (node.getMessageKey().equals(key)) {
@@ -366,10 +376,10 @@
public IKeyTreeNode getKeyTreeNode(String key) {
return getKeyTreeNode(key, null);
}
-
+
// TODO, think about a hashmap
private IKeyTreeNode getKeyTreeNode(String key, IKeyTreeNode node) {
- if (node == null) {
+ if (node == null) {
for (IKeyTreeNode ktn : treeModel.getRootNodes()) {
String id = ktn.getMessageKey();
if (key.equals(id)) {
@@ -394,5 +404,5 @@
public IKeyTreeNode[] getRootKeyItems() {
return treeModel.getRootNodes();
}
-
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeLabelProvider.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeLabelProvider.java
index ef4bfaa..1a9b6ce 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeLabelProvider.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeLabelProvider.java
@@ -35,146 +35,151 @@
/**
* Label provider for key tree viewer.
+ *
* @author Pascal Essiembre
*/
-public class KeyTreeLabelProvider
- extends ColumnLabelProvider implements IFontProvider, IColorProvider {
+public class KeyTreeLabelProvider extends ColumnLabelProvider implements
+ IFontProvider, IColorProvider {
private static final int KEY_DEFAULT = 1 << 1;
private static final int KEY_COMMENTED = 1 << 2;
private static final int KEY_VIRTUAL = 1 << 3;
private static final int BADGE_WARNING = 1 << 4;
private static final int BADGE_WARNING_GREY = 1 << 5;
-
+
/** Registry instead of UIUtils one for image not keyed by file name. */
private static ImageRegistry imageRegistry = new ImageRegistry();
-
private MessagesEditor editor;
private MessagesBundleGroup messagesBundleGroup;
/**
- * This label provider keeps a reference to the content provider.
- * This is only because the way the nodes are labeled depends on whether
- * the node is being displayed in a tree or a flat structure.
+ * This label provider keeps a reference to the content provider. This is
+ * only because the way the nodes are labeled depends on whether the node is
+ * being displayed in a tree or a flat structure.
* <P>
* This label provider does not have to listen to changes in the tree/flat
- * selection because such a change would cause the content provider to do
- * a full refresh anyway.
+ * selection because such a change would cause the content provider to do a
+ * full refresh anyway.
*/
private KeyTreeContentProvider contentProvider;
- /**
+ /**
*
*/
- public KeyTreeLabelProvider(
- MessagesEditor editor,
+ public KeyTreeLabelProvider(MessagesEditor editor,
AbstractKeyTreeModel treeModel,
KeyTreeContentProvider contentProvider) {
super();
this.editor = editor;
this.messagesBundleGroup = editor.getBundleGroup();
- this.contentProvider = contentProvider;
+ this.contentProvider = contentProvider;
}
/**
- * @see ILabelProvider#getImage(Object)
- */
- public Image getImage(Object element) {
- if (element instanceof KeyTreeNode) {
- KeyTreeNode node = (KeyTreeNode)element;
- Collection<IMessageCheck> c = editor.getMarkers().getFailedChecks(node.getMessageKey());
- if (c == null || c.isEmpty()) {
- // Return the default key image as no issue exists
- return UIUtils.getKeyImage();
- }
- if (editor.getMarkers().isUnusedKey(node.getMessageKey(), false)) {
- if (editor.getMarkers().isMissingKey(node.getMessageKey())){
- return UIUtils.getMissingAndUnusedTranslationsImage();
- } else if (editor.getMarkers().isDuplicateValue(node.getMessageKey())) {
- return UIUtils.getDuplicateEntryAndUnusedTranslationsImage();
- }
- return UIUtils.getUnusedTranslationsImage();
- } else if (editor.getMarkers().isMissingKey(node.getMessageKey())){
- return UIUtils.getMissingTranslationImage();
- } else if (editor.getMarkers().isDuplicateValue(node.getMessageKey())) {
- return UIUtils.getDuplicateEntryImage();
- }
-
- // This shouldnt happen, but just in case a default key with a warning icon will be showed
- Image someWarning = UIUtils.getKeyImage();
- ImageDescriptor warning = ImageDescriptor.createFromImage(UIUtils.getImage(UIUtils.IMAGE_WARNING));
- someWarning = new DecorationOverlayIcon(someWarning, warning, IDecoration.BOTTOM_RIGHT).createImage();
- return someWarning;
- //return UIUtils.getImage(UIUtils.IMAGE_WARNED_TRANSLATION);
- } else {
-/* // Figure out background icon
- if (messagesBundleGroup.isMessageKey(key)) {
- //TODO create check (or else)
-// if (!noInactiveKeyCheck.checkKey(messagesBundleGroup, node.getPath())) {
-// iconFlags += KEY_COMMENTED;
-// } else {
- iconFlags += KEY_DEFAULT;
-
-// }
- } else {
- iconFlags += KEY_VIRTUAL;
- }*/
-
- return UIUtils.getKeyImage();
-
- }
- }
+ * @see ILabelProvider#getImage(Object)
+ */
+ public Image getImage(Object element) {
+ if (element instanceof KeyTreeNode) {
+ KeyTreeNode node = (KeyTreeNode) element;
+ Collection<IMessageCheck> c = editor.getMarkers().getFailedChecks(
+ node.getMessageKey());
+ if (c == null || c.isEmpty()) {
+ // Return the default key image as no issue exists
+ return UIUtils.getKeyImage();
+ }
+ if (editor.getMarkers().isUnusedKey(node.getMessageKey(), false)) {
+ if (editor.getMarkers().isMissingKey(node.getMessageKey())) {
+ return UIUtils.getMissingAndUnusedTranslationsImage();
+ } else if (editor.getMarkers().isDuplicateValue(
+ node.getMessageKey())) {
+ return UIUtils
+ .getDuplicateEntryAndUnusedTranslationsImage();
+ }
+ return UIUtils.getUnusedTranslationsImage();
+ } else if (editor.getMarkers().isMissingKey(node.getMessageKey())) {
+ return UIUtils.getMissingTranslationImage();
+ } else if (editor.getMarkers().isDuplicateValue(
+ node.getMessageKey())) {
+ return UIUtils.getDuplicateEntryImage();
+ }
+ // This shouldnt happen, but just in case a default key with a
+ // warning icon will be showed
+ Image someWarning = UIUtils.getKeyImage();
+ ImageDescriptor warning = ImageDescriptor.createFromImage(UIUtils
+ .getImage(UIUtils.IMAGE_WARNING));
+ someWarning = new DecorationOverlayIcon(someWarning, warning,
+ IDecoration.BOTTOM_RIGHT).createImage();
+ return someWarning;
+ // return UIUtils.getImage(UIUtils.IMAGE_WARNED_TRANSLATION);
+ } else {
+ /*
+ * // Figure out background icon if
+ * (messagesBundleGroup.isMessageKey(key)) { //TODO create check (or
+ * else) // if (!noInactiveKeyCheck.checkKey(messagesBundleGroup,
+ * node.getPath())) { // iconFlags += KEY_COMMENTED; // } else {
+ * iconFlags += KEY_DEFAULT;
+ *
+ * // } } else { iconFlags += KEY_VIRTUAL; }
+ */
- /**
- * @see ILabelProvider#getText(Object)
- */
- public String getText(Object element) {
- /*
- * We look to the content provider to see if the node is being
- * displayed in flat or tree mode.
- */
+ return UIUtils.getKeyImage();
+
+ }
+ }
+
+ /**
+ * @see ILabelProvider#getText(Object)
+ */
+ public String getText(Object element) {
+ /*
+ * We look to the content provider to see if the node is being displayed
+ * in flat or tree mode.
+ */
KeyTreeNode node = (KeyTreeNode) element;
switch (contentProvider.getTreeType()) {
case Tree:
- return node.getName();
+ return node.getName();
case Flat:
- return node.getMessageKey();
- default:
- // Should not happen
- return "error";
+ return node.getMessageKey();
+ default:
+ // Should not happen
+ return "error";
}
- }
-
- public String getToolTipText(Object element) {
- if (element instanceof KeyTreeNode) {
- KeyTreeNode node = (KeyTreeNode)element;
- Collection<IMessageCheck> c = editor.getMarkers().getFailedChecks(node.getMessageKey());
- if (c == null || c.isEmpty()) {
- return null;
- }
- boolean isMissingOrUnused = editor.getMarkers().isMissingOrUnusedKey(node.getMessageKey());
- if (isMissingOrUnused) {
- if (editor.getMarkers().isUnusedKey(node.getMessageKey(), isMissingOrUnused)) {
- return "This Locale is unused";
- } else {
- return "This Locale has missing translations";
- }
- }
- if (editor.getMarkers().isDuplicateValue(node.getMessageKey())) {
- return "This Locale has a duplicate value";
- }
- }
- return null;
- }
+ }
+
+ public String getToolTipText(Object element) {
+ if (element instanceof KeyTreeNode) {
+ KeyTreeNode node = (KeyTreeNode) element;
+ Collection<IMessageCheck> c = editor.getMarkers().getFailedChecks(
+ node.getMessageKey());
+ if (c == null || c.isEmpty()) {
+ return null;
+ }
+ boolean isMissingOrUnused = editor.getMarkers()
+ .isMissingOrUnusedKey(node.getMessageKey());
+ if (isMissingOrUnused) {
+ if (editor.getMarkers().isUnusedKey(node.getMessageKey(),
+ isMissingOrUnused)) {
+ return "This Locale is unused";
+ } else {
+ return "This Locale has missing translations";
+ }
+ }
+ if (editor.getMarkers().isDuplicateValue(node.getMessageKey())) {
+ return "This Locale has a duplicate value";
+ }
+ }
+ return null;
+ }
/**
* @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
*/
- public void dispose() {
-//TODO imageRegistry.dispose(); could do if version 3.1
- }
+ public void dispose() {
+ // TODO imageRegistry.dispose(); could do if version 3.1
+ }
/**
* @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object)
@@ -196,9 +201,10 @@
public Color getBackground(Object element) {
return null;
}
-
+
/**
- * Generates an image based on icon flags.
+ * Generates an image based on icon flags.
+ *
* @param iconFlags
* @return generated image
*/
@@ -213,7 +219,7 @@
} else {
image = getRegistryImage("keyDefault.png"); //$NON-NLS-1$
}
-
+
// Add warning icon
if ((iconFlags & BADGE_WARNING) != 0) {
image = overlayImage(image, "warning.gif", //$NON-NLS-1$
@@ -225,18 +231,19 @@
}
return image;
}
-
- private Image overlayImage(
- Image baseImage, String imageName, int location, int iconFlags) {
- /* To obtain a unique key, we assume here that the baseImage and
- * location are always the same for each imageName and keyFlags
+
+ private Image overlayImage(Image baseImage, String imageName, int location,
+ int iconFlags) {
+ /*
+ * To obtain a unique key, we assume here that the baseImage and
+ * location are always the same for each imageName and keyFlags
* combination.
*/
String imageKey = imageName + iconFlags;
Image image = imageRegistry.get(imageKey);
if (image == null) {
- image = new OverlayImageIcon(baseImage, getRegistryImage(
- imageName), location).createImage();
+ image = new OverlayImageIcon(baseImage,
+ getRegistryImage(imageName), location).createImage();
imageRegistry.put(imageKey, image);
}
return image;
@@ -253,8 +260,8 @@
private boolean isOneChildrenMarked(IKeyTreeNode parentNode) {
MessagesEditorMarkers markers = editor.getMarkers();
- IKeyTreeNode[] childNodes =
- editor.getKeyTreeModel().getChildren(parentNode);
+ IKeyTreeNode[] childNodes = editor.getKeyTreeModel().getChildren(
+ parentNode);
for (int i = 0; i < childNodes.length; i++) {
IKeyTreeNode node = childNodes[i];
if (markers.isMarked(node.getMessageKey())) {
@@ -266,6 +273,5 @@
}
return false;
}
-
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/OverlayImageIcon.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/OverlayImageIcon.java
index 248113b..bd3923d 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/OverlayImageIcon.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/OverlayImageIcon.java
@@ -37,50 +37,53 @@
/**
* Constructor.
- * @param baseImage background image
- * @param overlayImage the image to put on top of background image
- * @param location in which corner to put the icon
+ *
+ * @param baseImage
+ * background image
+ * @param overlayImage
+ * the image to put on top of background image
+ * @param location
+ * in which corner to put the icon
*/
public OverlayImageIcon(Image baseImage, Image overlayImage, int location) {
super();
this.baseImage = baseImage;
this.overlayImage = overlayImage;
this.location = location;
- this.imgSize = new Point(
- baseImage.getImageData().width,
+ this.imgSize = new Point(baseImage.getImageData().width,
baseImage.getImageData().height);
}
/**
* @see org.eclipse.jface.resource.CompositeImageDescriptor
- * #drawCompositeImage(int, int)
+ * #drawCompositeImage(int, int)
*/
protected void drawCompositeImage(int width, int height) {
// Draw the base image
- drawImage(baseImage.getImageData(), 0, 0);
+ drawImage(baseImage.getImageData(), 0, 0);
ImageData imageData = overlayImage.getImageData();
- switch(location) {
- // Draw on the top left corner
- case TOP_LEFT:
- drawImage(imageData, 0, 0);
- break;
-
- // Draw on top right corner
- case TOP_RIGHT:
- drawImage(imageData, imgSize.x - imageData.width, 0);
- break;
-
- // Draw on bottom left
- case BOTTOM_LEFT:
- drawImage(imageData, 0, imgSize.y - imageData.height);
- break;
-
- // Draw on bottom right corner
- case BOTTOM_RIGHT:
- drawImage(imageData, imgSize.x - imageData.width,
- imgSize.y - imageData.height);
- break;
-
+ switch (location) {
+ // Draw on the top left corner
+ case TOP_LEFT:
+ drawImage(imageData, 0, 0);
+ break;
+
+ // Draw on top right corner
+ case TOP_RIGHT:
+ drawImage(imageData, imgSize.x - imageData.width, 0);
+ break;
+
+ // Draw on bottom left
+ case BOTTOM_LEFT:
+ drawImage(imageData, 0, imgSize.y - imageData.height);
+ break;
+
+ // Draw on bottom right corner
+ case BOTTOM_RIGHT:
+ drawImage(imageData, imgSize.x - imageData.width, imgSize.y
+ - imageData.height);
+ break;
+
}
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/UIUtils.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/UIUtils.java
index ae6e38a..2677626 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/UIUtils.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/UIUtils.java
@@ -55,88 +55,67 @@
/**
* Utility methods related to application UI.
+ *
* @author Pascal Essiembre
*/
public final class UIUtils {
-
/** Name of resource bundle image. */
- public static final String IMAGE_RESOURCE_BUNDLE =
- "resourcebundle.gif"; //$NON-NLS-1$
+ public static final String IMAGE_RESOURCE_BUNDLE = "resourcebundle.gif"; //$NON-NLS-1$
/** Name of properties file image. */
- public static final String IMAGE_PROPERTIES_FILE =
- "propertiesfile.gif"; //$NON-NLS-1$
+ public static final String IMAGE_PROPERTIES_FILE = "propertiesfile.gif"; //$NON-NLS-1$
/** Name of new properties file image. */
- public static final String IMAGE_NEW_PROPERTIES_FILE =
- "newpropertiesfile.gif"; //$NON-NLS-1$
+ public static final String IMAGE_NEW_PROPERTIES_FILE = "newpropertiesfile.gif"; //$NON-NLS-1$
/** Name of hierarchical layout image. */
- public static final String IMAGE_LAYOUT_HIERARCHICAL =
- "hierarchicalLayout.gif"; //$NON-NLS-1$
+ public static final String IMAGE_LAYOUT_HIERARCHICAL = "hierarchicalLayout.gif"; //$NON-NLS-1$
/** Name of flat layout image. */
- public static final String IMAGE_LAYOUT_FLAT =
- "flatLayout.gif"; //$NON-NLS-1$
+ public static final String IMAGE_LAYOUT_FLAT = "flatLayout.gif"; //$NON-NLS-1$
/** Name of add icon. */
- public static final String IMAGE_ADD = "add.png"; //$NON-NLS-1$
+ public static final String IMAGE_ADD = "add.png"; //$NON-NLS-1$
/** Name of edit icon. */
- public static final String IMAGE_RENAME = "rename.gif"; //$NON-NLS-1$
+ public static final String IMAGE_RENAME = "rename.gif"; //$NON-NLS-1$
/** Name of "view left" icon. */
- public static final String IMAGE_VIEW_LEFT = "viewLeft.gif"; //$NON-NLS-1$
+ public static final String IMAGE_VIEW_LEFT = "viewLeft.gif"; //$NON-NLS-1$
/** Name of locale icon. */
- public static final String IMAGE_LOCALE = "locale.gif"; //$NON-NLS-1$
+ public static final String IMAGE_LOCALE = "locale.gif"; //$NON-NLS-1$
/** Name of new locale icon. */
- public static final String IMAGE_NEW_LOCALE =
- "newLocale.gif"; //$NON-NLS-1$
+ public static final String IMAGE_NEW_LOCALE = "newLocale.gif"; //$NON-NLS-1$
/** Name of expand all icon. */
- public static final String IMAGE_EXPAND_ALL =
- "expandall.png"; //$NON-NLS-1$
+ public static final String IMAGE_EXPAND_ALL = "expandall.png"; //$NON-NLS-1$
/** Name of collapse all icon. */
- public static final String IMAGE_COLLAPSE_ALL =
- "collapseall.png"; //$NON-NLS-1$
+ public static final String IMAGE_COLLAPSE_ALL = "collapseall.png"; //$NON-NLS-1$
-
- public static final String IMAGE_KEY =
- "keyDefault.png"; //$NON-NLS-1$
- public static final String IMAGE_INCOMPLETE_ENTRIES =
- "incomplete.gif"; //$NON-NLS-1$
- public static final String IMAGE_EMPTY =
- "empty.gif"; //$NON-NLS-1$
- public static final String IMAGE_MISSING_TRANSLATION =
- "missing_translation.gif"; //$NON-NLS-1$
- public static final String IMAGE_UNUSED_TRANSLATION =
- "unused_translation.png"; //$NON-NLS-1$
- public static final String IMAGE_UNUSED_AND_MISSING_TRANSLATIONS =
- "unused_and_missing_translations.png"; //$NON-NLS-1$
- public static final String IMAGE_WARNED_TRANSLATION =
- "warned_translation.png"; //$NON-NLS-1$
- public static final String IMAGE_DUPLICATE =
- "duplicate.gif"; //$NON-NLS-1$
-
- public static final String IMAGE_WARNING =
- "warning.gif"; //$NON-NLS-1$
- public static final String IMAGE_ERROR =
- "error_co.gif"; //$NON-NLS-1$
-
-
+ public static final String IMAGE_KEY = "keyDefault.png"; //$NON-NLS-1$
+ public static final String IMAGE_INCOMPLETE_ENTRIES = "incomplete.gif"; //$NON-NLS-1$
+ public static final String IMAGE_EMPTY = "empty.gif"; //$NON-NLS-1$
+ public static final String IMAGE_MISSING_TRANSLATION = "missing_translation.gif"; //$NON-NLS-1$
+ public static final String IMAGE_UNUSED_TRANSLATION = "unused_translation.png"; //$NON-NLS-1$
+ public static final String IMAGE_UNUSED_AND_MISSING_TRANSLATIONS = "unused_and_missing_translations.png"; //$NON-NLS-1$
+ public static final String IMAGE_WARNED_TRANSLATION = "warned_translation.png"; //$NON-NLS-1$
+ public static final String IMAGE_DUPLICATE = "duplicate.gif"; //$NON-NLS-1$
+
+ public static final String IMAGE_WARNING = "warning.gif"; //$NON-NLS-1$
+ public static final String IMAGE_ERROR = "error_co.gif"; //$NON-NLS-1$
+
/** Image registry. */
private static final ImageRegistry imageRegistry =
- //TODO: REMOVE this comment eventually:
- //necessary to specify the display otherwise Display.getCurrent()
- //is called and will return null if this is not the UI-thread.
- //this happens if the builder is called and initialize this class:
- //the thread will not be the UI-thread.
- new ImageRegistry(PlatformUI.getWorkbench().getDisplay());
+ // TODO: REMOVE this comment eventually:
+ // necessary to specify the display otherwise Display.getCurrent()
+ // is called and will return null if this is not the UI-thread.
+ // this happens if the builder is called and initialize this class:
+ // the thread will not be the UI-thread.
+ new ImageRegistry(PlatformUI.getWorkbench().getDisplay());
public static final String PDE_NATURE = "org.eclipse.pde.PluginNature"; //$NON-NLS-1$
public static final String JDT_JAVA_NATURE = "org.eclipse.jdt.core.javanature"; //$NON-NLS-1$
-
-
+
/**
- * The root locale used for the original properties file.
- * This constant is defined in java.util.Local starting with jdk6.
+ * The root locale used for the original properties file. This constant is
+ * defined in java.util.Local starting with jdk6.
*/
public static final Locale ROOT_LOCALE = new Locale(""); //$NON-NLS-1$
-
+
/**
* Sort the Locales alphabetically. Make sure the root Locale is first.
*
@@ -165,78 +144,82 @@
};
Collections.sort(localesList, comp);
for (int i = 0; i < locales.length; i++) {
- locales[i] = localesList.get(i);
+ locales[i] = localesList.get(i);
}
}
-
+
/**
* @param locale
- * @return true if the locale is selected by the local-filter defined in the rpeferences
+ * @return true if the locale is selected by the local-filter defined in the
+ * rpeferences
* @see MsgEditorPreferences#getFilterLocalesStringMatcher()
*/
public static boolean isDisplayed(Locale locale) {
- if (ROOT_LOCALE.equals(locale) || locale == null) {
- return true;
- }
- StringMatcher[] patterns =
- MsgEditorPreferences.getInstance().getFilterLocalesStringMatchers();
- if (patterns == null || patterns.length == 0) {
- return true;
- }
- String locStr = locale.toString();
- for (int i = 0; i < patterns.length; i++) {
- if (patterns[i].match(locStr)) {
- return true;
- }
- }
- return false;
+ if (ROOT_LOCALE.equals(locale) || locale == null) {
+ return true;
+ }
+ StringMatcher[] patterns = MsgEditorPreferences.getInstance()
+ .getFilterLocalesStringMatchers();
+ if (patterns == null || patterns.length == 0) {
+ return true;
+ }
+ String locStr = locale.toString();
+ for (int i = 0; i < patterns.length; i++) {
+ if (patterns[i].match(locStr)) {
+ return true;
+ }
+ }
+ return false;
}
-
+
/**
- * Reads the filter of locales in the preferences and apply it
- * to filter the passed locales.
+ * Reads the filter of locales in the preferences and apply it to filter the
+ * passed locales.
+ *
* @param locales
- * @return The new collection of locales; removed the ones not selected by the preferences.
+ * @return The new collection of locales; removed the ones not selected by
+ * the preferences.
*/
public static Locale[] filterLocales(Locale[] locales) {
- StringMatcher[] patterns =
- MsgEditorPreferences.getInstance().getFilterLocalesStringMatchers();
- Set<Locale> already = new HashSet<Locale>();
- //first look for the root locale:
- ArrayList<Locale> result = new ArrayList<Locale>();
- for (int j = 0; j < locales.length; j++) {
- Locale loc = locales[j];
- if (ROOT_LOCALE.equals(loc) || loc == null) {
- already.add(loc);
- result.add(loc);
- break;
- }
- }
- //now go through each pattern until already indexed locales found all locales
- //or we run out of locales.
- for (int pi = 0; pi < patterns.length; pi++) {
- StringMatcher pattern = patterns[pi];
- for (int j = 0; j < locales.length; j++) {
- Locale loc = locales[j];
- if (!already.contains(loc)) {
- if (pattern.match(loc.toString())) {
- already.add(loc);
- result.add(loc);
- if (already.size() == locales.length) {
- for (int k = 0; k < locales.length; k++) {
- locales[k] = (Locale) result.get(k);
- }
- return locales;
- }
- }
- }
- }
- }
- Locale[] filtered = new Locale[result.size()];
- for (int k = 0; k < filtered.length; k++) {
- filtered[k] = result.get(k);
+ StringMatcher[] patterns = MsgEditorPreferences.getInstance()
+ .getFilterLocalesStringMatchers();
+ Set<Locale> already = new HashSet<Locale>();
+ // first look for the root locale:
+ ArrayList<Locale> result = new ArrayList<Locale>();
+ for (int j = 0; j < locales.length; j++) {
+ Locale loc = locales[j];
+ if (ROOT_LOCALE.equals(loc) || loc == null) {
+ already.add(loc);
+ result.add(loc);
+ break;
+ }
}
- return filtered;
+ // now go through each pattern until already indexed locales found all
+ // locales
+ // or we run out of locales.
+ for (int pi = 0; pi < patterns.length; pi++) {
+ StringMatcher pattern = patterns[pi];
+ for (int j = 0; j < locales.length; j++) {
+ Locale loc = locales[j];
+ if (!already.contains(loc)) {
+ if (pattern.match(loc.toString())) {
+ already.add(loc);
+ result.add(loc);
+ if (already.size() == locales.length) {
+ for (int k = 0; k < locales.length; k++) {
+ locales[k] = (Locale) result.get(k);
+ }
+ return locales;
+ }
+ }
+ }
+ }
+ }
+ Locale[] filtered = new Locale[result.size()];
+ for (int k = 0; k < filtered.length; k++) {
+ filtered[k] = result.get(k);
+ }
+ return filtered;
}
/**
@@ -247,28 +230,34 @@
}
/**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style (size is unaffected).
- * @param control control we base our font data on
- * @param style style to apply to the new font
+ * Creates a font by altering the font associated with the given control and
+ * applying the provided style (size is unaffected).
+ *
+ * @param control
+ * control we base our font data on
+ * @param style
+ * style to apply to the new font
* @return newly created font
*/
public static Font createFont(Control control, int style) {
- //TODO consider dropping in favor of control-less version?
+ // TODO consider dropping in favor of control-less version?
return createFont(control, style, 0);
}
-
/**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style and relative size.
- * @param control control we base our font data on
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
+ * Creates a font by altering the font associated with the given control and
+ * applying the provided style and relative size.
+ *
+ * @param control
+ * control we base our font data on
+ * @param style
+ * style to apply to the new font
+ * @param relSize
+ * size to add or remove from the control size
* @return newly created font
*/
public static Font createFont(Control control, int style, int relSize) {
- //TODO consider dropping in favor of control-less version?
+ // TODO consider dropping in favor of control-less version?
FontData[] fontData = control.getFont().getFontData();
for (int i = 0; i < fontData.length; i++) {
fontData[i].setHeight(fontData[i].getHeight() + relSize);
@@ -278,24 +267,30 @@
}
/**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
+ * Creates a font by altering the system font and applying the provided
+ * style and relative size.
+ *
+ * @param style
+ * style to apply to the new font
* @return newly created font
*/
public static Font createFont(int style) {
return createFont(style, 0);
}
-
+
/**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
+ * Creates a font by altering the system font and applying the provided
+ * style and relative size.
+ *
+ * @param style
+ * style to apply to the new font
+ * @param relSize
+ * size to add or remove from the control size
* @return newly created font
*/
public static Font createFont(int style, int relSize) {
- Display display = MessagesEditorPlugin.getDefault().getWorkbench().getDisplay();
+ Display display = MessagesEditorPlugin.getDefault().getWorkbench()
+ .getDisplay();
FontData[] fontData = display.getSystemFont().getFontData();
for (int i = 0; i < fontData.length; i++) {
fontData[i].setHeight(fontData[i].getHeight() + relSize);
@@ -306,31 +301,39 @@
/**
* Creates a cursor matching given style.
- * @param style style to apply to the new font
+ *
+ * @param style
+ * style to apply to the new font
* @return newly created cursor
*/
public static Cursor createCursor(int style) {
- Display display = MessagesEditorPlugin.getDefault().getWorkbench().getDisplay();
+ Display display = MessagesEditorPlugin.getDefault().getWorkbench()
+ .getDisplay();
return new Cursor(display, style);
}
-
+
/**
* Gets a system color.
- * @param colorId SWT constant
+ *
+ * @param colorId
+ * SWT constant
* @return system color
*/
public static Color getSystemColor(int colorId) {
- return MessagesEditorPlugin.getDefault().getWorkbench()
- .getDisplay().getSystemColor(colorId);
+ return MessagesEditorPlugin.getDefault().getWorkbench().getDisplay()
+ .getSystemColor(colorId);
}
-
+
/**
* Gets the approximate width required to display a given number of
* characters in a control.
- * @param control the control on which to get width
- * @param numOfChars the number of chars
+ *
+ * @param control
+ * the control on which to get width
+ * @param numOfChars
+ * the number of chars
* @return width
- */
+ */
public static int getWidthInChars(Control control, int numOfChars) {
GC gc = new GC(control);
Point extent = gc.textExtent("W");//$NON-NLS-1$
@@ -341,78 +344,86 @@
/**
* Gets the approximate height required to display a given number of
* characters in a control, assuming, they were laid out vertically.
- * @param control the control on which to get height
- * @param numOfChars the number of chars
+ *
+ * @param control
+ * the control on which to get height
+ * @param numOfChars
+ * the number of chars
* @return height
- */
+ */
public static int getHeightInChars(Control control, int numOfChars) {
GC gc = new GC(control);
Point extent = gc.textExtent("W");//$NON-NLS-1$
gc.dispose();
return numOfChars * extent.y;
}
-
+
/**
* Shows an error dialog based on the supplied arguments.
- * @param shell the shell
- * @param exception the core exception
- * @param msgKey key to the plugin message text
+ *
+ * @param shell
+ * the shell
+ * @param exception
+ * the core exception
+ * @param msgKey
+ * key to the plugin message text
*/
- public static void showErrorDialog(
- Shell shell, CoreException exception, String msgKey) {
+ public static void showErrorDialog(Shell shell, CoreException exception,
+ String msgKey) {
exception.printStackTrace();
- ErrorDialog.openError(
- shell,
- MessagesEditorPlugin.getString(msgKey),
- exception.getLocalizedMessage(),
- exception.getStatus());
+ ErrorDialog.openError(shell, MessagesEditorPlugin.getString(msgKey),
+ exception.getLocalizedMessage(), exception.getStatus());
}
-
+
/**
* Shows an error dialog based on the supplied arguments.
- * @param shell the shell
- * @param exception the core exception
- * @param msgKey key to the plugin message text
+ *
+ * @param shell
+ * the shell
+ * @param exception
+ * the core exception
+ * @param msgKey
+ * key to the plugin message text
*/
- public static void showErrorDialog(
- Shell shell, Exception exception, String msgKey) {
+ public static void showErrorDialog(Shell shell, Exception exception,
+ String msgKey) {
exception.printStackTrace();
- IStatus status = new Status(
- IStatus.ERROR,
- MessagesEditorPlugin.PLUGIN_ID,
- 0,
+ IStatus status = new Status(IStatus.ERROR,
+ MessagesEditorPlugin.PLUGIN_ID, 0,
MessagesEditorPlugin.getString(msgKey) + " " //$NON-NLS-1$
+ MessagesEditorPlugin.getString("error.seeLogs"), //$NON-NLS-1$
exception);
- ErrorDialog.openError(
- shell,
- MessagesEditorPlugin.getString(msgKey),
- exception.getLocalizedMessage(),
- status);
+ ErrorDialog.openError(shell, MessagesEditorPlugin.getString(msgKey),
+ exception.getLocalizedMessage(), status);
}
-
+
/**
* Gets a locale, null-safe, display name.
- * @param locale locale to get display name
+ *
+ * @param locale
+ * locale to get display name
* @return display name
*/
public static String getDisplayName(Locale locale) {
if (locale == null || ROOT_LOCALE.equals(locale)) {
- return MessagesEditorPlugin.getString("editor.i18nentry.rootlocale.label"); //$NON-NLS-1$
+ return MessagesEditorPlugin
+ .getString("editor.i18nentry.rootlocale.label"); //$NON-NLS-1$
}
return locale.getDisplayName();
}
/**
* Gets an image descriptor.
- * @param name image name
+ *
+ * @param name
+ * image name
* @return image descriptor
*/
public static ImageDescriptor getImageDescriptor(String name) {
String iconPath = "icons/"; //$NON-NLS-1$
try {
- URL installURL = MessagesEditorPlugin.getDefault().getBundle().getEntry(
- "/"); //$NON-NLS-1$
+ URL installURL = MessagesEditorPlugin.getDefault().getBundle()
+ .getEntry("/"); //$NON-NLS-1$
URL url = new URL(installURL, iconPath + name);
return ImageDescriptor.createFromURL(url);
} catch (MalformedURLException e) {
@@ -420,10 +431,12 @@
return ImageDescriptor.getMissingImageDescriptor();
}
}
-
+
/**
* Gets an image.
- * @param imageName image name
+ *
+ * @param imageName
+ * image name
* @return image
*/
public static Image getImage(String imageName) {
@@ -439,123 +452,143 @@
* @return Image for the icon that indicates a key with no issues
*/
public static Image getKeyImage() {
- Image image = UIUtils.getImage(UIUtils.IMAGE_KEY);
- return image;
+ Image image = UIUtils.getImage(UIUtils.IMAGE_KEY);
+ return image;
}
-
+
/**
- * @return Image for the icon which indicates a key that has missing translations
+ * @return Image for the icon which indicates a key that has missing
+ * translations
*/
public static Image getMissingTranslationImage() {
- Image image = UIUtils.getImage(UIUtils.IMAGE_KEY);
- ImageDescriptor missing = ImageDescriptor.createFromImage(UIUtils.getImage(UIUtils.IMAGE_ERROR));
- image = new DecorationOverlayIcon(image, missing, IDecoration.BOTTOM_RIGHT).createImage();
- return image;
+ Image image = UIUtils.getImage(UIUtils.IMAGE_KEY);
+ ImageDescriptor missing = ImageDescriptor.createFromImage(UIUtils
+ .getImage(UIUtils.IMAGE_ERROR));
+ image = new DecorationOverlayIcon(image, missing,
+ IDecoration.BOTTOM_RIGHT).createImage();
+ return image;
}
-
+
/**
* @return Image for the icon which indicates a key that is unused
*/
public static Image getUnusedTranslationsImage() {
- Image image = UIUtils.getImage(UIUtils.IMAGE_UNUSED_TRANSLATION);
- ImageDescriptor warning = ImageDescriptor.createFromImage(UIUtils.getImage(UIUtils.IMAGE_WARNING));
- image = new DecorationOverlayIcon(image, warning, IDecoration.BOTTOM_RIGHT).createImage();
- return image;
+ Image image = UIUtils.getImage(UIUtils.IMAGE_UNUSED_TRANSLATION);
+ ImageDescriptor warning = ImageDescriptor.createFromImage(UIUtils
+ .getImage(UIUtils.IMAGE_WARNING));
+ image = new DecorationOverlayIcon(image, warning,
+ IDecoration.BOTTOM_RIGHT).createImage();
+ return image;
}
-
+
/**
- * @return Image for the icon which indicates a key that has missing translations and is unused
+ * @return Image for the icon which indicates a key that has missing
+ * translations and is unused
*/
public static Image getMissingAndUnusedTranslationsImage() {
- Image image = UIUtils.getImage(UIUtils.IMAGE_UNUSED_TRANSLATION);
- ImageDescriptor missing = ImageDescriptor.createFromImage(UIUtils.getImage(UIUtils.IMAGE_ERROR));
- image = new DecorationOverlayIcon(image, missing, IDecoration.BOTTOM_RIGHT).createImage();
- return image;
+ Image image = UIUtils.getImage(UIUtils.IMAGE_UNUSED_TRANSLATION);
+ ImageDescriptor missing = ImageDescriptor.createFromImage(UIUtils
+ .getImage(UIUtils.IMAGE_ERROR));
+ image = new DecorationOverlayIcon(image, missing,
+ IDecoration.BOTTOM_RIGHT).createImage();
+ return image;
}
-
+
/**
- * @return Image for the icon which indicates a key that has duplicate entries
+ * @return Image for the icon which indicates a key that has duplicate
+ * entries
*/
public static Image getDuplicateEntryImage() {
- Image image = UIUtils.getImage(UIUtils.IMAGE_KEY);
- ImageDescriptor missing = ImageDescriptor.createFromImage(UIUtils.getImage(UIUtils.IMAGE_WARNING));
- image = new DecorationOverlayIcon(image, missing, IDecoration.BOTTOM_RIGHT).createImage();
- return image;
+ Image image = UIUtils.getImage(UIUtils.IMAGE_KEY);
+ ImageDescriptor missing = ImageDescriptor.createFromImage(UIUtils
+ .getImage(UIUtils.IMAGE_WARNING));
+ image = new DecorationOverlayIcon(image, missing,
+ IDecoration.BOTTOM_RIGHT).createImage();
+ return image;
}
-
+
/**
- * @return Image for the icon which indicates a key that has duplicate entries and is unused
+ * @return Image for the icon which indicates a key that has duplicate
+ * entries and is unused
*/
public static Image getDuplicateEntryAndUnusedTranslationsImage() {
- Image image = UIUtils.getImage(UIUtils.IMAGE_UNUSED_TRANSLATION);
- ImageDescriptor missing = ImageDescriptor.createFromImage(UIUtils.getImage(UIUtils.IMAGE_DUPLICATE));
- image = new DecorationOverlayIcon(image, missing, IDecoration.BOTTOM_RIGHT).createImage();
- return image;
+ Image image = UIUtils.getImage(UIUtils.IMAGE_UNUSED_TRANSLATION);
+ ImageDescriptor missing = ImageDescriptor.createFromImage(UIUtils
+ .getImage(UIUtils.IMAGE_DUPLICATE));
+ image = new DecorationOverlayIcon(image, missing,
+ IDecoration.BOTTOM_RIGHT).createImage();
+ return image;
}
-
+
/**
* Gets the orientation suited for a given locale.
- * @param locale the locale
+ *
+ * @param locale
+ * the locale
* @return <code>SWT.RIGHT_TO_LEFT</code> or <code>SWT.LEFT_TO_RIGHT</code>
*/
- public static int getOrientation(Locale locale){
- if(locale!=null){
- ComponentOrientation orientation =
- ComponentOrientation.getOrientation(locale);
- if(orientation==ComponentOrientation.RIGHT_TO_LEFT){
+ public static int getOrientation(Locale locale) {
+ if (locale != null) {
+ ComponentOrientation orientation = ComponentOrientation
+ .getOrientation(locale);
+ if (orientation == ComponentOrientation.RIGHT_TO_LEFT) {
return SWT.RIGHT_TO_LEFT;
}
}
return SWT.LEFT_TO_RIGHT;
}
-
+
/**
* Parses manually the project descriptor looking for a nature.
* <p>
- * Calling IProject.getNature(naturedId) throws exception if the
- * Nature is not defined in the currently executed platform.
- * For example if looking for a pde nature inside an eclipse-platform.
+ * Calling IProject.getNature(naturedId) throws exception if the Nature is
+ * not defined in the currently executed platform. For example if looking
+ * for a pde nature inside an eclipse-platform.
* </p>
* <p>
* This method returns the result without that constraint.
* </p>
- * @param proj The project to examine
- * @param nature The nature to look for.
+ *
+ * @param proj
+ * The project to examine
+ * @param nature
+ * The nature to look for.
* @return true if the nature is defined in that project.
*/
- public static boolean hasNature(
- IProject proj, String nature) {
- IFile projDescr = proj.getFile(".project"); //$NON-NLS-1$
- if (!projDescr.exists()) {
- return false;//a corrupted project
- }
-
- //<classpathentry kind="src" path="src"/>
- InputStream in = null;
- try {
- in = ((IFile)projDescr).getContents();
- //supposedly in utf-8. should not really matter for us
- Reader r = new InputStreamReader(in, "UTF-8");
- LineNumberReader lnr = new LineNumberReader(r);
- String line = lnr.readLine();
- while (line != null) {
- if (line.trim().equals("<nature>" + nature + "</nature>")) {
- lnr.close();
- r.close();
- return true;
- }
- line = lnr.readLine();
- }
- lnr.close();
- r.close();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (in != null) try { in.close(); } catch (IOException e) {}
- }
- return false;
+ public static boolean hasNature(IProject proj, String nature) {
+ IFile projDescr = proj.getFile(".project"); //$NON-NLS-1$
+ if (!projDescr.exists()) {
+ return false;// a corrupted project
+ }
+
+ // <classpathentry kind="src" path="src"/>
+ InputStream in = null;
+ try {
+ in = ((IFile) projDescr).getContents();
+ // supposedly in utf-8. should not really matter for us
+ Reader r = new InputStreamReader(in, "UTF-8");
+ LineNumberReader lnr = new LineNumberReader(r);
+ String line = lnr.readLine();
+ while (line != null) {
+ if (line.trim().equals("<nature>" + nature + "</nature>")) {
+ lnr.close();
+ r.close();
+ return true;
+ }
+ line = lnr.readLine();
+ }
+ lnr.close();
+ r.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (in != null)
+ try {
+ in.close();
+ } catch (IOException e) {
+ }
+ }
+ return false;
}
-
}
-
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/views/MessagesBundleGroupOutline.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/views/MessagesBundleGroupOutline.java
index e6f77d5..f9a5dee 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/views/MessagesBundleGroupOutline.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/views/MessagesBundleGroupOutline.java
@@ -10,8 +10,6 @@
******************************************************************************/
package org.eclipse.babel.editor.views;
-
-
import org.eclipse.babel.editor.internal.MessagesEditor;
import org.eclipse.babel.editor.tree.actions.CollapseAllAction;
import org.eclipse.babel.editor.tree.actions.ExpandAllAction;
@@ -24,200 +22,204 @@
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.views.contentoutline.ContentOutlinePage;
-
/**
- * This outline provides a view for the property keys coming with
- * with a ResourceBundle
+ * This outline provides a view for the property keys coming with with a
+ * ResourceBundle
*/
public class MessagesBundleGroupOutline extends ContentOutlinePage {
private final MessagesEditor editor;
-
- public MessagesBundleGroupOutline(MessagesEditor editor) {
- super();
+
+ public MessagesBundleGroupOutline(MessagesEditor editor) {
+ super();
this.editor = editor;
- }
-
-
- /**
- * {@inheritDoc}
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
-
- KeyTreeContributor treeContributor = new KeyTreeContributor(editor);
- treeContributor.contribute(getTreeViewer());
- }
-
-// /**
-// * {@inheritDoc}
-// */
-// public void dispose() {
-// contributor.dispose();
-// super.dispose();
-// }
-//
-//
-// /**
-// * Gets the selected key tree item.
-// * @return key tree item
-// */
-// public KeyTreeItem getTreeSelection() {
-// IStructuredSelection selection = (IStructuredSelection) getTreeViewer().getSelection();
-// return((KeyTreeItem) selection.getFirstElement());
-// }
-//
-//
-// /**
-// * Gets selected key.
-// * @return selected key
-// */
-// private String getSelectedKey() {
-// String key = null;
-// KeyTreeItem item = getTreeSelection();
-// if(item != null) {
-// key = item.getId();
-// }
-// return(key);
-// }
-//
-//
+ }
+
/**
* {@inheritDoc}
*/
- public void setActionBars(IActionBars actionbars) {
- super.setActionBars(actionbars);
-// filterincomplete = new ToggleAction(UIUtils.IMAGE_INCOMPLETE_ENTRIES);
-// flataction = new ToggleAction(UIUtils.IMAGE_LAYOUT_FLAT);
-// hierarchicalaction = new ToggleAction(UIUtils.IMAGE_LAYOUT_HIERARCHICAL);
-// flataction . setToolTipText(RBEPlugin.getString("key.layout.flat")); //$NON-NLS-1$
-// hierarchicalaction . setToolTipText(RBEPlugin.getString("key.layout.tree")); //$NON-NLS-1$
-// filterincomplete . setToolTipText(RBEPlugin.getString("key.filter.incomplete")); //$NON-NLS-1$
-// flataction . setChecked( ! hierarchical );
-// hierarchicalaction . setChecked( hierarchical );
-// actionbars.getToolBarManager().add( flataction );
-// actionbars.getToolBarManager().add( hierarchicalaction );
-// actionbars.getToolBarManager().add( filterincomplete );
+ public void createControl(Composite parent) {
+ super.createControl(parent);
+
+ KeyTreeContributor treeContributor = new KeyTreeContributor(editor);
+ treeContributor.contribute(getTreeViewer());
+ }
+
+ // /**
+ // * {@inheritDoc}
+ // */
+ // public void dispose() {
+ // contributor.dispose();
+ // super.dispose();
+ // }
+ //
+ //
+ // /**
+ // * Gets the selected key tree item.
+ // * @return key tree item
+ // */
+ // public KeyTreeItem getTreeSelection() {
+ // IStructuredSelection selection = (IStructuredSelection)
+ // getTreeViewer().getSelection();
+ // return((KeyTreeItem) selection.getFirstElement());
+ // }
+ //
+ //
+ // /**
+ // * Gets selected key.
+ // * @return selected key
+ // */
+ // private String getSelectedKey() {
+ // String key = null;
+ // KeyTreeItem item = getTreeSelection();
+ // if(item != null) {
+ // key = item.getId();
+ // }
+ // return(key);
+ // }
+ //
+ //
+ /**
+ * {@inheritDoc}
+ */
+ public void setActionBars(IActionBars actionbars) {
+ super.setActionBars(actionbars);
+ // filterincomplete = new
+ // ToggleAction(UIUtils.IMAGE_INCOMPLETE_ENTRIES);
+ // flataction = new ToggleAction(UIUtils.IMAGE_LAYOUT_FLAT);
+ // hierarchicalaction = new
+ // ToggleAction(UIUtils.IMAGE_LAYOUT_HIERARCHICAL);
+ // flataction . setToolTipText(RBEPlugin.getString("key.layout.flat")); //$NON-NLS-1$
+ // hierarchicalaction . setToolTipText(RBEPlugin.getString("key.layout.tree")); //$NON-NLS-1$
+ // filterincomplete . setToolTipText(RBEPlugin.getString("key.filter.incomplete")); //$NON-NLS-1$
+ // flataction . setChecked( ! hierarchical );
+ // hierarchicalaction . setChecked( hierarchical );
+ // actionbars.getToolBarManager().add( flataction );
+ // actionbars.getToolBarManager().add( hierarchicalaction );
+ // actionbars.getToolBarManager().add( filterincomplete );
IToolBarManager toolBarMgr = actionbars.getToolBarManager();
-
-// ActionGroup
-// ActionContext
-// IAction
-
+
+ // ActionGroup
+ // ActionContext
+ // IAction
+
toolBarMgr.add(new TreeModelAction(editor, getTreeViewer()));
toolBarMgr.add(new FlatModelAction(editor, getTreeViewer()));
toolBarMgr.add(new Separator());
toolBarMgr.add(new ExpandAllAction(editor, getTreeViewer()));
toolBarMgr.add(new CollapseAllAction(editor, getTreeViewer()));
- }
-//
-//
-// /**
-// * Invokes ths functionality according to the toggled action.
-// *
-// * @param action The action that has been toggled.
-// */
-// private void update(ToggleAction action) {
-// int actioncode = 0;
-// if(action == filterincomplete) {
-// actioncode = TreeViewerContributor.KT_INCOMPLETE;
-// } else if(action == flataction) {
-// actioncode = TreeViewerContributor.KT_FLAT;
-// } else if(action == hierarchicalaction) {
-// actioncode = TreeViewerContributor.KT_HIERARCHICAL;
-// }
-// contributor.update(actioncode, action.isChecked());
-// flataction.setChecked((contributor.getMode() & TreeViewerContributor.KT_HIERARCHICAL) == 0);
-// hierarchicalaction.setChecked((contributor.getMode() & TreeViewerContributor.KT_HIERARCHICAL) != 0);
-// }
-//
-//
-// /**
-// * Simple toggle action which delegates it's invocation to
-// * the method {@link #update(ToggleAction)}.
-// */
-// private class ToggleAction extends Action {
-//
-// /**
-// * Initialises this action using the supplied icon.
-// *
-// * @param icon The icon which shall be displayed.
-// */
-// public ToggleAction(String icon) {
-// super(null, IAction.AS_CHECK_BOX);
-// setImageDescriptor(RBEPlugin.getImageDescriptor(icon));
-// }
-//
-// /**
-// * {@inheritDoc}
-// */
-// public void run() {
-// update(this);
-// }
-//
-// } /* ENDCLASS */
-//
-//
-// /**
-// * Implementation of custom behaviour.
-// */
-// private class LocalBehaviour extends MouseAdapter implements IDeltaListener ,
-// ISelectionChangedListener {
-//
-//
-// /**
-// * {@inheritDoc}
-// */
-// public void selectionChanged(SelectionChangedEvent event) {
-// String selected = getSelectedKey();
-// if(selected != null) {
-// tree.selectKey(selected);
-// }
-// }
-//
-// /**
-// * {@inheritDoc}
-// */
-// public void add(DeltaEvent event) {
-// }
-//
-// /**
-// * {@inheritDoc}
-// */
-// public void remove(DeltaEvent event) {
-// }
-//
-// /**
-// * {@inheritDoc}
-// */
-// public void modify(DeltaEvent event) {
-// }
-//
-// /**
-// * {@inheritDoc}
-// */
-// public void select(DeltaEvent event) {
-// KeyTreeItem item = (KeyTreeItem) event.receiver();
-// if(item != null) {
-// getTreeViewer().setSelection(new StructuredSelection(item));
-// }
-// }
-//
-// /**
-// * {@inheritDoc}
-// */
-// public void mouseDoubleClick(MouseEvent event) {
-// Object element = getSelection();
-// if (getTreeViewer().isExpandable(element)) {
-// if (getTreeViewer().getExpandedState(element)) {
-// getTreeViewer().collapseToLevel(element, 1);
-// } else {
-// getTreeViewer().expandToLevel(element, 1);
-// }
-// }
-// }
-//
-// } /* ENDCLASS */
-//
+ }
+ //
+ //
+ // /**
+ // * Invokes ths functionality according to the toggled action.
+ // *
+ // * @param action The action that has been toggled.
+ // */
+ // private void update(ToggleAction action) {
+ // int actioncode = 0;
+ // if(action == filterincomplete) {
+ // actioncode = TreeViewerContributor.KT_INCOMPLETE;
+ // } else if(action == flataction) {
+ // actioncode = TreeViewerContributor.KT_FLAT;
+ // } else if(action == hierarchicalaction) {
+ // actioncode = TreeViewerContributor.KT_HIERARCHICAL;
+ // }
+ // contributor.update(actioncode, action.isChecked());
+ // flataction.setChecked((contributor.getMode() &
+ // TreeViewerContributor.KT_HIERARCHICAL) == 0);
+ // hierarchicalaction.setChecked((contributor.getMode() &
+ // TreeViewerContributor.KT_HIERARCHICAL) != 0);
+ // }
+ //
+ //
+ // /**
+ // * Simple toggle action which delegates it's invocation to
+ // * the method {@link #update(ToggleAction)}.
+ // */
+ // private class ToggleAction extends Action {
+ //
+ // /**
+ // * Initialises this action using the supplied icon.
+ // *
+ // * @param icon The icon which shall be displayed.
+ // */
+ // public ToggleAction(String icon) {
+ // super(null, IAction.AS_CHECK_BOX);
+ // setImageDescriptor(RBEPlugin.getImageDescriptor(icon));
+ // }
+ //
+ // /**
+ // * {@inheritDoc}
+ // */
+ // public void run() {
+ // update(this);
+ // }
+ //
+ // } /* ENDCLASS */
+ //
+ //
+ // /**
+ // * Implementation of custom behaviour.
+ // */
+ // private class LocalBehaviour extends MouseAdapter implements
+ // IDeltaListener ,
+ // ISelectionChangedListener {
+ //
+ //
+ // /**
+ // * {@inheritDoc}
+ // */
+ // public void selectionChanged(SelectionChangedEvent event) {
+ // String selected = getSelectedKey();
+ // if(selected != null) {
+ // tree.selectKey(selected);
+ // }
+ // }
+ //
+ // /**
+ // * {@inheritDoc}
+ // */
+ // public void add(DeltaEvent event) {
+ // }
+ //
+ // /**
+ // * {@inheritDoc}
+ // */
+ // public void remove(DeltaEvent event) {
+ // }
+ //
+ // /**
+ // * {@inheritDoc}
+ // */
+ // public void modify(DeltaEvent event) {
+ // }
+ //
+ // /**
+ // * {@inheritDoc}
+ // */
+ // public void select(DeltaEvent event) {
+ // KeyTreeItem item = (KeyTreeItem) event.receiver();
+ // if(item != null) {
+ // getTreeViewer().setSelection(new StructuredSelection(item));
+ // }
+ // }
+ //
+ // /**
+ // * {@inheritDoc}
+ // */
+ // public void mouseDoubleClick(MouseEvent event) {
+ // Object element = getSelection();
+ // if (getTreeViewer().isExpandable(element)) {
+ // if (getTreeViewer().getExpandedState(element)) {
+ // getTreeViewer().collapseToLevel(element, 1);
+ // } else {
+ // getTreeViewer().expandToLevel(element, 1);
+ // }
+ // }
+ // }
+ //
+ // } /* ENDCLASS */
+ //
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/ActionButton.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/ActionButton.java
index 732847f..3ab9ce0 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/ActionButton.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/ActionButton.java
@@ -18,6 +18,7 @@
/**
* A button that when clicked, will execute the given action.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public class ActionButton extends Composite {
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/LocaleSelector.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/LocaleSelector.java
index ec9ac6b..f88144e 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/LocaleSelector.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/LocaleSelector.java
@@ -35,6 +35,7 @@
/**
* Composite for dynamically selecting a locale from a list of available
* locales.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public class LocaleSelector extends Composite {
@@ -42,7 +43,7 @@
private static final String DEFAULT_LOCALE = "[" //$NON-NLS-1$
+ MessagesEditorPlugin.getString("editor.default") //$NON-NLS-1$
+ "]"; //$NON-NLS-1$
-
+
private Locale[] availableLocales;
private Combo localesCombo;
@@ -50,10 +51,11 @@
private Text countryText;
private Text variantText;
-
/**
* Constructor.
- * @param parent parent composite
+ *
+ * @param parent
+ * parent composite
*/
public LocaleSelector(Composite parent) {
super(parent, SWT.NONE);
@@ -62,25 +64,24 @@
availableLocales = Locale.getAvailableLocales();
Arrays.sort(availableLocales, new Comparator<Locale>() {
public int compare(Locale locale1, Locale locale2) {
- return Collator.getInstance().compare(
- locale1.getDisplayName(),
+ return Collator.getInstance().compare(locale1.getDisplayName(),
locale2.getDisplayName());
}
});
-
+
// This layout
GridLayout layout = new GridLayout();
setLayout(layout);
layout.numColumns = 1;
layout.verticalSpacing = 20;
-
+
// Group settings
Group selectionGroup = new Group(this, SWT.NULL);
layout = new GridLayout(3, false);
selectionGroup.setLayout(layout);
- selectionGroup.setText(MessagesEditorPlugin.getString(
- "selector.title")); //$NON-NLS-1$
-
+ selectionGroup
+ .setText(MessagesEditorPlugin.getString("selector.title")); //$NON-NLS-1$
+
// Set locales drop-down
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 3;
@@ -97,7 +98,7 @@
langText.setText(""); //$NON-NLS-1$
countryText.setText(""); //$NON-NLS-1$
} else {
- Locale locale = availableLocales[index -1];
+ Locale locale = availableLocales[index - 1];
langText.setText(locale.getLanguage());
countryText.setText(locale.getCountry());
}
@@ -126,8 +127,7 @@
countryText.setLayoutData(gd);
countryText.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
- countryText.setText(
- countryText.getText().toUpperCase());
+ countryText.setText(countryText.getText().toUpperCase());
setLocaleOnlocalesCombo();
}
});
@@ -142,7 +142,7 @@
setLocaleOnlocalesCombo();
}
});
-
+
// Labels
gd = new GridData();
gd.horizontalAlignment = GridData.CENTER;
@@ -153,28 +153,27 @@
gd = new GridData();
gd.horizontalAlignment = GridData.CENTER;
Label lblCountry = new Label(selectionGroup, SWT.NULL);
- lblCountry.setText(MessagesEditorPlugin.getString(
- "selector.country")); //$NON-NLS-1$
+ lblCountry.setText(MessagesEditorPlugin.getString("selector.country")); //$NON-NLS-1$
lblCountry.setLayoutData(gd);
gd = new GridData();
gd.horizontalAlignment = GridData.CENTER;
Label lblVariant = new Label(selectionGroup, SWT.NULL);
- lblVariant.setText(MessagesEditorPlugin.getString(
- "selector.variant")); //$NON-NLS-1$
+ lblVariant.setText(MessagesEditorPlugin.getString("selector.variant")); //$NON-NLS-1$
lblVariant.setLayoutData(gd);
}
/**
- * Gets the selected locale. Default locale is represented by a
+ * Gets the selected locale. Default locale is represented by a
* <code>null</code> value.
+ *
* @return selected locale
*/
public Locale getSelectedLocale() {
String lang = langText.getText().trim();
String country = countryText.getText().trim();
String variant = variantText.getText().trim();
-
+
if (lang.length() > 0 && country.length() > 0 && variant.length() > 0) {
return new Locale(lang, country, variant);
} else if (lang.length() > 0 && country.length() > 0) {
@@ -189,10 +188,8 @@
/**
* Sets an available locale on the available locales combo box.
*/
- /*default*/ void setLocaleOnlocalesCombo() {
- Locale locale = new Locale(
- langText.getText(),
- countryText.getText(),
+ /* default */void setLocaleOnlocalesCombo() {
+ Locale locale = new Locale(langText.getText(), countryText.getText(),
variantText.getText());
int index = -1;
for (int i = 0; i < availableLocales.length; i++) {
@@ -207,23 +204,25 @@
localesCombo.clearSelection();
}
}
-
+
/**
* Adds a modify listener.
- * @param listener modify listener
+ *
+ * @param listener
+ * modify listener
*/
public void addModifyListener(final ModifyListener listener) {
- langText.addModifyListener(new ModifyListener(){
+ langText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
listener.modifyText(e);
}
});
- countryText.addModifyListener(new ModifyListener(){
+ countryText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
listener.modifyText(e);
}
});
- variantText.addModifyListener(new ModifyListener(){
+ variantText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
listener.modifyText(e);
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/NullableText.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/NullableText.java
index 46ff23b..f500469 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/NullableText.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/NullableText.java
@@ -24,13 +24,13 @@
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
-
/**
- * Special text control that regognized the difference between a
- * <code>null</code> values and an empty string. When a <code>null</code>
- * value is supplied, the control background is of a different color.
- * Pressing the backspace button when the field is currently empty will
- * change its value from empty string to <code>null</code>.
+ * Special text control that regognized the difference between a
+ * <code>null</code> values and an empty string. When a <code>null</code> value
+ * is supplied, the control background is of a different color. Pressing the
+ * backspace button when the field is currently empty will change its value from
+ * empty string to <code>null</code>.
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
public class NullableText extends Composite {
@@ -40,7 +40,7 @@
private final Color nullColor;
private boolean isnull;
-
+
private KeyListener keyListener = new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (SWT.BS == e.character) {
@@ -49,13 +49,14 @@
}
}
}
+
public void keyReleased(KeyEvent e) {
if (text.getText().length() > 0) {
renderNormal();
}
}
};
-
+
/**
* Constructor.
*/
@@ -66,8 +67,8 @@
text.setData("REDO", new Stack<String>());
defaultColor = text.getBackground();
nullColor = UIUtils.getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW);
-
- GridLayout gridLayout = new GridLayout(1, false);
+
+ GridLayout gridLayout = new GridLayout(1, false);
gridLayout.horizontalSpacing = 0;
gridLayout.verticalSpacing = 0;
gridLayout.marginWidth = 0;
@@ -82,7 +83,7 @@
public void setOrientation(int orientation) {
text.setOrientation(orientation);
}
-
+
public void setText(String text) {
isnull = text == null;
if (isnull) {
@@ -95,13 +96,14 @@
Stack<String> undoCache = (Stack<String>) this.text.getData("UNDO");
undoCache.push(this.text.getText());
}
+
public String getText() {
if (isnull) {
return null;
}
return this.text.getText();
}
-
+
/**
* @see org.eclipse.swt.widgets.Control#setEnabled(boolean)
*/
@@ -111,95 +113,95 @@
}
private void initComponents() {
- GridData gridData = new GridData(
- GridData.FILL, GridData.FILL, true, true);
+ GridData gridData = new GridData(GridData.FILL, GridData.FILL, true,
+ true);
text.setLayoutData(gridData);
text.addKeyListener(keyListener);
-
+
}
-
private void renderNull() {
isnull = true;
if (isEnabled()) {
text.setBackground(nullColor);
-// try {
-// text.setBackgroundImage(UIUtils.getImage("null.bmp"));
-// } catch (Throwable t) {
-// t.printStackTrace();
-// }
+ // try {
+ // text.setBackgroundImage(UIUtils.getImage("null.bmp"));
+ // } catch (Throwable t) {
+ // t.printStackTrace();
+ // }
} else {
- text.setBackground(UIUtils.getSystemColor(
- SWT.COLOR_WIDGET_BACKGROUND));
-// text.setBackgroundImage(null);
+ text.setBackground(UIUtils
+ .getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
+ // text.setBackgroundImage(null);
}
}
+
private void renderNormal() {
isnull = false;
if (isEnabled()) {
text.setBackground(defaultColor);
} else {
- text.setBackground(UIUtils.getSystemColor(
- SWT.COLOR_WIDGET_BACKGROUND));
+ text.setBackground(UIUtils
+ .getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
}
-// text.setBackgroundImage(null);
+ // text.setBackgroundImage(null);
}
/**
- * @see org.eclipse.swt.widgets.Control#addFocusListener(
- * org.eclipse.swt.events.FocusListener)
+ * @see org.eclipse.swt.widgets.Control#addFocusListener(org.eclipse.swt.events.FocusListener)
*/
public void addFocusListener(FocusListener listener) {
text.addFocusListener(listener);
}
+
/**
- * @see org.eclipse.swt.widgets.Control#addKeyListener(
- * org.eclipse.swt.events.KeyListener)
+ * @see org.eclipse.swt.widgets.Control#addKeyListener(org.eclipse.swt.events.KeyListener)
*/
public void addKeyListener(KeyListener listener) {
text.addKeyListener(listener);
}
+
/**
- * @see org.eclipse.swt.widgets.Control#removeFocusListener(
- * org.eclipse.swt.events.FocusListener)
+ * @see org.eclipse.swt.widgets.Control#removeFocusListener(org.eclipse.swt.events.FocusListener)
*/
public void removeFocusListener(FocusListener listener) {
text.removeFocusListener(listener);
}
+
/**
- * @see org.eclipse.swt.widgets.Control#removeKeyListener(
- * org.eclipse.swt.events.KeyListener)
+ * @see org.eclipse.swt.widgets.Control#removeKeyListener(org.eclipse.swt.events.KeyListener)
*/
public void removeKeyListener(KeyListener listener) {
text.removeKeyListener(listener);
}
/**
- * @param editable true if editable false otherwise.
- * If never called it is editable by default.
+ * @param editable
+ * true if editable false otherwise. If never called it is
+ * editable by default.
*/
public void setEditable(boolean editable) {
text.setEditable(editable);
}
-
-// private class SaveListener implements IMessagesEditorListener {
-//
-// public void onSave() {
-// Stack<String> undoCache = (Stack<String>) text.getData("UNDO");
-// undoCache.clear();
-// }
-//
-// public void onModify() {
-// // TODO Auto-generated method stub
-//
-// }
-//
-// public void onResourceChanged(IMessagesBundle bundle) {
-// // TODO Auto-generated method stub
-//
-// }
-//
-// }
-
+
+ // private class SaveListener implements IMessagesEditorListener {
+ //
+ // public void onSave() {
+ // Stack<String> undoCache = (Stack<String>) text.getData("UNDO");
+ // undoCache.clear();
+ // }
+ //
+ // public void onModify() {
+ // // TODO Auto-generated method stub
+ //
+ // }
+ //
+ // public void onResourceChanged(IMessagesBundle bundle) {
+ // // TODO Auto-generated method stub
+ //
+ // }
+ //
+ // }
+
}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/IResourceBundleWizard.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/IResourceBundleWizard.java
index 5a797dc..8965166 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/IResourceBundleWizard.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/IResourceBundleWizard.java
@@ -12,8 +12,8 @@
public interface IResourceBundleWizard {
- void setBundleId(String rbName);
+ void setBundleId(String rbName);
- void setDefaultPath(String pathName);
+ void setDefaultPath(String pathName);
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleNewWizardPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleNewWizardPage.java
index 3e2e8be..c872e08 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleNewWizardPage.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleNewWizardPage.java
@@ -43,9 +43,10 @@
import org.eclipse.ui.dialogs.ContainerSelectionDialog;
/**
- * The "New" wizard page allows setting the container for
- * the new bundle group as well as the bundle group common base name. The page
- * will only accept file name without the extension.
+ * The "New" wizard page allows setting the container for the new bundle group
+ * as well as the bundle group common base name. The page will only accept file
+ * name without the extension.
+ *
* @author Pascal Essiembre (essiembre@users.sourceforge.net)
* @version $Author: droy $ $Revision: 1.2 $ $Date: 2012/07/18 20:13:09 $
*/
@@ -54,9 +55,10 @@
static final String DEFAULT_LOCALE = "[" //$NON-NLS-1$
+ MessagesEditorPlugin.getString("editor.default") //$NON-NLS-1$
+ "]"; //$NON-NLS-1$
-
+
/**
- * contains the path of the folder in which the resource file will be created
+ * contains the path of the folder in which the resource file will be
+ * created
*/
private Text containerText;
/**
@@ -64,33 +66,36 @@
*/
private Text fileText;
private ISelection selection;
-
+
private Button addButton;
private Button removeButton;
/**
* Contains all added locales
*/
private List bundleLocalesList;
-
+
private LocaleSelector localeSelector;
private String defaultPath = "";
private String defaultRBName = "ApplicationResources";
-
+
/**
* Constructor for SampleNewWizardPage.
- * @param selection workbench selection
+ *
+ * @param selection
+ * workbench selection
*/
- public ResourceBundleNewWizardPage(ISelection selection, String defaultPath, String defaultRBName) {
+ public ResourceBundleNewWizardPage(ISelection selection,
+ String defaultPath, String defaultRBName) {
super("wizardPage"); //$NON-NLS-1$
setTitle(MessagesEditorPlugin.getString("editor.wiz.title")); //$NON-NLS-1$
setDescription(MessagesEditorPlugin.getString("editor.wiz.desc")); //$NON-NLS-1$
this.selection = selection;
-
- if (! defaultPath.isEmpty())
- this.defaultPath = defaultPath;
- if (! defaultRBName.isEmpty())
- this.defaultRBName = defaultRBName;
+
+ if (!defaultPath.isEmpty())
+ this.defaultPath = defaultPath;
+ if (!defaultRBName.isEmpty())
+ this.defaultRBName = defaultRBName;
}
/**
@@ -104,23 +109,23 @@
layout.verticalSpacing = 20;
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
container.setLayoutData(gd);
-
- // Bundle name + location
+
+ // Bundle name + location
createTopComposite(container);
- // Locales
+ // Locales
createBottomComposite(container);
-
-
+
initialize();
dialogChanged();
setControl(container);
}
-
/**
* Creates the bottom part of this wizard, which is the locales to add.
- * @param parent parent container
+ *
+ * @param parent
+ * parent container
*/
private void createBottomComposite(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
@@ -130,21 +135,22 @@
layout.verticalSpacing = 9;
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
container.setLayoutData(gd);
-
+
// Available locales
createBottomAvailableLocalesComposite(container);
// Buttons
createBottomButtonsComposite(container);
-
+
// Selected locales
createBottomSelectedLocalesComposite(container);
}
/**
- * Creates the bottom part of this wizard where selected locales
- * are stored.
- * @param parent parent container
+ * Creates the bottom part of this wizard where selected locales are stored.
+ *
+ * @param parent
+ * parent container
*/
private void createBottomSelectedLocalesComposite(Composite parent) {
@@ -156,27 +162,29 @@
selectedGroup.setLayout(layout);
GridData gd = new GridData(GridData.FILL_BOTH);
selectedGroup.setLayoutData(gd);
- selectedGroup.setText(MessagesEditorPlugin.getString(
- "editor.wiz.selected")); //$NON-NLS-1$
- bundleLocalesList =
- new List(selectedGroup, SWT.READ_ONLY | SWT.MULTI | SWT.BORDER);
+ selectedGroup.setText(MessagesEditorPlugin
+ .getString("editor.wiz.selected")); //$NON-NLS-1$
+ bundleLocalesList = new List(selectedGroup, SWT.READ_ONLY | SWT.MULTI
+ | SWT.BORDER);
gd = new GridData(GridData.FILL_BOTH);
bundleLocalesList.setLayoutData(gd);
bundleLocalesList.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
- removeButton.setEnabled(
- bundleLocalesList.getSelectionIndices().length != 0);
+ removeButton.setEnabled(bundleLocalesList.getSelectionIndices().length != 0);
setAddButtonState();
}
});
- // add a single Locale so that the bundleLocalesList isn't empty on startup
+ // add a single Locale so that the bundleLocalesList isn't empty on
+ // startup
bundleLocalesList.add(DEFAULT_LOCALE);
}
-
+
/**
* Creates the bottom part of this wizard where buttons to add/remove
* locales are located.
- * @param parent parent container
+ *
+ * @param parent
+ * parent container
*/
private void createBottomButtonsComposite(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
@@ -189,8 +197,7 @@
addButton = new Button(container, SWT.NULL);
gd = new GridData(GridData.FILL_HORIZONTAL);
addButton.setLayoutData(gd);
- addButton.setText(MessagesEditorPlugin.getString(
- "editor.wiz.add")); //$NON-NLS-1$
+ addButton.setText(MessagesEditorPlugin.getString("editor.wiz.add")); //$NON-NLS-1$
addButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
bundleLocalesList.add(getSelectedLocaleAsString());
@@ -202,40 +209,43 @@
removeButton = new Button(container, SWT.NULL);
gd = new GridData(GridData.FILL_HORIZONTAL);
removeButton.setLayoutData(gd);
- removeButton.setText(MessagesEditorPlugin.getString(
- "editor.wiz.remove")); //$NON-NLS-1$
+ removeButton.setText(MessagesEditorPlugin
+ .getString("editor.wiz.remove")); //$NON-NLS-1$
removeButton.setEnabled(false);
removeButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
- bundleLocalesList.remove(
- bundleLocalesList.getSelectionIndices());
+ bundleLocalesList.remove(bundleLocalesList
+ .getSelectionIndices());
removeButton.setEnabled(false);
setAddButtonState();
dialogChanged(); // for the locale-check
}
});
}
-
+
/**
- * Creates the bottom part of this wizard where locales can be chosen
- * or created
- * @param parent parent container
+ * Creates the bottom part of this wizard where locales can be chosen or
+ * created
+ *
+ * @param parent
+ * parent container
*/
private void createBottomAvailableLocalesComposite(Composite parent) {
- localeSelector =
- new LocaleSelector(parent);
- localeSelector.addModifyListener(new ModifyListener(){
+ localeSelector = new LocaleSelector(parent);
+ localeSelector.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
setAddButtonState();
}
});
}
-
+
/**
- * Creates the top part of this wizard, which is the bundle name
- * and location.
- * @param parent parent container
+ * Creates the top part of this wizard, which is the bundle name and
+ * location.
+ *
+ * @param parent
+ * parent container
*/
private void createTopComposite(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
@@ -245,11 +255,10 @@
layout.verticalSpacing = 9;
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
container.setLayoutData(gd);
-
+
// Folder
Label label = new Label(container, SWT.NULL);
- label.setText(MessagesEditorPlugin.getString(
- "editor.wiz.folder")); //$NON-NLS-1$
+ label.setText(MessagesEditorPlugin.getString("editor.wiz.folder")); //$NON-NLS-1$
containerText = new Text(container, SWT.BORDER | SWT.SINGLE);
gd = new GridData(GridData.FILL_HORIZONTAL);
@@ -260,18 +269,16 @@
}
});
Button button = new Button(container, SWT.PUSH);
- button.setText(MessagesEditorPlugin.getString(
- "editor.wiz.browse")); //$NON-NLS-1$
+ button.setText(MessagesEditorPlugin.getString("editor.wiz.browse")); //$NON-NLS-1$
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleBrowse();
}
});
-
+
// Bundle name
label = new Label(container, SWT.NULL);
- label.setText(MessagesEditorPlugin.getString(
- "editor.wiz.bundleName")); //$NON-NLS-1$
+ label.setText(MessagesEditorPlugin.getString("editor.wiz.bundleName")); //$NON-NLS-1$
fileText = new Text(container, SWT.BORDER | SWT.SINGLE);
gd = new GridData(GridData.FILL_HORIZONTAL);
@@ -284,121 +291,117 @@
label = new Label(container, SWT.NULL);
label.setText("[locale].properties"); //$NON-NLS-1$
}
-
+
/**
- * Tests if the current workbench selection is a suitable
- * container to use.
+ * Tests if the current workbench selection is a suitable container to use.
*/
private void initialize() {
- if (! defaultPath.isEmpty()) {
- containerText.setText(defaultPath);
-
- } else if (selection!=null && selection.isEmpty()==false &&
- selection instanceof IStructuredSelection) {
- IStructuredSelection ssel = (IStructuredSelection)selection;
- if (ssel.size()>1) {
- return;
+ if (!defaultPath.isEmpty()) {
+ containerText.setText(defaultPath);
+
+ } else if (selection != null && selection.isEmpty() == false
+ && selection instanceof IStructuredSelection) {
+ IStructuredSelection ssel = (IStructuredSelection) selection;
+ if (ssel.size() > 1) {
+ return;
}
Object obj = ssel.getFirstElement();
if (obj instanceof IAdaptable) {
- IResource resource = (IResource) ((IAdaptable) obj).
- getAdapter(IResource.class);
- // check if selection is a file
- if (resource.getType() == IResource.FILE) {
- resource = resource.getParent();
- }
- // fill filepath container
- containerText.setText(resource.getFullPath().
- toPortableString());
- } else if (obj instanceof IResource) {
- // this will most likely never happen (legacy code)
+ IResource resource = (IResource) ((IAdaptable) obj)
+ .getAdapter(IResource.class);
+ // check if selection is a file
+ if (resource.getType() == IResource.FILE) {
+ resource = resource.getParent();
+ }
+ // fill filepath container
+ containerText
+ .setText(resource.getFullPath().toPortableString());
+ } else if (obj instanceof IResource) {
+ // this will most likely never happen (legacy code)
IContainer container;
if (obj instanceof IContainer) {
- container = (IContainer)obj;
+ container = (IContainer) obj;
} else {
- container = ((IResource)obj).getParent();
+ container = ((IResource) obj).getParent();
}
- containerText.setText(container.getFullPath().
- toPortableString());
- }
+ containerText.setText(container.getFullPath()
+ .toPortableString());
+ }
}
-
+
fileText.setText(defaultRBName);
}
-
+
/**
- * Uses the standard container selection dialog to
- * choose the new value for the container field.
+ * Uses the standard container selection dialog to choose the new value for
+ * the container field.
*/
- /*default*/ void handleBrowse() {
- ContainerSelectionDialog dialog =
- new ContainerSelectionDialog(
- getShell(),
- ResourcesPlugin.getWorkspace().getRoot(),
- false,
- MessagesEditorPlugin.getString(
- "editor.wiz.selectFolder")); //$NON-NLS-1$
+ /* default */void handleBrowse() {
+ ContainerSelectionDialog dialog = new ContainerSelectionDialog(
+ getShell(), ResourcesPlugin.getWorkspace().getRoot(), false,
+ MessagesEditorPlugin.getString("editor.wiz.selectFolder")); //$NON-NLS-1$
if (dialog.open() == Window.OK) {
Object[] result = dialog.getResult();
if (result.length == 1) {
- containerText.setText(((Path)result[0]).toOSString());
+ containerText.setText(((Path) result[0]).toOSString());
}
}
}
-
+
/**
* Ensures that both text fields and the Locale field are set.
*/
- /*default*/ void dialogChanged() {
+ /* default */void dialogChanged() {
String container = getContainerName();
String fileName = getFileName();
if (container.length() == 0) {
- updateStatus(MessagesEditorPlugin.getString(
- "editor.wiz.error.container")); //$NON-NLS-1$
+ updateStatus(MessagesEditorPlugin
+ .getString("editor.wiz.error.container")); //$NON-NLS-1$
return;
}
if (fileName.length() == 0) {
- updateStatus(MessagesEditorPlugin.getString(
- "editor.wiz.error.bundleName")); //$NON-NLS-1$
+ updateStatus(MessagesEditorPlugin
+ .getString("editor.wiz.error.bundleName")); //$NON-NLS-1$
return;
}
int dotLoc = fileName.lastIndexOf('.');
if (dotLoc != -1) {
- updateStatus(MessagesEditorPlugin.getString(
- "editor.wiz.error.extension")); //$NON-NLS-1$
+ updateStatus(MessagesEditorPlugin
+ .getString("editor.wiz.error.extension")); //$NON-NLS-1$
return;
}
// check if at least one Locale has been added to th list
if (bundleLocalesList.getItemCount() <= 0) {
- updateStatus(MessagesEditorPlugin.getString(
- "editor.wiz.error.locale")); //$NON-NLS-1$
+ updateStatus(MessagesEditorPlugin
+ .getString("editor.wiz.error.locale")); //$NON-NLS-1$
return;
}
// check if the container field contains a valid path
// meaning: Project exists, at least one segment, valid path
Path pathContainer = new Path(container);
if (!pathContainer.isValidPath(container)) {
- updateStatus(MessagesEditorPlugin.getString(
- "editor.wiz.error.invalidpath")); //$NON-NLS-1$
+ updateStatus(MessagesEditorPlugin
+ .getString("editor.wiz.error.invalidpath")); //$NON-NLS-1$
return;
}
-
+
if (pathContainer.segmentCount() < 1) {
- updateStatus(MessagesEditorPlugin.getString(
- "editor.wiz.error.invalidpath")); //$NON-NLS-1$
- return;
+ updateStatus(MessagesEditorPlugin
+ .getString("editor.wiz.error.invalidpath")); //$NON-NLS-1$
+ return;
}
-
+
if (!projectExists(pathContainer.segment(0))) {
- String errormessage = MessagesEditorPlugin.getString(
- "editor.wiz.error.projectnotexist");
- errormessage = String.format(errormessage, pathContainer.segment(0));
- updateStatus(errormessage); //$NON-NLS-1$
- return;
+ String errormessage = MessagesEditorPlugin
+ .getString("editor.wiz.error.projectnotexist");
+ errormessage = String
+ .format(errormessage, pathContainer.segment(0));
+ updateStatus(errormessage); //$NON-NLS-1$
+ return;
}
-
+
updateStatus(null);
}
@@ -409,67 +412,73 @@
/**
* Gets the container name.
+ *
* @return container name
*/
public String getContainerName() {
return containerText.getText();
}
- /**
+
+ /**
* Gets the file name.
+ *
* @return file name
*/
public String getFileName() {
return fileText.getText();
}
-
+
/**
- * Sets the "add" button state.
+ * Sets the "add" button state.
*/
- /*default*/ void setAddButtonState() {
- addButton.setEnabled(bundleLocalesList.indexOf(
- getSelectedLocaleAsString()) == -1);
+ /* default */void setAddButtonState() {
+ addButton.setEnabled(bundleLocalesList
+ .indexOf(getSelectedLocaleAsString()) == -1);
}
-
+
/**
* Gets the user selected locales.
+ *
* @return locales
*/
- /*default*/ String[] getLocaleStrings() {
+ /* default */String[] getLocaleStrings() {
return bundleLocalesList.getItems();
}
-
+
/**
* Gets a string representation of selected locale.
+ *
* @return string representation of selected locale
*/
- /*default*/ String getSelectedLocaleAsString() {
+ /* default */String getSelectedLocaleAsString() {
Locale selectedLocale = localeSelector.getSelectedLocale();
if (selectedLocale != null) {
return selectedLocale.toString();
}
return DEFAULT_LOCALE;
}
-
+
/**
* Checks if there is a Project with the given name in the Package Explorer
+ *
* @param projectName
* @return
*/
- /*default*/ boolean projectExists(String projectName) {
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- Path containerNamePath = new Path("/"+projectName);
+ /* default */boolean projectExists(String projectName) {
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ Path containerNamePath = new Path("/" + projectName);
IResource resource = root.findMember(containerNamePath);
if (resource == null) {
- return false;
+ return false;
}
return resource.exists();
}
-
+
public void setDefaultRBName(String name) {
- defaultRBName = name;
+ defaultRBName = name;
}
-
+
public void setDefaultPath(String path) {
- defaultPath = path;
+ defaultPath = path;
}
}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleWizard.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleWizard.java
index c04016a..364ded1 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleWizard.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleWizard.java
@@ -45,17 +45,18 @@
/**
* This is the main wizard class for creating a new set of ResourceBundle
- * properties files. If the container resource
- * (a folder or a project) is selected in the workspace
- * when the wizard is opened, it will accept it as the target
- * container. The wizard creates one or several files with the extension
+ * properties files. If the container resource (a folder or a project) is
+ * selected in the workspace when the wizard is opened, it will accept it as the
+ * target container. The wizard creates one or several files with the extension
* "properties".
+ *
* @author Pascal Essiembre (pascal@essiembre.com)
*/
-public class ResourceBundleWizard extends Wizard implements INewWizard, IResourceBundleWizard {
+public class ResourceBundleWizard extends Wizard implements INewWizard,
+ IResourceBundleWizard {
private ResourceBundleNewWizardPage page;
private ISelection selection;
-
+
private String defaultRbName = "";
private String defaultPath = "";
@@ -66,56 +67,59 @@
super();
setNeedsProgressMonitor(true);
}
-
+
/**
* Adding the page to the wizard.
*/
public void addPages() {
- page = new ResourceBundleNewWizardPage(selection, defaultPath, defaultRbName);
+ page = new ResourceBundleNewWizardPage(selection, defaultPath,
+ defaultRbName);
addPage(page);
}
-
+
/**
- * This method is called when 'Finish' button is pressed in
- * the wizard. We will create an operation and run it
- * using wizard as execution context.
+ * This method is called when 'Finish' button is pressed in the wizard. We
+ * will create an operation and run it using wizard as execution context.
*/
public boolean performFinish() {
final String containerName = page.getContainerName();
final String baseName = page.getFileName();
final String[] locales = page.getLocaleStrings();
if (!folderExists(containerName)) {
- //show choosedialog
- String message = MessagesEditorPlugin.getString(
- "editor.wiz.createfolder");
- message = String.format(message, containerName);
- if(!MessageDialog.openConfirm(getShell(), "Create Folder", message)) { //$NON-NLS-1$
- return false;
- }
-
+ // show choosedialog
+ String message = MessagesEditorPlugin
+ .getString("editor.wiz.createfolder");
+ message = String.format(message, containerName);
+ if (!MessageDialog
+ .openConfirm(getShell(), "Create Folder", message)) { //$NON-NLS-1$
+ return false;
+ }
+
}
IRunnableWithProgress op = new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException {
+ public void run(IProgressMonitor monitor)
+ throws InvocationTargetException {
try {
monitor.worked(1);
- monitor.setTaskName(MessagesEditorPlugin.getString(
- "editor.wiz.creating")); //$NON-NLS-1$
+ monitor.setTaskName(MessagesEditorPlugin
+ .getString("editor.wiz.creating")); //$NON-NLS-1$
IFile file = null;
- for (int i = 0; i < locales.length; i++) {
+ for (int i = 0; i < locales.length; i++) {
String fileName = baseName;
- if (locales[i].equals(
- ResourceBundleNewWizardPage.DEFAULT_LOCALE)) {
+ if (locales[i]
+ .equals(ResourceBundleNewWizardPage.DEFAULT_LOCALE)) {
fileName += ".properties"; //$NON-NLS-1$
} else {
fileName += "_" + locales[i] //$NON-NLS-1$
- + ".properties"; //$NON-NLS-1$
+ + ".properties"; //$NON-NLS-1$
}
file = createFile(containerName, fileName, monitor);
}
if (file == null) { // file creation failed
- MessageDialog.openError(getShell(), "Error", "Error creating file"); //$NON-NLS-1$
- throwCoreException("File \""+containerName+baseName+"\" could not be created"); //$NON-NLS-1$
+ MessageDialog.openError(getShell(),
+ "Error", "Error creating file"); //$NON-NLS-1$
+ throwCoreException("File \"" + containerName + baseName + "\" could not be created"); //$NON-NLS-1$
}
final IFile lastFile = file;
getShell().getDisplay().asyncExec(new Runnable() {
@@ -142,69 +146,79 @@
return false;
} catch (InvocationTargetException e) {
Throwable realException = e.getTargetException();
- MessageDialog.openError(getShell(),
+ MessageDialog.openError(getShell(),
"Error", realException.getLocalizedMessage()); //$NON-NLS-1$
return false;
}
return true;
}
+
/*
* Checks if the input folder existsS
*/
- /*default*/ boolean folderExists(String path) {
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ /* default */boolean folderExists(String path) {
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IResource resource = root.findMember(new Path(path));
if (resource == null) {
- return false;
+ return false;
} else {
- return resource.exists();
+ return resource.exists();
}
}
-
+
/*
- * The worker method. It will find the container, create the
- * file if missing or just replace its contents, and open
- * the editor on the newly created file. Will also create
- * the parent folders of the file if they do not exist.
+ * The worker method. It will find the container, create the file if missing
+ * or just replace its contents, and open the editor on the newly created
+ * file. Will also create the parent folders of the file if they do not
+ * exist.
*/
- /*default*/ IFile createFile(
- String containerName,
- String fileName,
- IProgressMonitor monitor)
- throws CoreException {
-
- monitor.beginTask(MessagesEditorPlugin.getString(
- "editor.wiz.creating") + fileName, 2); //$NON-NLS-1$
+ /* default */IFile createFile(String containerName, String fileName,
+ IProgressMonitor monitor) throws CoreException {
+
+ monitor.beginTask(
+ MessagesEditorPlugin.getString("editor.wiz.creating") + fileName, 2); //$NON-NLS-1$
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
Path containerNamePath = new Path(containerName);
IResource resource = root.findMember(containerNamePath);
if (resource == null) {
- if (!createFolder(containerNamePath, root, monitor)) {
- MessageDialog.openError(getShell(), "Error",
- String.format(MessagesEditorPlugin.getString(
- "editor.wiz.error.couldnotcreatefolder"),
- containerName)); //$NON-NLS-1$
- return null;
- }
+ if (!createFolder(containerNamePath, root, monitor)) {
+ MessageDialog
+ .openError(
+ getShell(),
+ "Error",
+ String.format(
+ MessagesEditorPlugin
+ .getString("editor.wiz.error.couldnotcreatefolder"),
+ containerName)); //$NON-NLS-1$
+ return null;
+ }
} else if (!resource.exists() || !(resource instanceof IContainer)) {
//throwCoreException("Container \"" + containerName //$NON-NLS-1$
// + "\" does not exist."); //$NON-NLS-1$
- if (!createFolder(containerNamePath, root, monitor)) {
- MessageDialog.openError(getShell(), "Error",
- String.format(MessagesEditorPlugin.getString(
- "editor.wiz.error.couldnotcreatefolder"),
- containerName)); //$NON-NLS-1$
- return null;
- }
+ if (!createFolder(containerNamePath, root, monitor)) {
+ MessageDialog
+ .openError(
+ getShell(),
+ "Error",
+ String.format(
+ MessagesEditorPlugin
+ .getString("editor.wiz.error.couldnotcreatefolder"),
+ containerName)); //$NON-NLS-1$
+ return null;
+ }
}
-
+
IContainer container = (IContainer) root.findMember(containerNamePath);
if (container == null) {
- MessageDialog.openError(getShell(), "Error",
- String.format(MessagesEditorPlugin.getString(
- "editor.wiz.error.couldnotcreatefolder"),
- containerName)); //$NON-NLS-1$
- return null;
+ MessageDialog
+ .openError(
+ getShell(),
+ "Error",
+ String.format(
+ MessagesEditorPlugin
+ .getString("editor.wiz.error.couldnotcreatefolder"),
+ containerName)); //$NON-NLS-1$
+ return null;
}
final IFile file = container.getFile(new Path(fileName));
try {
@@ -219,75 +233,81 @@
}
return file;
}
-
+
/*
* Recursively creates all missing folders
*/
- /*default*/ boolean createFolder(Path folderPath, IWorkspaceRoot root, IProgressMonitor monitor) {
- IResource baseResource = root.findMember(folderPath);
- if (!(baseResource == null)) {
- if (baseResource.exists()) {
- return true;
- }
- } else { // if folder does not exist
- if (folderPath.segmentCount() <= 1) {
- return true;
- }
- Path oneSegmentLess = (Path)folderPath.removeLastSegments(1); // get parent
- if (createFolder(oneSegmentLess, root, monitor)) { // create parent folder
- IResource resource = root.findMember(oneSegmentLess);
- if (resource == null) {
- return false; // resource is null
- } else if (!resource.exists() || !(resource instanceof IContainer)) {
- return false; // resource does not exist
- }
- final IFolder folder = root.getFolder(folderPath);
- try {
- folder.create(true, true, monitor);
- } catch (CoreException e) {
- return false;
- }
- return true;
- } else {
- return false; // could not create parent folder of the input path
- }
- }
- return true;
+ /* default */boolean createFolder(Path folderPath, IWorkspaceRoot root,
+ IProgressMonitor monitor) {
+ IResource baseResource = root.findMember(folderPath);
+ if (!(baseResource == null)) {
+ if (baseResource.exists()) {
+ return true;
+ }
+ } else { // if folder does not exist
+ if (folderPath.segmentCount() <= 1) {
+ return true;
+ }
+ Path oneSegmentLess = (Path) folderPath.removeLastSegments(1); // get
+ // parent
+ if (createFolder(oneSegmentLess, root, monitor)) { // create parent
+ // folder
+ IResource resource = root.findMember(oneSegmentLess);
+ if (resource == null) {
+ return false; // resource is null
+ } else if (!resource.exists()
+ || !(resource instanceof IContainer)) {
+ return false; // resource does not exist
+ }
+ final IFolder folder = root.getFolder(folderPath);
+ try {
+ folder.create(true, true, monitor);
+ } catch (CoreException e) {
+ return false;
+ }
+ return true;
+ } else {
+ return false; // could not create parent folder of the input
+ // path
+ }
+ }
+ return true;
}
-
+
/*
* We will initialize file contents with a sample text.
*/
private InputStream openContentStream() {
String contents = ""; //$NON-NLS-1$
- if (MsgEditorPreferences.getInstance().getSerializerConfig().isShowSupportEnabled()) {
-// contents = PropertiesGenerator.GENERATED_BY;
+ if (MsgEditorPreferences.getInstance().getSerializerConfig()
+ .isShowSupportEnabled()) {
+ // contents = PropertiesGenerator.GENERATED_BY;
}
return new ByteArrayInputStream(contents.getBytes());
}
- private synchronized void throwCoreException(String message) throws CoreException {
- IStatus status = new Status(IStatus.ERROR,
- "org.eclipse.babel.editor", //$NON-NLS-1$
+ private synchronized void throwCoreException(String message)
+ throws CoreException {
+ IStatus status = new Status(IStatus.ERROR, "org.eclipse.babel.editor", //$NON-NLS-1$
IStatus.OK, message, null);
throw new CoreException(status);
}
/**
- * We will accept the selection in the workbench to see if
- * we can initialize from it.
+ * We will accept the selection in the workbench to see if we can initialize
+ * from it.
+ *
* @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
*/
- public void init(
- IWorkbench workbench, IStructuredSelection structSelection) {
+ public void init(IWorkbench workbench, IStructuredSelection structSelection) {
this.selection = structSelection;
}
- public void setBundleId(String rbName) {
- defaultRbName = rbName;
- }
+ public void setBundleId(String rbName) {
+ defaultRbName = rbName;
+ }
- public void setDefaultPath(String pathName) {
- defaultPath = pathName;
- }
+ public void setDefaultPath(String pathName) {
+ defaultPath = pathName;
+ }
}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/OpenLocalizationEditorHandler.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/OpenLocalizationEditorHandler.java
index 9b3bb32..944cbd8 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/OpenLocalizationEditorHandler.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/OpenLocalizationEditorHandler.java
@@ -22,21 +22,25 @@
public class OpenLocalizationEditorHandler extends AbstractHandler {
- public OpenLocalizationEditorHandler() {
- }
+ public OpenLocalizationEditorHandler() {
+ }
- /*
- * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
- */
- public Object execute(ExecutionEvent event) throws ExecutionException {
- try {
- IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
- IWorkbenchPage page = window.getActivePage();
- page.openEditor(new LocalizationEditorInput(), LocalizationEditor.ID);
- } catch (PartInitException e) {
- throw new RuntimeException(e);
- }
- return null;
- }
+ /*
+ * @see
+ * org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.
+ * ExecutionEvent)
+ */
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ try {
+ IWorkbenchWindow window = HandlerUtil
+ .getActiveWorkbenchWindow(event);
+ IWorkbenchPage page = window.getActivePage();
+ page.openEditor(new LocalizationEditorInput(),
+ LocalizationEditor.ID);
+ } catch (PartInitException e) {
+ throw new RuntimeException(e);
+ }
+ return null;
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/ConfigureColumnsDialog.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/ConfigureColumnsDialog.java
index 6318c6a..af4b349 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/ConfigureColumnsDialog.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/ConfigureColumnsDialog.java
@@ -38,160 +38,170 @@
public class ConfigureColumnsDialog extends Dialog {
- private class ColumnField {
- Text text;
- ToolItem clearButton;
- }
+ private class ColumnField {
+ Text text;
+ ToolItem clearButton;
+ }
- private ArrayList<ColumnField> fields = new ArrayList<ColumnField>();
+ private ArrayList<ColumnField> fields = new ArrayList<ColumnField>();
- private ArrayList<String> result = new ArrayList<String>();
- private String[] initialValues;
- private Color errorColor;
+ private ArrayList<String> result = new ArrayList<String>();
+ private String[] initialValues;
+ private Color errorColor;
- private Image clearImage;
+ private Image clearImage;
- public ConfigureColumnsDialog(Shell parentShell, String[] initialValues) {
- super(parentShell);
- setShellStyle(getShellStyle() | SWT.RESIZE);
- this.initialValues = initialValues;
- }
+ public ConfigureColumnsDialog(Shell parentShell, String[] initialValues) {
+ super(parentShell);
+ setShellStyle(getShellStyle() | SWT.RESIZE);
+ this.initialValues = initialValues;
+ }
- /*
- * @see org.eclipse.jface.window.Window#open()
- */
- @Override
- public int open() {
- return super.open();
- }
+ /*
+ * @see org.eclipse.jface.window.Window#open()
+ */
+ @Override
+ public int open() {
+ return super.open();
+ }
- /*
- * @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
- */
- @Override
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Configure Columns");
- }
+ /*
+ * @see
+ * org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets
+ * .Shell)
+ */
+ @Override
+ protected void configureShell(Shell newShell) {
+ super.configureShell(newShell);
+ newShell.setText("Configure Columns");
+ }
- /*
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite composite = (Composite) super.createDialogArea(parent);
- GridLayout gridLayout = (GridLayout) composite.getLayout();
- gridLayout.numColumns = 3;
+ /*
+ * @see
+ * org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets
+ * .Composite)
+ */
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite composite = (Composite) super.createDialogArea(parent);
+ GridLayout gridLayout = (GridLayout) composite.getLayout();
+ gridLayout.numColumns = 3;
- Label label = new Label(composite, SWT.NONE);
- label.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
- label.setText("Enter \"key\", \"default\" or locale (e.g. \"de\" or \"zh_TW\"):");
- label.setLayoutData(GridDataFactory.fillDefaults().hint(300, SWT.DEFAULT).span(3, 1).create());
+ Label label = new Label(composite, SWT.NONE);
+ label.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false,
+ false));
+ label.setText("Enter \"key\", \"default\" or locale (e.g. \"de\" or \"zh_TW\"):");
+ label.setLayoutData(GridDataFactory.fillDefaults()
+ .hint(300, SWT.DEFAULT).span(3, 1).create());
- fields.add(createLanguageField(composite, "Column &1:"));
- fields.add(createLanguageField(composite, "Column &2:"));
- fields.add(createLanguageField(composite, "Column &3:"));
- fields.add(createLanguageField(composite, "Column &4:"));
+ fields.add(createLanguageField(composite, "Column &1:"));
+ fields.add(createLanguageField(composite, "Column &2:"));
+ fields.add(createLanguageField(composite, "Column &3:"));
+ fields.add(createLanguageField(composite, "Column &4:"));
- if (initialValues != null) {
- for (int i = 0; i < 4 && i < initialValues.length; i++) {
- fields.get(i).text.setText(initialValues[i]);
- }
- }
-
- ModifyListener modifyListener = new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- validate();
- }
- };
- for (ColumnField field : fields) {
- field.text.addModifyListener(modifyListener);
- }
- errorColor = new Color(Display.getCurrent(), 0xff, 0x7f, 0x7f);
+ if (initialValues != null) {
+ for (int i = 0; i < 4 && i < initialValues.length; i++) {
+ fields.get(i).text.setText(initialValues[i]);
+ }
+ }
- return composite;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#createContents(org.eclipse.swt.widgets.Composite)
- */
- @Override
- protected Control createContents(Composite parent) {
- Control contents = super.createContents(parent);
- validate();
- return contents;
- }
+ ModifyListener modifyListener = new ModifyListener() {
+ public void modifyText(ModifyEvent e) {
+ validate();
+ }
+ };
+ for (ColumnField field : fields) {
+ field.text.addModifyListener(modifyListener);
+ }
+ errorColor = new Color(Display.getCurrent(), 0xff, 0x7f, 0x7f);
- private ColumnField createLanguageField(Composite parent, String labelText) {
- Label label = new Label(parent, SWT.NONE);
- label.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
- label.setText(labelText);
+ return composite;
+ }
- Text text = new Text(parent, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
+ /*
+ * @see
+ * org.eclipse.jface.dialogs.Dialog#createContents(org.eclipse.swt.widgets
+ * .Composite)
+ */
+ @Override
+ protected Control createContents(Composite parent) {
+ Control contents = super.createContents(parent);
+ validate();
+ return contents;
+ }
- if (clearImage == null)
- clearImage = MessagesEditorPlugin.getImageDescriptor("elcl16/clear_co.gif").createImage(); //$NON-NLS-1$
-
- ToolBar toolbar = new ToolBar(parent, SWT.FLAT);
- ToolItem item = new ToolItem(toolbar, SWT.PUSH);
- item.setImage(clearImage);
- item.setToolTipText("Clear");
- item.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- for (ColumnField field : fields) {
- if (field.clearButton == e.widget) {
- field.text.setText(""); //$NON-NLS-1$
- }
- }
- }
- });
-
- ColumnField field = new ColumnField();
- field.text = text;
- field.clearButton = item;
- return field;
- }
+ private ColumnField createLanguageField(Composite parent, String labelText) {
+ Label label = new Label(parent, SWT.NONE);
+ label.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false,
+ false));
+ label.setText(labelText);
- /*
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- */
- @Override
- protected void okPressed() {
- for (ColumnField field : fields) {
- String text = field.text.getText().trim();
- if (text.length() > 0) {
- result.add(text);
- }
- }
- super.okPressed();
- errorColor.dispose();
- clearImage.dispose();
- }
+ Text text = new Text(parent, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
+ text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- public String[] getResult() {
- return result.toArray(new String[result.size()]);
- }
-
- protected void validate() {
- boolean isValid = true;
- for (ColumnField field : fields) {
- String text = field.text.getText();
- if (text.equals("") || text.equals("key") || text.equals("default")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- field.text.setBackground(null);
- } else {
- try {
- LocaleUtil.parseLocale(text);
- field.text.setBackground(null);
- } catch (IllegalArgumentException e) {
- field.text.setBackground(errorColor);
- isValid = false;
- }
- }
- }
- Button okButton = getButton(IDialogConstants.OK_ID);
- okButton.setEnabled(isValid);
- }
+ if (clearImage == null)
+ clearImage = MessagesEditorPlugin.getImageDescriptor(
+ "elcl16/clear_co.gif").createImage(); //$NON-NLS-1$
+
+ ToolBar toolbar = new ToolBar(parent, SWT.FLAT);
+ ToolItem item = new ToolItem(toolbar, SWT.PUSH);
+ item.setImage(clearImage);
+ item.setToolTipText("Clear");
+ item.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ for (ColumnField field : fields) {
+ if (field.clearButton == e.widget) {
+ field.text.setText(""); //$NON-NLS-1$
+ }
+ }
+ }
+ });
+
+ ColumnField field = new ColumnField();
+ field.text = text;
+ field.clearButton = item;
+ return field;
+ }
+
+ /*
+ * @see org.eclipse.jface.dialogs.Dialog#okPressed()
+ */
+ @Override
+ protected void okPressed() {
+ for (ColumnField field : fields) {
+ String text = field.text.getText().trim();
+ if (text.length() > 0) {
+ result.add(text);
+ }
+ }
+ super.okPressed();
+ errorColor.dispose();
+ clearImage.dispose();
+ }
+
+ public String[] getResult() {
+ return result.toArray(new String[result.size()]);
+ }
+
+ protected void validate() {
+ boolean isValid = true;
+ for (ColumnField field : fields) {
+ String text = field.text.getText();
+ if (text.equals("") || text.equals("key") || text.equals("default")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ field.text.setBackground(null);
+ } else {
+ try {
+ LocaleUtil.parseLocale(text);
+ field.text.setBackground(null);
+ } catch (IllegalArgumentException e) {
+ field.text.setBackground(errorColor);
+ isValid = false;
+ }
+ }
+ }
+ Button okButton = getButton(IDialogConstants.OK_ID);
+ okButton.setEnabled(isValid);
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditMultiLineEntryDialog.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditMultiLineEntryDialog.java
index 62947de..a910c30 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditMultiLineEntryDialog.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditMultiLineEntryDialog.java
@@ -20,54 +20,61 @@
public class EditMultiLineEntryDialog extends Dialog {
- private Text textWidget;
- private String text;
- private boolean readOnly;
-
- protected EditMultiLineEntryDialog(Shell parentShell, String initialInput, boolean readOnly) {
- super(parentShell);
- this.readOnly = readOnly;
- setShellStyle(getShellStyle() | SWT.RESIZE);
- text = initialInput;
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
- */
- @Override
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Edit Resource Bundle Entry");
- }
+ private Text textWidget;
+ private String text;
+ private boolean readOnly;
- public String getValue() {
- return text;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite composite = (Composite) super.createDialogArea(parent);
-
- int readOnly = this.readOnly ? SWT.READ_ONLY : 0;
- Text text = new Text(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | readOnly);
- text.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).hint(350, 150).create());
- text.setText(text == null ? "" : this.text);
-
- textWidget = text;
-
- return composite;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- */
- @Override
- protected void okPressed() {
- text = textWidget.getText();
- super.okPressed();
- }
+ protected EditMultiLineEntryDialog(Shell parentShell, String initialInput,
+ boolean readOnly) {
+ super(parentShell);
+ this.readOnly = readOnly;
+ setShellStyle(getShellStyle() | SWT.RESIZE);
+ text = initialInput;
+ }
+
+ /*
+ * @see
+ * org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets
+ * .Shell)
+ */
+ @Override
+ protected void configureShell(Shell newShell) {
+ super.configureShell(newShell);
+ newShell.setText("Edit Resource Bundle Entry");
+ }
+
+ public String getValue() {
+ return text;
+ }
+
+ /*
+ * @see
+ * org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets
+ * .Composite)
+ */
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite composite = (Composite) super.createDialogArea(parent);
+
+ int readOnly = this.readOnly ? SWT.READ_ONLY : 0;
+ Text text = new Text(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL
+ | SWT.BORDER | readOnly);
+ text.setLayoutData(GridDataFactory.fillDefaults().grab(true, true)
+ .hint(350, 150).create());
+ text.setText(text == null ? "" : this.text);
+
+ textWidget = text;
+
+ return composite;
+ }
+
+ /*
+ * @see org.eclipse.jface.dialogs.Dialog#okPressed()
+ */
+ @Override
+ protected void okPressed() {
+ text = textWidget.getText();
+ super.okPressed();
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditResourceBundleEntriesDialog.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditResourceBundleEntriesDialog.java
index 1ad0557..a345901 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditResourceBundleEntriesDialog.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditResourceBundleEntriesDialog.java
@@ -52,359 +52,382 @@
public class EditResourceBundleEntriesDialog extends Dialog {
- private class LocaleField {
- ResourceBundle bundle;
- Label label;
- Text text;
- Locale locale;
- String oldValue;
- boolean isReadOnly;
- Button button;
- }
+ private class LocaleField {
+ ResourceBundle bundle;
+ Label label;
+ Text text;
+ Locale locale;
+ String oldValue;
+ boolean isReadOnly;
+ Button button;
+ }
- private ResourceBundleKey resourceBundleKey;
- protected ArrayList<LocaleField> fields = new ArrayList<LocaleField>();
- private final Locale[] locales;
- private Color errorColor;
+ private ResourceBundleKey resourceBundleKey;
+ protected ArrayList<LocaleField> fields = new ArrayList<LocaleField>();
+ private final Locale[] locales;
+ private Color errorColor;
- /**
- * @param locales the locales to edit
- */
- public EditResourceBundleEntriesDialog(Shell parentShell, Locale[] locales) {
- super(parentShell);
- this.locales = locales;
- setShellStyle(getShellStyle() | SWT.RESIZE);
- }
+ /**
+ * @param locales
+ * the locales to edit
+ */
+ public EditResourceBundleEntriesDialog(Shell parentShell, Locale[] locales) {
+ super(parentShell);
+ this.locales = locales;
+ setShellStyle(getShellStyle() | SWT.RESIZE);
+ }
- public void setResourceBundleKey(ResourceBundleKey resourceBundleKey) {
- this.resourceBundleKey = resourceBundleKey;
- }
+ public void setResourceBundleKey(ResourceBundleKey resourceBundleKey) {
+ this.resourceBundleKey = resourceBundleKey;
+ }
- /*
- * @see org.eclipse.jface.window.Window#open()
- */
- @Override
- public int open() {
- if (resourceBundleKey == null)
- throw new RuntimeException("Resource bundle key not set.");
- return super.open();
- }
+ /*
+ * @see org.eclipse.jface.window.Window#open()
+ */
+ @Override
+ public int open() {
+ if (resourceBundleKey == null)
+ throw new RuntimeException("Resource bundle key not set.");
+ return super.open();
+ }
- /*
- * @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
- */
- @Override
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Edit Resource Bundle Entries");
- }
+ /*
+ * @see
+ * org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets
+ * .Shell)
+ */
+ @Override
+ protected void configureShell(Shell newShell) {
+ super.configureShell(newShell);
+ newShell.setText("Edit Resource Bundle Entries");
+ }
- /*
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite composite = (Composite) super.createDialogArea(parent);
- GridLayout gridLayout = (GridLayout) composite.getLayout();
- gridLayout.numColumns = 3;
+ /*
+ * @see
+ * org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets
+ * .Composite)
+ */
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite composite = (Composite) super.createDialogArea(parent);
+ GridLayout gridLayout = (GridLayout) composite.getLayout();
+ gridLayout.numColumns = 3;
- Label keyLabel = new Label(composite, SWT.NONE);
- keyLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
- keyLabel.setText("&Key:");
+ Label keyLabel = new Label(composite, SWT.NONE);
+ keyLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false,
+ false));
+ keyLabel.setText("&Key:");
- int style = SWT.SINGLE | SWT.LEAD | SWT.BORDER | SWT.READ_ONLY;
- Text keyText = new Text(composite, style);
- keyText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- keyText.setText(resourceBundleKey.getName());
+ int style = SWT.SINGLE | SWT.LEAD | SWT.BORDER | SWT.READ_ONLY;
+ Text keyText = new Text(composite, style);
+ keyText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
+ keyText.setText(resourceBundleKey.getName());
- new Label(composite, SWT.NONE); // spacer
+ new Label(composite, SWT.NONE); // spacer
- for (Locale locale : locales) {
- if (locale.getLanguage().equals("")) { //$NON-NLS-1$
- fields.add(createLocaleField(composite, locale, "&Default Bundle:"));
- } else {
- fields.add(createLocaleField(composite, locale, "&" + locale.getDisplayName() + ":"));
- }
- }
+ for (Locale locale : locales) {
+ if (locale.getLanguage().equals("")) { //$NON-NLS-1$
+ fields.add(createLocaleField(composite, locale,
+ "&Default Bundle:"));
+ } else {
+ fields.add(createLocaleField(composite, locale,
+ "&" + locale.getDisplayName() + ":"));
+ }
+ }
- // Set focus on first editable field
- if (fields.size() > 0) {
- for (int i = 0; i < fields.size(); i++) {
- if (fields.get(i).text.getEditable()) {
- fields.get(i).text.setFocus();
- break;
- }
- }
- }
+ // Set focus on first editable field
+ if (fields.size() > 0) {
+ for (int i = 0; i < fields.size(); i++) {
+ if (fields.get(i).text.getEditable()) {
+ fields.get(i).text.setFocus();
+ break;
+ }
+ }
+ }
- Label label = new Label(composite, SWT.NONE);
- label.setLayoutData(GridDataFactory.fillDefaults().span(3, 1).create());
- label.setText("Note: The following escape sequences are allowed: \\r, \\n, \\t, \\\\");
+ Label label = new Label(composite, SWT.NONE);
+ label.setLayoutData(GridDataFactory.fillDefaults().span(3, 1).create());
+ label.setText("Note: The following escape sequences are allowed: \\r, \\n, \\t, \\\\");
- ModifyListener modifyListener = new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- validate();
- }
- };
- for (LocaleField field : fields) {
- field.text.addModifyListener(modifyListener);
- }
- errorColor = new Color(Display.getCurrent(), 0xff, 0x7f, 0x7f);
-
- return composite;
- }
+ ModifyListener modifyListener = new ModifyListener() {
+ public void modifyText(ModifyEvent e) {
+ validate();
+ }
+ };
+ for (LocaleField field : fields) {
+ field.text.addModifyListener(modifyListener);
+ }
+ errorColor = new Color(Display.getCurrent(), 0xff, 0x7f, 0x7f);
- private LocaleField createLocaleField(Composite parent, Locale locale, String localeLabel) {
- ResourceBundle bundle = resourceBundleKey.getFamily().getBundle(locale);
+ return composite;
+ }
- Label label = new Label(parent, SWT.NONE);
- label.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
- label.setText(localeLabel);
+ private LocaleField createLocaleField(Composite parent, Locale locale,
+ String localeLabel) {
+ ResourceBundle bundle = resourceBundleKey.getFamily().getBundle(locale);
- boolean readOnly = bundle == null || bundle.isReadOnly();
- int style = SWT.SINGLE | SWT.LEAD | SWT.BORDER | (readOnly ? SWT.READ_ONLY : 0);
- Text text = new Text(parent, style);
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
+ Label label = new Label(parent, SWT.NONE);
+ label.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false,
+ false));
+ label.setText(localeLabel);
- String value = null;
- if (bundle != null) {
- try {
- value = bundle.getString(resourceBundleKey.getName());
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- }
- if (value == null) {
- if (readOnly) {
- value = "(Key does not exist)";
- } else {
- value = ""; // TODO Indicate that the entry is missing: perhaps red background
- }
- }
- text.setText(escape(value));
- } else {
- text.setText("(Resource bundle not found)");
- }
+ boolean readOnly = bundle == null || bundle.isReadOnly();
+ int style = SWT.SINGLE | SWT.LEAD | SWT.BORDER
+ | (readOnly ? SWT.READ_ONLY : 0);
+ Text text = new Text(parent, style);
+ text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- Button button = new Button(parent, SWT.PUSH);
- button.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
- button.setText("..."); //$NON-NLS-1$
- button.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- for (LocaleField field : fields) {
- if (e.widget == field.button) {
- EditMultiLineEntryDialog dialog = new EditMultiLineEntryDialog(
- getShell(),
- unescape(field.text.getText()),
- field.isReadOnly);
- if (dialog.open() == Window.OK) {
- field.text.setText(escape(dialog.getValue()));
- }
- }
- }
- }
- });
+ String value = null;
+ if (bundle != null) {
+ try {
+ value = bundle.getString(resourceBundleKey.getName());
+ } catch (CoreException e) {
+ MessagesEditorPlugin.log(e);
+ }
+ if (value == null) {
+ if (readOnly) {
+ value = "(Key does not exist)";
+ } else {
+ value = ""; // TODO Indicate that the entry is missing:
+ // perhaps red background
+ }
+ }
+ text.setText(escape(value));
+ } else {
+ text.setText("(Resource bundle not found)");
+ }
- LocaleField field = new LocaleField();
- field.bundle = bundle;
- field.label = label;
- field.text = text;
- field.locale = locale;
- field.oldValue = value;
- field.isReadOnly = readOnly;
- field.button = button;
- return field;
- }
+ Button button = new Button(parent, SWT.PUSH);
+ button.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false,
+ false));
+ button.setText("..."); //$NON-NLS-1$
+ button.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ for (LocaleField field : fields) {
+ if (e.widget == field.button) {
+ EditMultiLineEntryDialog dialog = new EditMultiLineEntryDialog(
+ getShell(), unescape(field.text.getText()),
+ field.isReadOnly);
+ if (dialog.open() == Window.OK) {
+ field.text.setText(escape(dialog.getValue()));
+ }
+ }
+ }
+ }
+ });
- /*
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- */
- @Override
- protected void okPressed() {
- for (LocaleField field : fields) {
- if (field.isReadOnly)
- continue;
- String key = resourceBundleKey.getName();
- String value = unescape(field.text.getText());
- boolean hasChanged = (field.oldValue == null && !value.equals("")) //$NON-NLS-1$
- || (field.oldValue != null && !field.oldValue.equals(value));
- if (hasChanged) {
- try {
- Object resource = field.bundle.getUnderlyingResource();
- if (resource instanceof IFile) {
- MsgEditorPreferences prefs = MsgEditorPreferences.getInstance();
+ LocaleField field = new LocaleField();
+ field.bundle = bundle;
+ field.label = label;
+ field.text = text;
+ field.locale = locale;
+ field.oldValue = value;
+ field.isReadOnly = readOnly;
+ field.button = button;
+ return field;
+ }
- IMessagesResource messagesResource = new PropertiesIFileResource(
- field.locale,
- new PropertiesSerializer(prefs.getSerializerConfig()),
- new PropertiesDeserializer(prefs.getDeserializerConfig()),
- (IFile) resource, MessagesEditorPlugin.getDefault());
- MessagesBundle bundle = new MessagesBundle(messagesResource);
+ /*
+ * @see org.eclipse.jface.dialogs.Dialog#okPressed()
+ */
+ @Override
+ protected void okPressed() {
+ for (LocaleField field : fields) {
+ if (field.isReadOnly)
+ continue;
+ String key = resourceBundleKey.getName();
+ String value = unescape(field.text.getText());
+ boolean hasChanged = (field.oldValue == null && !value.equals("")) //$NON-NLS-1$
+ || (field.oldValue != null && !field.oldValue.equals(value));
+ if (hasChanged) {
+ try {
+ Object resource = field.bundle.getUnderlyingResource();
+ if (resource instanceof IFile) {
+ MsgEditorPreferences prefs = MsgEditorPreferences
+ .getInstance();
- Message message = new Message(key, field.locale);
- message.setText(value);
- bundle.addMessage(message);
+ IMessagesResource messagesResource = new PropertiesIFileResource(
+ field.locale, new PropertiesSerializer(
+ prefs.getSerializerConfig()),
+ new PropertiesDeserializer(prefs
+ .getDeserializerConfig()),
+ (IFile) resource,
+ MessagesEditorPlugin.getDefault());
+ MessagesBundle bundle = new MessagesBundle(
+ messagesResource);
- // This commented out code is how the update was done before this code was merged
- // into the Babel Message Editor. This code should be removed.
-
-// InputStream inputStream;
-// IFile file = (IFile) resource;
-//
-// inputStream = file.getContents();
-// RawBundle rawBundle;
-// try {
-// rawBundle = RawBundle.createFrom(inputStream);
-// rawBundle.put(key, value);
-// } catch (Exception e) {
-// openError("Value could not be saved: " + value, e);
-// return;
-// }
-// StringWriter stringWriter = new StringWriter();
-// rawBundle.writeTo(stringWriter);
-// byte[] bytes = stringWriter.toString().getBytes("ISO-8859-1"); //$NON-NLS-1$
-// ByteArrayInputStream newContents = new ByteArrayInputStream(bytes);
-// file.setContents(newContents, false, false, new NullProgressMonitor());
- } else {
- // Unexpected type of resource
- throw new RuntimeException("Not yet implemented."); //$NON-NLS-1$
- }
- field.bundle.put(key, value);
- } catch (Exception e) {
- openError("Value could not be saved: " + value, e);
- return;
- }
- }
- }
- super.okPressed();
- errorColor.dispose();
- }
+ Message message = new Message(key, field.locale);
+ message.setText(value);
+ bundle.addMessage(message);
- /*
- * @see org.eclipse.jface.dialogs.Dialog#getDialogBoundsStrategy()
- */
- @Override
- protected int getDialogBoundsStrategy() {
- return DIALOG_PERSISTLOCATION | DIALOG_PERSISTSIZE;
- }
+ // This commented out code is how the update was done
+ // before this code was merged
+ // into the Babel Message Editor. This code should be
+ // removed.
- /*
- * @see org.eclipse.jface.dialogs.Dialog#getDialogBoundsSettings()
- */
- @Override
- protected IDialogSettings getDialogBoundsSettings() {
- IDialogSettings settings = MessagesEditorPlugin.getDefault().getDialogSettings();
- String sectionName = "EditResourceBundleEntriesDialog"; //$NON-NLS-1$
- IDialogSettings section = settings.getSection(sectionName);
- if (section == null)
- section = settings.addNewSection(sectionName);
- return section;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#getInitialSize()
- */
- @Override
- protected Point getInitialSize() {
- Point initialSize = super.getInitialSize();
- // Make sure that all locales are visible
- Point size = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
- if (initialSize.y < size.y)
- initialSize.y = size.y;
- return initialSize;
- }
+ // InputStream inputStream;
+ // IFile file = (IFile) resource;
+ //
+ // inputStream = file.getContents();
+ // RawBundle rawBundle;
+ // try {
+ // rawBundle = RawBundle.createFrom(inputStream);
+ // rawBundle.put(key, value);
+ // } catch (Exception e) {
+ // openError("Value could not be saved: " + value, e);
+ // return;
+ // }
+ // StringWriter stringWriter = new StringWriter();
+ // rawBundle.writeTo(stringWriter);
+ // byte[] bytes = stringWriter.toString().getBytes("ISO-8859-1"); //$NON-NLS-1$
+ // ByteArrayInputStream newContents = new
+ // ByteArrayInputStream(bytes);
+ // file.setContents(newContents, false, false, new
+ // NullProgressMonitor());
+ } else {
+ // Unexpected type of resource
+ throw new RuntimeException("Not yet implemented."); //$NON-NLS-1$
+ }
+ field.bundle.put(key, value);
+ } catch (Exception e) {
+ openError("Value could not be saved: " + value, e);
+ return;
+ }
+ }
+ }
+ super.okPressed();
+ errorColor.dispose();
+ }
- protected void validate() {
- boolean isValid = true;
- for (LocaleField field : fields) {
- try {
- unescape(field.text.getText());
- field.text.setBackground(null);
- } catch (IllegalArgumentException e) {
- field.text.setBackground(errorColor);
- isValid = false;
- }
- }
- Button okButton = getButton(IDialogConstants.OK_ID);
- okButton.setEnabled(isValid);
- }
-
- private void openError(String message, Exception e) {
- IStatus status;
- if (e instanceof CoreException) {
- CoreException coreException = (CoreException) e;
- status = coreException.getStatus();
- } else {
- status = new Status(IStatus.ERROR, "<dummy>", e.getMessage(), e); //$NON-NLS-1$
- }
- e.printStackTrace();
- ErrorDialog.openError(getParentShell(), "Error", message, status);
- }
+ /*
+ * @see org.eclipse.jface.dialogs.Dialog#getDialogBoundsStrategy()
+ */
+ @Override
+ protected int getDialogBoundsStrategy() {
+ return DIALOG_PERSISTLOCATION | DIALOG_PERSISTSIZE;
+ }
- /**
- * Escapes line separators, tabulators and double backslashes.
- *
- * @param str
- * @return the escaped string
- */
- public static String escape(String str) {
- StringBuilder builder = new StringBuilder(str.length() + 10);
- for (int i = 0; i < str.length(); i++) {
- char c = str.charAt(i);
- switch (c) {
- case '\r' :
- builder.append("\\r"); //$NON-NLS-1$
- break;
- case '\n' :
- builder.append("\\n"); //$NON-NLS-1$
- break;
- case '\t' :
- builder.append("\\t"); //$NON-NLS-1$
- break;
- case '\\' :
- builder.append("\\\\"); //$NON-NLS-1$
- break;
- default :
- builder.append(c);
- break;
- }
- }
- return builder.toString();
- }
+ /*
+ * @see org.eclipse.jface.dialogs.Dialog#getDialogBoundsSettings()
+ */
+ @Override
+ protected IDialogSettings getDialogBoundsSettings() {
+ IDialogSettings settings = MessagesEditorPlugin.getDefault()
+ .getDialogSettings();
+ String sectionName = "EditResourceBundleEntriesDialog"; //$NON-NLS-1$
+ IDialogSettings section = settings.getSection(sectionName);
+ if (section == null)
+ section = settings.addNewSection(sectionName);
+ return section;
+ }
- /**
- * Unescapes line separators, tabulators and double backslashes.
- *
- * @param str
- * @return the unescaped string
- * @throws IllegalArgumentException when an invalid or unexpected escape is encountered
- */
- public static String unescape(String str) {
- StringBuilder builder = new StringBuilder(str.length() + 10);
- for (int i = 0; i < str.length(); i++) {
- char c = str.charAt(i);
- if (c == '\\') {
- switch (str.charAt(i + 1)) {
- case 'r' :
- builder.append('\r');
- break;
- case 'n' :
- builder.append('\n');
- break;
- case 't' :
- builder.append('\t');
- break;
- case '\\' :
- builder.append('\\');
- break;
- default :
- throw new IllegalArgumentException("Invalid escape sequence.");
- }
- i++;
- } else {
- builder.append(c);
- }
- }
- return builder.toString();
- }
+ /*
+ * @see org.eclipse.jface.dialogs.Dialog#getInitialSize()
+ */
+ @Override
+ protected Point getInitialSize() {
+ Point initialSize = super.getInitialSize();
+ // Make sure that all locales are visible
+ Point size = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
+ if (initialSize.y < size.y)
+ initialSize.y = size.y;
+ return initialSize;
+ }
+
+ protected void validate() {
+ boolean isValid = true;
+ for (LocaleField field : fields) {
+ try {
+ unescape(field.text.getText());
+ field.text.setBackground(null);
+ } catch (IllegalArgumentException e) {
+ field.text.setBackground(errorColor);
+ isValid = false;
+ }
+ }
+ Button okButton = getButton(IDialogConstants.OK_ID);
+ okButton.setEnabled(isValid);
+ }
+
+ private void openError(String message, Exception e) {
+ IStatus status;
+ if (e instanceof CoreException) {
+ CoreException coreException = (CoreException) e;
+ status = coreException.getStatus();
+ } else {
+ status = new Status(IStatus.ERROR, "<dummy>", e.getMessage(), e); //$NON-NLS-1$
+ }
+ e.printStackTrace();
+ ErrorDialog.openError(getParentShell(), "Error", message, status);
+ }
+
+ /**
+ * Escapes line separators, tabulators and double backslashes.
+ *
+ * @param str
+ * @return the escaped string
+ */
+ public static String escape(String str) {
+ StringBuilder builder = new StringBuilder(str.length() + 10);
+ for (int i = 0; i < str.length(); i++) {
+ char c = str.charAt(i);
+ switch (c) {
+ case '\r':
+ builder.append("\\r"); //$NON-NLS-1$
+ break;
+ case '\n':
+ builder.append("\\n"); //$NON-NLS-1$
+ break;
+ case '\t':
+ builder.append("\\t"); //$NON-NLS-1$
+ break;
+ case '\\':
+ builder.append("\\\\"); //$NON-NLS-1$
+ break;
+ default:
+ builder.append(c);
+ break;
+ }
+ }
+ return builder.toString();
+ }
+
+ /**
+ * Unescapes line separators, tabulators and double backslashes.
+ *
+ * @param str
+ * @return the unescaped string
+ * @throws IllegalArgumentException
+ * when an invalid or unexpected escape is encountered
+ */
+ public static String unescape(String str) {
+ StringBuilder builder = new StringBuilder(str.length() + 10);
+ for (int i = 0; i < str.length(); i++) {
+ char c = str.charAt(i);
+ if (c == '\\') {
+ switch (str.charAt(i + 1)) {
+ case 'r':
+ builder.append('\r');
+ break;
+ case 'n':
+ builder.append('\n');
+ break;
+ case 't':
+ builder.append('\t');
+ break;
+ case '\\':
+ builder.append('\\');
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Invalid escape sequence.");
+ }
+ i++;
+ } else {
+ builder.append(c);
+ }
+ }
+ return builder.toString();
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptions.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptions.java
index 7b6ff5b..10b74cb 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptions.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptions.java
@@ -12,8 +12,8 @@
public class FilterOptions {
- public boolean filterPlugins;
- public String[] pluginPatterns;
- public boolean keysWithMissingEntriesOnly;
+ public boolean filterPlugins;
+ public String[] pluginPatterns;
+ public boolean keysWithMissingEntriesOnly;
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptionsDialog.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptionsDialog.java
index ae4e038..2d13ac9 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptionsDialog.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptionsDialog.java
@@ -23,90 +23,98 @@
public class FilterOptionsDialog extends Dialog {
- private static final String SEPARATOR = ","; //$NON-NLS-1$
+ private static final String SEPARATOR = ","; //$NON-NLS-1$
- private Button enablePluginPatterns;
- private Button keysWithMissingEntriesOnly;
- private Text pluginPatterns;
-
- private FilterOptions initialOptions;
- private FilterOptions result;
+ private Button enablePluginPatterns;
+ private Button keysWithMissingEntriesOnly;
+ private Text pluginPatterns;
- public FilterOptionsDialog(Shell shell) {
- super(shell);
- }
+ private FilterOptions initialOptions;
+ private FilterOptions result;
- public void setInitialFilterOptions(FilterOptions initialfilterOptions) {
- this.initialOptions = initialfilterOptions;
- }
+ public FilterOptionsDialog(Shell shell) {
+ super(shell);
+ }
- /*
- * @see org.eclipse.ui.dialogs.SelectionDialog#configureShell(org.eclipse.swt.widgets.Shell)
- */
- protected void configureShell(Shell shell) {
- super.configureShell(shell);
- shell.setText("Filters");
- }
+ public void setInitialFilterOptions(FilterOptions initialfilterOptions) {
+ this.initialOptions = initialfilterOptions;
+ }
- /*
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- protected Control createDialogArea(Composite parent) {
- Composite composite = (Composite) super.createDialogArea(parent);
+ /*
+ * @see
+ * org.eclipse.ui.dialogs.SelectionDialog#configureShell(org.eclipse.swt
+ * .widgets.Shell)
+ */
+ protected void configureShell(Shell shell) {
+ super.configureShell(shell);
+ shell.setText("Filters");
+ }
- // Checkbox
- enablePluginPatterns = new Button(composite, SWT.CHECK);
- enablePluginPatterns.setFocus();
- enablePluginPatterns.setText("Filter by plug-in id patterns (separated by comma):");
- enablePluginPatterns.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- pluginPatterns.setEnabled(enablePluginPatterns.getSelection());
- }
- });
- enablePluginPatterns.setSelection(initialOptions.filterPlugins);
+ /*
+ * @see
+ * org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets
+ * .Composite)
+ */
+ protected Control createDialogArea(Composite parent) {
+ Composite composite = (Composite) super.createDialogArea(parent);
- // Pattern field
- pluginPatterns = new Text(composite, SWT.SINGLE | SWT.BORDER);
- GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
- data.widthHint = convertWidthInCharsToPixels(59);
- pluginPatterns.setLayoutData(data);
- pluginPatterns.setEnabled(initialOptions.filterPlugins);
- if (initialOptions.pluginPatterns != null) {
- StringBuilder builder = new StringBuilder();
- String[] patterns = initialOptions.pluginPatterns;
- for (String pattern : patterns) {
- if (builder.length() > 0) {
- builder.append(SEPARATOR);
- builder.append(" ");
- }
- builder.append(pattern);
- }
- pluginPatterns.setText(builder.toString());
- }
-
- keysWithMissingEntriesOnly = new Button(composite, SWT.CHECK);
- keysWithMissingEntriesOnly.setText("Keys with missing entries only");
- keysWithMissingEntriesOnly.setSelection(initialOptions.keysWithMissingEntriesOnly);
+ // Checkbox
+ enablePluginPatterns = new Button(composite, SWT.CHECK);
+ enablePluginPatterns.setFocus();
+ enablePluginPatterns
+ .setText("Filter by plug-in id patterns (separated by comma):");
+ enablePluginPatterns.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ pluginPatterns.setEnabled(enablePluginPatterns.getSelection());
+ }
+ });
+ enablePluginPatterns.setSelection(initialOptions.filterPlugins);
- applyDialogFont(parent);
- return parent;
- }
+ // Pattern field
+ pluginPatterns = new Text(composite, SWT.SINGLE | SWT.BORDER);
+ GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL
+ | GridData.GRAB_HORIZONTAL);
+ data.widthHint = convertWidthInCharsToPixels(59);
+ pluginPatterns.setLayoutData(data);
+ pluginPatterns.setEnabled(initialOptions.filterPlugins);
+ if (initialOptions.pluginPatterns != null) {
+ StringBuilder builder = new StringBuilder();
+ String[] patterns = initialOptions.pluginPatterns;
+ for (String pattern : patterns) {
+ if (builder.length() > 0) {
+ builder.append(SEPARATOR);
+ builder.append(" ");
+ }
+ builder.append(pattern);
+ }
+ pluginPatterns.setText(builder.toString());
+ }
- protected void okPressed() {
- String patterns = pluginPatterns.getText();
- result = new FilterOptions();
- result.filterPlugins = enablePluginPatterns.getSelection();
- String[] split = patterns.split(SEPARATOR);
- for (int i = 0; i < split.length; i++) {
- split[i] = split[i].trim();
- }
- result.pluginPatterns = split;
- result.keysWithMissingEntriesOnly = keysWithMissingEntriesOnly.getSelection();
- super.okPressed();
- }
-
- public FilterOptions getResult() {
- return result;
- }
-
+ keysWithMissingEntriesOnly = new Button(composite, SWT.CHECK);
+ keysWithMissingEntriesOnly.setText("Keys with missing entries only");
+ keysWithMissingEntriesOnly
+ .setSelection(initialOptions.keysWithMissingEntriesOnly);
+
+ applyDialogFont(parent);
+ return parent;
+ }
+
+ protected void okPressed() {
+ String patterns = pluginPatterns.getText();
+ result = new FilterOptions();
+ result.filterPlugins = enablePluginPatterns.getSelection();
+ String[] split = patterns.split(SEPARATOR);
+ for (int i = 0; i < split.length; i++) {
+ split[i] = split[i].trim();
+ }
+ result.pluginPatterns = split;
+ result.keysWithMissingEntriesOnly = keysWithMissingEntriesOnly
+ .getSelection();
+ super.okPressed();
+ }
+
+ public FilterOptions getResult() {
+ return result;
+ }
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditor.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditor.java
index f2b9223..fa1a606 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditor.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditor.java
@@ -105,1063 +105,1063 @@
@SuppressWarnings("restriction")
public class LocalizationEditor extends EditorPart {
- private final class LocalizationLabelProvider extends ColumnLabelProvider {
+ private final class LocalizationLabelProvider extends ColumnLabelProvider {
- private final Object columnConfig;
+ private final Object columnConfig;
- public LocalizationLabelProvider(Object columnConfig) {
- this.columnConfig = columnConfig;
- }
+ public LocalizationLabelProvider(Object columnConfig) {
+ this.columnConfig = columnConfig;
+ }
- @Override
- public String getText(Object element) {
- ResourceBundleKey key = (ResourceBundleKey) element;
- if (columnConfig == KEY) {
- return key.getName();
- }
- Locale locale = (Locale) columnConfig;
- String value;
- try {
- value = key.getValue(locale);
- } catch (CoreException e) {
- value = null;
- MessagesEditorPlugin.log(e);
- }
- if (value == null) {
- value = "";
- }
- return value;
- }
- }
+ @Override
+ public String getText(Object element) {
+ ResourceBundleKey key = (ResourceBundleKey) element;
+ if (columnConfig == KEY) {
+ return key.getName();
+ }
+ Locale locale = (Locale) columnConfig;
+ String value;
+ try {
+ value = key.getValue(locale);
+ } catch (CoreException e) {
+ value = null;
+ MessagesEditorPlugin.log(e);
+ }
+ if (value == null) {
+ value = "";
+ }
+ return value;
+ }
+ }
- private class EditEntryAction extends Action {
- public EditEntryAction() {
- super("&Edit", IAction.AS_PUSH_BUTTON);
- }
+ private class EditEntryAction extends Action {
+ public EditEntryAction() {
+ super("&Edit", IAction.AS_PUSH_BUTTON);
+ }
- /*
- * @see org.eclipse.jface.action.Action#run()
- */
- @Override
- public void run() {
- ResourceBundleKey key = getSelectedEntry();
- if (key == null) {
- return;
- }
- Shell shell = Display.getCurrent().getActiveShell();
- Locale[] locales = getLocales();
- EditResourceBundleEntriesDialog dialog = new EditResourceBundleEntriesDialog(
- shell, locales);
- dialog.setResourceBundleKey(key);
- if (dialog.open() == Window.OK) {
- updateLabels();
- }
- }
- }
+ /*
+ * @see org.eclipse.jface.action.Action#run()
+ */
+ @Override
+ public void run() {
+ ResourceBundleKey key = getSelectedEntry();
+ if (key == null) {
+ return;
+ }
+ Shell shell = Display.getCurrent().getActiveShell();
+ Locale[] locales = getLocales();
+ EditResourceBundleEntriesDialog dialog = new EditResourceBundleEntriesDialog(
+ shell, locales);
+ dialog.setResourceBundleKey(key);
+ if (dialog.open() == Window.OK) {
+ updateLabels();
+ }
+ }
+ }
- private class ConfigureColumnsAction extends Action {
- public ConfigureColumnsAction() {
- super(null, IAction.AS_PUSH_BUTTON);
- setImageDescriptor(MessagesEditorPlugin
- .getImageDescriptor("elcl16/conf_columns.gif"));
- setToolTipText("Configure Columns");
- }
+ private class ConfigureColumnsAction extends Action {
+ public ConfigureColumnsAction() {
+ super(null, IAction.AS_PUSH_BUTTON);
+ setImageDescriptor(MessagesEditorPlugin
+ .getImageDescriptor("elcl16/conf_columns.gif"));
+ setToolTipText("Configure Columns");
+ }
- /*
- * @see org.eclipse.jface.action.Action#run()
- */
- @Override
- public void run() {
- Shell shell = Display.getCurrent().getActiveShell();
- String[] values = new String[columnConfigs.length];
- for (int i = 0; i < columnConfigs.length; i++) {
- String config = columnConfigs[i].toString();
- if (config.equals("")) {
- config = "default"; //$NON-NLS-1$
- }
- values[i] = config;
- }
- ConfigureColumnsDialog dialog = new ConfigureColumnsDialog(shell,
- values);
- if (dialog.open() == Window.OK) {
- String[] result = dialog.getResult();
- Object[] newConfigs = new Object[result.length];
- for (int i = 0; i < newConfigs.length; i++) {
- if (result[i].equals("key")) { //$NON-NLS-1$
- newConfigs[i] = KEY;
- } else if (result[i].equals("default")) { //$NON-NLS-1$
- newConfigs[i] = new Locale("");
- } else {
- newConfigs[i] = LocaleUtil.parseLocale(result[i]);
- }
- }
- setColumns(newConfigs);
- }
- }
- }
+ /*
+ * @see org.eclipse.jface.action.Action#run()
+ */
+ @Override
+ public void run() {
+ Shell shell = Display.getCurrent().getActiveShell();
+ String[] values = new String[columnConfigs.length];
+ for (int i = 0; i < columnConfigs.length; i++) {
+ String config = columnConfigs[i].toString();
+ if (config.equals("")) {
+ config = "default"; //$NON-NLS-1$
+ }
+ values[i] = config;
+ }
+ ConfigureColumnsDialog dialog = new ConfigureColumnsDialog(shell,
+ values);
+ if (dialog.open() == Window.OK) {
+ String[] result = dialog.getResult();
+ Object[] newConfigs = new Object[result.length];
+ for (int i = 0; i < newConfigs.length; i++) {
+ if (result[i].equals("key")) { //$NON-NLS-1$
+ newConfigs[i] = KEY;
+ } else if (result[i].equals("default")) { //$NON-NLS-1$
+ newConfigs[i] = new Locale("");
+ } else {
+ newConfigs[i] = LocaleUtil.parseLocale(result[i]);
+ }
+ }
+ setColumns(newConfigs);
+ }
+ }
+ }
- private class EditFilterOptionsAction extends Action {
- public EditFilterOptionsAction() {
- super(null, IAction.AS_PUSH_BUTTON);
- setImageDescriptor(MessagesEditorPlugin
- .getImageDescriptor("elcl16/filter_obj.gif"));
- setToolTipText("Edit Filter Options");
- }
+ private class EditFilterOptionsAction extends Action {
+ public EditFilterOptionsAction() {
+ super(null, IAction.AS_PUSH_BUTTON);
+ setImageDescriptor(MessagesEditorPlugin
+ .getImageDescriptor("elcl16/filter_obj.gif"));
+ setToolTipText("Edit Filter Options");
+ }
- /*
- * @see org.eclipse.jface.action.Action#run()
- */
- @Override
- public void run() {
- Shell shell = Display.getCurrent().getActiveShell();
- FilterOptionsDialog dialog = new FilterOptionsDialog(shell);
- dialog.setInitialFilterOptions(filterOptions);
- if (dialog.open() == Window.OK) {
- filterOptions = dialog.getResult();
- refresh();
- updateFilterLabel();
- }
- }
- }
+ /*
+ * @see org.eclipse.jface.action.Action#run()
+ */
+ @Override
+ public void run() {
+ Shell shell = Display.getCurrent().getActiveShell();
+ FilterOptionsDialog dialog = new FilterOptionsDialog(shell);
+ dialog.setInitialFilterOptions(filterOptions);
+ if (dialog.open() == Window.OK) {
+ filterOptions = dialog.getResult();
+ refresh();
+ updateFilterLabel();
+ }
+ }
+ }
- private class RefreshAction extends Action {
- public RefreshAction() {
- super(null, IAction.AS_PUSH_BUTTON);
- setImageDescriptor(MessagesEditorPlugin
- .getImageDescriptor("elcl16/refresh.gif"));
- setToolTipText("Refresh");
- }
+ private class RefreshAction extends Action {
+ public RefreshAction() {
+ super(null, IAction.AS_PUSH_BUTTON);
+ setImageDescriptor(MessagesEditorPlugin
+ .getImageDescriptor("elcl16/refresh.gif"));
+ setToolTipText("Refresh");
+ }
- /*
- * @see org.eclipse.jface.action.Action#run()
- */
- @Override
- public void run() {
- MessagesEditorPlugin.disposeModel();
- entryList = new ResourceBundleKeyList(new ResourceBundleKey[0]);
- tableViewer.getTable().setItemCount(0);
- updateLabels();
- refresh();
- }
- }
+ /*
+ * @see org.eclipse.jface.action.Action#run()
+ */
+ @Override
+ public void run() {
+ MessagesEditorPlugin.disposeModel();
+ entryList = new ResourceBundleKeyList(new ResourceBundleKey[0]);
+ tableViewer.getTable().setItemCount(0);
+ updateLabels();
+ refresh();
+ }
+ }
- private class BundleStringComparator implements
- Comparator<ResourceBundleKey> {
- private final Locale locale;
+ private class BundleStringComparator implements
+ Comparator<ResourceBundleKey> {
+ private final Locale locale;
- public BundleStringComparator(Locale locale) {
- this.locale = locale;
- }
+ public BundleStringComparator(Locale locale) {
+ this.locale = locale;
+ }
- public int compare(ResourceBundleKey o1, ResourceBundleKey o2) {
- String value1 = null;
- String value2 = null;
- try {
- value1 = o1.getValue(locale);
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- }
- try {
- value2 = o2.getValue(locale);
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- }
- if (value1 == null) {
- value1 = ""; //$NON-NLS-1$
- }
- if (value2 == null) {
- value2 = ""; //$NON-NLS-1$
- }
- return value1.compareToIgnoreCase(value2);
- }
- }
+ public int compare(ResourceBundleKey o1, ResourceBundleKey o2) {
+ String value1 = null;
+ String value2 = null;
+ try {
+ value1 = o1.getValue(locale);
+ } catch (CoreException e) {
+ MessagesEditorPlugin.log(e);
+ }
+ try {
+ value2 = o2.getValue(locale);
+ } catch (CoreException e) {
+ MessagesEditorPlugin.log(e);
+ }
+ if (value1 == null) {
+ value1 = ""; //$NON-NLS-1$
+ }
+ if (value2 == null) {
+ value2 = ""; //$NON-NLS-1$
+ }
+ return value1.compareToIgnoreCase(value2);
+ }
+ }
- private class ExportAction extends Action {
- public ExportAction() {
- super(null, IAction.AS_PUSH_BUTTON);
- setImageDescriptor(MessagesEditorPlugin
- .getImageDescriptor("elcl16/export.gif"));
- setToolTipText("Export Current View to CSV or HTML File");
- }
+ private class ExportAction extends Action {
+ public ExportAction() {
+ super(null, IAction.AS_PUSH_BUTTON);
+ setImageDescriptor(MessagesEditorPlugin
+ .getImageDescriptor("elcl16/export.gif"));
+ setToolTipText("Export Current View to CSV or HTML File");
+ }
- /*
- * @see org.eclipse.jface.action.Action#run()
- */
- @Override
- public void run() {
- Shell shell = Display.getCurrent().getActiveShell();
- FileDialog dialog = new FileDialog(shell);
- dialog.setText("Export File");
- dialog.setFilterExtensions(new String[] { "*.*", "*.htm; *.html",
- "*.txt; *.csv" });
- dialog.setFilterNames(new String[] { "All Files (*.*)",
- "HTML File (*.htm; *.html)",
- "Tabulator Separated File (*.txt; *.csv)" });
- final String filename = dialog.open();
- if (filename != null) {
- BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
- public void run() {
- File file = new File(filename);
- try {
- BufferedWriter writer = new BufferedWriter(
- new OutputStreamWriter(
- new FileOutputStream(file), "UTF8")); //$NON-NLS-1$
- boolean isHtml = filename.endsWith(".htm") || filename.endsWith(".html"); //$NON-NLS-1$ //$NON-NLS-2$
- if (isHtml) {
- writer.write("" //$NON-NLS-1$
- + "<html>\r\n" //$NON-NLS-1$
- + "<head>\r\n" //$NON-NLS-1$
- + "<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">\r\n" //$NON-NLS-1$
- + "<style>\r\n" //$NON-NLS-1$
- + "table {width:100%;}\r\n" //$NON-NLS-1$
- + "td.sep {height:10px;background:#C0C0C0;}\r\n" //$NON-NLS-1$
- + "</style>\r\n" //$NON-NLS-1$
- + "</head>\r\n" //$NON-NLS-1$
- + "<body>\r\n" //$NON-NLS-1$
- + "<table width=\"100%\" border=\"1\">\r\n"); //$NON-NLS-1$
- }
+ /*
+ * @see org.eclipse.jface.action.Action#run()
+ */
+ @Override
+ public void run() {
+ Shell shell = Display.getCurrent().getActiveShell();
+ FileDialog dialog = new FileDialog(shell);
+ dialog.setText("Export File");
+ dialog.setFilterExtensions(new String[] { "*.*", "*.htm; *.html",
+ "*.txt; *.csv" });
+ dialog.setFilterNames(new String[] { "All Files (*.*)",
+ "HTML File (*.htm; *.html)",
+ "Tabulator Separated File (*.txt; *.csv)" });
+ final String filename = dialog.open();
+ if (filename != null) {
+ BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
+ public void run() {
+ File file = new File(filename);
+ try {
+ BufferedWriter writer = new BufferedWriter(
+ new OutputStreamWriter(
+ new FileOutputStream(file), "UTF8")); //$NON-NLS-1$
+ boolean isHtml = filename.endsWith(".htm") || filename.endsWith(".html"); //$NON-NLS-1$ //$NON-NLS-2$
+ if (isHtml) {
+ writer.write("" //$NON-NLS-1$
+ + "<html>\r\n" //$NON-NLS-1$
+ + "<head>\r\n" //$NON-NLS-1$
+ + "<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">\r\n" //$NON-NLS-1$
+ + "<style>\r\n" //$NON-NLS-1$
+ + "table {width:100%;}\r\n" //$NON-NLS-1$
+ + "td.sep {height:10px;background:#C0C0C0;}\r\n" //$NON-NLS-1$
+ + "</style>\r\n" //$NON-NLS-1$
+ + "</head>\r\n" //$NON-NLS-1$
+ + "<body>\r\n" //$NON-NLS-1$
+ + "<table width=\"100%\" border=\"1\">\r\n"); //$NON-NLS-1$
+ }
- int size = entryList.getSize();
- Object[] configs = LocalizationEditor.this.columnConfigs;
- int valueCount = 0;
- int missingCount = 0;
- for (int i = 0; i < size; i++) {
- ResourceBundleKey key = entryList.getKey(i);
- if (isHtml) {
- writer.write("<table border=\"1\">\r\n"); //$NON-NLS-1$
- }
- for (int j = 0; j < configs.length; j++) {
- if (isHtml) {
- writer.write("<tr><td>"); //$NON-NLS-1$
- }
- Object config = configs[j];
- if (!isHtml && j > 0) {
- writer.write("\t"); //$NON-NLS-1$
- }
- if (config == KEY) {
- writer.write(key.getName());
- } else {
- Locale locale = (Locale) config;
- String value;
- try {
- value = key.getValue(locale);
- } catch (CoreException e) {
- value = null;
- MessagesEditorPlugin.log(e);
- }
- if (value == null) {
- value = ""; //$NON-NLS-1$
- missingCount++;
- } else {
- valueCount++;
- }
- writer.write(EditResourceBundleEntriesDialog
- .escape(value));
- }
- if (isHtml) {
- writer.write("</td></tr>\r\n"); //$NON-NLS-1$
- }
- }
- if (isHtml) {
- writer.write("<tr><td class=\"sep\"> </td></tr>\r\n"); //$NON-NLS-1$
- writer.write("</table>\r\n"); //$NON-NLS-1$
- } else {
- writer.write("\r\n"); //$NON-NLS-1$
- }
- }
- if (isHtml) {
- writer.write("</body>\r\n" + "</html>\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- writer.close();
- Shell shell = Display.getCurrent().getActiveShell();
- MessageDialog.openInformation(shell, "Finished",
- "File written successfully.\n\nNumber of entries written: "
- + entryList.getSize()
- + "\nNumber of translations: "
- + valueCount + " (" + missingCount
- + " missing)");
- } catch (IOException e) {
- Shell shell = Display.getCurrent().getActiveShell();
- ErrorDialog.openError(
- shell,
- "Error",
- "Error saving file.",
- new Status(IStatus.ERROR,
- MessagesEditorPlugin.PLUGIN_ID, e
- .getMessage(), e));
- }
- }
- });
- }
- }
- }
+ int size = entryList.getSize();
+ Object[] configs = LocalizationEditor.this.columnConfigs;
+ int valueCount = 0;
+ int missingCount = 0;
+ for (int i = 0; i < size; i++) {
+ ResourceBundleKey key = entryList.getKey(i);
+ if (isHtml) {
+ writer.write("<table border=\"1\">\r\n"); //$NON-NLS-1$
+ }
+ for (int j = 0; j < configs.length; j++) {
+ if (isHtml) {
+ writer.write("<tr><td>"); //$NON-NLS-1$
+ }
+ Object config = configs[j];
+ if (!isHtml && j > 0) {
+ writer.write("\t"); //$NON-NLS-1$
+ }
+ if (config == KEY) {
+ writer.write(key.getName());
+ } else {
+ Locale locale = (Locale) config;
+ String value;
+ try {
+ value = key.getValue(locale);
+ } catch (CoreException e) {
+ value = null;
+ MessagesEditorPlugin.log(e);
+ }
+ if (value == null) {
+ value = ""; //$NON-NLS-1$
+ missingCount++;
+ } else {
+ valueCount++;
+ }
+ writer.write(EditResourceBundleEntriesDialog
+ .escape(value));
+ }
+ if (isHtml) {
+ writer.write("</td></tr>\r\n"); //$NON-NLS-1$
+ }
+ }
+ if (isHtml) {
+ writer.write("<tr><td class=\"sep\"> </td></tr>\r\n"); //$NON-NLS-1$
+ writer.write("</table>\r\n"); //$NON-NLS-1$
+ } else {
+ writer.write("\r\n"); //$NON-NLS-1$
+ }
+ }
+ if (isHtml) {
+ writer.write("</body>\r\n" + "</html>\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ writer.close();
+ Shell shell = Display.getCurrent().getActiveShell();
+ MessageDialog.openInformation(shell, "Finished",
+ "File written successfully.\n\nNumber of entries written: "
+ + entryList.getSize()
+ + "\nNumber of translations: "
+ + valueCount + " (" + missingCount
+ + " missing)");
+ } catch (IOException e) {
+ Shell shell = Display.getCurrent().getActiveShell();
+ ErrorDialog.openError(
+ shell,
+ "Error",
+ "Error saving file.",
+ new Status(IStatus.ERROR,
+ MessagesEditorPlugin.PLUGIN_ID, e
+ .getMessage(), e));
+ }
+ }
+ });
+ }
+ }
+ }
- public static final String ID = "org.eclipse.pde.nls.ui.LocalizationEditor"; //$NON-NLS-1$
+ public static final String ID = "org.eclipse.pde.nls.ui.LocalizationEditor"; //$NON-NLS-1$
- protected static final Object KEY = "key"; // used to indicate the key
- // column
+ protected static final Object KEY = "key"; // used to indicate the key
+ // column
- private static final String PREF_SECTION_NAME = "org.eclipse.pde.nls.ui.LocalizationEditor"; //$NON-NLS-1$
- private static final String PREF_SORT_ORDER = "sortOrder"; //$NON-NLS-1$
- private static final String PREF_COLUMNS = "columns"; //$NON-NLS-1$
- private static final String PREF_FILTER_OPTIONS_FILTER_PLUGINS = "filterOptions_filterPlugins"; //$NON-NLS-1$
- private static final String PREF_FILTER_OPTIONS_PLUGIN_PATTERNS = "filterOptions_pluginPatterns"; //$NON-NLS-1$
- private static final String PREF_FILTER_OPTIONS_MISSING_ONLY = "filterOptions_missingOnly"; //$NON-NLS-1$
+ private static final String PREF_SECTION_NAME = "org.eclipse.pde.nls.ui.LocalizationEditor"; //$NON-NLS-1$
+ private static final String PREF_SORT_ORDER = "sortOrder"; //$NON-NLS-1$
+ private static final String PREF_COLUMNS = "columns"; //$NON-NLS-1$
+ private static final String PREF_FILTER_OPTIONS_FILTER_PLUGINS = "filterOptions_filterPlugins"; //$NON-NLS-1$
+ private static final String PREF_FILTER_OPTIONS_PLUGIN_PATTERNS = "filterOptions_pluginPatterns"; //$NON-NLS-1$
+ private static final String PREF_FILTER_OPTIONS_MISSING_ONLY = "filterOptions_missingOnly"; //$NON-NLS-1$
- // Actions
- private EditFilterOptionsAction editFiltersAction;
- private ConfigureColumnsAction selectLanguagesAction;
- private RefreshAction refreshAction;
- private ExportAction exportAction;
+ // Actions
+ private EditFilterOptionsAction editFiltersAction;
+ private ConfigureColumnsAction selectLanguagesAction;
+ private RefreshAction refreshAction;
+ private ExportAction exportAction;
- // Form
- protected FormToolkit toolkit = new FormToolkit(Display.getCurrent());
- private Form form;
- private Image formImage;
+ // Form
+ protected FormToolkit toolkit = new FormToolkit(Display.getCurrent());
+ private Form form;
+ private Image formImage;
- // Query
- protected Composite queryComposite;
- protected Text queryText;
+ // Query
+ protected Composite queryComposite;
+ protected Text queryText;
- // Results
- private Section resultsSection;
- private Composite tableComposite;
- protected TableViewer tableViewer;
- protected Table table;
- protected ArrayList<TableColumn> columns = new ArrayList<TableColumn>();
+ // Results
+ private Section resultsSection;
+ private Composite tableComposite;
+ protected TableViewer tableViewer;
+ protected Table table;
+ protected ArrayList<TableColumn> columns = new ArrayList<TableColumn>();
- // Data and configuration
- protected LocalizationEditorInput input;
- protected ResourceBundleKeyList entryList;
- protected FilterOptions filterOptions;
+ // Data and configuration
+ protected LocalizationEditorInput input;
+ protected ResourceBundleKeyList entryList;
+ protected FilterOptions filterOptions;
- /**
- * Column configuration. Values may be either <code>KEY</code> or a
- * {@link Locale}.
- */
- protected Object[] columnConfigs;
- /**
- * Either <code>KEY</code> or a {@link Locale}.
- */
- protected Object sortOrder;
+ /**
+ * Column configuration. Values may be either <code>KEY</code> or a
+ * {@link Locale}.
+ */
+ protected Object[] columnConfigs;
+ /**
+ * Either <code>KEY</code> or a {@link Locale}.
+ */
+ protected Object sortOrder;
- private String lastQuery = "";
- protected Job searchJob;
+ private String lastQuery = "";
+ protected Job searchJob;
- private ISchedulingRule mutexRule = new ISchedulingRule() {
- public boolean contains(ISchedulingRule rule) {
- return rule == this;
- }
+ private ISchedulingRule mutexRule = new ISchedulingRule() {
+ public boolean contains(ISchedulingRule rule) {
+ return rule == this;
+ }
- public boolean isConflicting(ISchedulingRule rule) {
- return rule == this;
- }
- };
+ public boolean isConflicting(ISchedulingRule rule) {
+ return rule == this;
+ }
+ };
- private Label filteredLabel;
+ private Label filteredLabel;
- public LocalizationEditor() {
- }
+ public LocalizationEditor() {
+ }
- public ResourceBundleKey getSelectedEntry() {
- IStructuredSelection selection = (IStructuredSelection) tableViewer
- .getSelection();
- if (selection.size() == 1) {
- return (ResourceBundleKey) selection.getFirstElement();
- }
- return null;
- }
+ public ResourceBundleKey getSelectedEntry() {
+ IStructuredSelection selection = (IStructuredSelection) tableViewer
+ .getSelection();
+ if (selection.size() == 1) {
+ return (ResourceBundleKey) selection.getFirstElement();
+ }
+ return null;
+ }
- public String getQueryText() {
- return queryText.getText();
- }
+ public String getQueryText() {
+ return queryText.getText();
+ }
- @Override
- public void createPartControl(Composite parent) {
- GridData gd;
- GridLayout gridLayout;
+ @Override
+ public void createPartControl(Composite parent) {
+ GridData gd;
+ GridLayout gridLayout;
- form = toolkit.createForm(parent);
- form.setSeparatorVisible(true);
- form.setText("Localization");
+ form = toolkit.createForm(parent);
+ form.setSeparatorVisible(true);
+ form.setText("Localization");
- form.setImage(formImage = MessagesEditorPlugin.getImageDescriptor(
- "obj16/nls_editor.gif").createImage()); //$NON-NLS-1$
- toolkit.adapt(form);
- toolkit.paintBordersFor(form);
- final Composite body = form.getBody();
- gridLayout = new GridLayout();
- gridLayout.numColumns = 1;
- body.setLayout(gridLayout);
- toolkit.paintBordersFor(body);
- toolkit.decorateFormHeading(form);
+ form.setImage(formImage = MessagesEditorPlugin.getImageDescriptor(
+ "obj16/nls_editor.gif").createImage()); //$NON-NLS-1$
+ toolkit.adapt(form);
+ toolkit.paintBordersFor(form);
+ final Composite body = form.getBody();
+ gridLayout = new GridLayout();
+ gridLayout.numColumns = 1;
+ body.setLayout(gridLayout);
+ toolkit.paintBordersFor(body);
+ toolkit.decorateFormHeading(form);
- queryComposite = toolkit.createComposite(body);
- gd = new GridData(SWT.FILL, SWT.CENTER, true, false);
- queryComposite.setLayoutData(gd);
- gridLayout = new GridLayout(5, false);
- gridLayout.marginHeight = 0;
- queryComposite.setLayout(gridLayout);
- toolkit.paintBordersFor(queryComposite);
+ queryComposite = toolkit.createComposite(body);
+ gd = new GridData(SWT.FILL, SWT.CENTER, true, false);
+ queryComposite.setLayoutData(gd);
+ gridLayout = new GridLayout(5, false);
+ gridLayout.marginHeight = 0;
+ queryComposite.setLayout(gridLayout);
+ toolkit.paintBordersFor(queryComposite);
- // Form toolbar
- editFiltersAction = new EditFilterOptionsAction();
- selectLanguagesAction = new ConfigureColumnsAction();
- refreshAction = new RefreshAction();
- exportAction = new ExportAction();
- IToolBarManager toolBarManager = form.getToolBarManager();
- toolBarManager.add(refreshAction);
- toolBarManager.add(editFiltersAction);
- toolBarManager.add(selectLanguagesAction);
- toolBarManager.add(exportAction);
- form.updateToolBar();
+ // Form toolbar
+ editFiltersAction = new EditFilterOptionsAction();
+ selectLanguagesAction = new ConfigureColumnsAction();
+ refreshAction = new RefreshAction();
+ exportAction = new ExportAction();
+ IToolBarManager toolBarManager = form.getToolBarManager();
+ toolBarManager.add(refreshAction);
+ toolBarManager.add(editFiltersAction);
+ toolBarManager.add(selectLanguagesAction);
+ toolBarManager.add(exportAction);
+ form.updateToolBar();
- toolkit.createLabel(queryComposite, "Search:");
+ toolkit.createLabel(queryComposite, "Search:");
- // Query text
- queryText = toolkit.createText(queryComposite,
- "", SWT.WRAP | SWT.SINGLE); //$NON-NLS-1$
- queryText.addKeyListener(new KeyAdapter() {
- @Override
- public void keyPressed(KeyEvent e) {
- if (e.keyCode == SWT.ARROW_DOWN) {
- table.setFocus();
- } else if (e.keyCode == SWT.ESC) {
- queryText.setText(""); //$NON-NLS-1$
- }
- }
- });
- queryText.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- executeQuery();
+ // Query text
+ queryText = toolkit.createText(queryComposite,
+ "", SWT.WRAP | SWT.SINGLE); //$NON-NLS-1$
+ queryText.addKeyListener(new KeyAdapter() {
+ @Override
+ public void keyPressed(KeyEvent e) {
+ if (e.keyCode == SWT.ARROW_DOWN) {
+ table.setFocus();
+ } else if (e.keyCode == SWT.ESC) {
+ queryText.setText(""); //$NON-NLS-1$
+ }
+ }
+ });
+ queryText.addModifyListener(new ModifyListener() {
+ public void modifyText(ModifyEvent e) {
+ executeQuery();
- Object[] listeners = getListeners();
- for (int i = 0; i < listeners.length; i++) {
- IPropertyListener listener = (IPropertyListener) listeners[i];
- listener.propertyChanged(this, PROP_TITLE);
- }
- }
- });
- gd = new GridData(SWT.FILL, SWT.CENTER, true, false);
- queryText.setLayoutData(gd);
- toolkit.adapt(queryText, true, true);
+ Object[] listeners = getListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IPropertyListener listener = (IPropertyListener) listeners[i];
+ listener.propertyChanged(this, PROP_TITLE);
+ }
+ }
+ });
+ gd = new GridData(SWT.FILL, SWT.CENTER, true, false);
+ queryText.setLayoutData(gd);
+ toolkit.adapt(queryText, true, true);
- ToolBarManager toolBarManager2 = new ToolBarManager(SWT.FLAT);
- toolBarManager2.createControl(queryComposite);
- ToolBar control = toolBarManager2.getControl();
- toolkit.adapt(control);
+ ToolBarManager toolBarManager2 = new ToolBarManager(SWT.FLAT);
+ toolBarManager2.createControl(queryComposite);
+ ToolBar control = toolBarManager2.getControl();
+ toolkit.adapt(control);
- // Results section
- resultsSection = toolkit.createSection(body,
- ExpandableComposite.TITLE_BAR
- | ExpandableComposite.LEFT_TEXT_CLIENT_ALIGNMENT);
- resultsSection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
- true, 2, 1));
- resultsSection.setText("Localization Strings");
- toolkit.adapt(resultsSection);
+ // Results section
+ resultsSection = toolkit.createSection(body,
+ ExpandableComposite.TITLE_BAR
+ | ExpandableComposite.LEFT_TEXT_CLIENT_ALIGNMENT);
+ resultsSection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
+ true, 2, 1));
+ resultsSection.setText("Localization Strings");
+ toolkit.adapt(resultsSection);
- final Composite resultsComposite = toolkit.createComposite(
- resultsSection, SWT.NONE);
- toolkit.adapt(resultsComposite);
- final GridLayout gridLayout2 = new GridLayout();
- gridLayout2.marginTop = 1;
- gridLayout2.marginWidth = 1;
- gridLayout2.marginHeight = 1;
- gridLayout2.horizontalSpacing = 0;
- resultsComposite.setLayout(gridLayout2);
+ final Composite resultsComposite = toolkit.createComposite(
+ resultsSection, SWT.NONE);
+ toolkit.adapt(resultsComposite);
+ final GridLayout gridLayout2 = new GridLayout();
+ gridLayout2.marginTop = 1;
+ gridLayout2.marginWidth = 1;
+ gridLayout2.marginHeight = 1;
+ gridLayout2.horizontalSpacing = 0;
+ resultsComposite.setLayout(gridLayout2);
- filteredLabel = new Label(resultsSection, SWT.NONE);
- filteredLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER,
- false, false));
- filteredLabel.setForeground(Display.getCurrent().getSystemColor(
- SWT.COLOR_RED));
- filteredLabel.setText(""); //$NON-NLS-1$
+ filteredLabel = new Label(resultsSection, SWT.NONE);
+ filteredLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER,
+ false, false));
+ filteredLabel.setForeground(Display.getCurrent().getSystemColor(
+ SWT.COLOR_RED));
+ filteredLabel.setText(""); //$NON-NLS-1$
- toolkit.paintBordersFor(resultsComposite);
- resultsSection.setClient(resultsComposite);
- resultsSection.setTextClient(filteredLabel);
+ toolkit.paintBordersFor(resultsComposite);
+ resultsSection.setClient(resultsComposite);
+ resultsSection.setTextClient(filteredLabel);
- tableComposite = toolkit.createComposite(resultsComposite, SWT.NONE);
- tableComposite.setData(FormToolkit.KEY_DRAW_BORDER,
- FormToolkit.TREE_BORDER);
- toolkit.adapt(tableComposite);
- tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
- true));
+ tableComposite = toolkit.createComposite(resultsComposite, SWT.NONE);
+ tableComposite.setData(FormToolkit.KEY_DRAW_BORDER,
+ FormToolkit.TREE_BORDER);
+ toolkit.adapt(tableComposite);
+ tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
+ true));
- // Table
- createTableViewer();
+ // Table
+ createTableViewer();
- registerContextMenu();
+ registerContextMenu();
- // Set default configuration
- filterOptions = new FilterOptions();
- filterOptions.filterPlugins = false;
- filterOptions.pluginPatterns = new String[0];
- filterOptions.keysWithMissingEntriesOnly = false;
- sortOrder = KEY;
- columnConfigs = new Object[] { KEY, new Locale(""), new Locale("de") }; //$NON-NLS-1$ //$NON-NLS-2$
+ // Set default configuration
+ filterOptions = new FilterOptions();
+ filterOptions.filterPlugins = false;
+ filterOptions.pluginPatterns = new String[0];
+ filterOptions.keysWithMissingEntriesOnly = false;
+ sortOrder = KEY;
+ columnConfigs = new Object[] { KEY, new Locale(""), new Locale("de") }; //$NON-NLS-1$ //$NON-NLS-2$
- // Load configuration
- try {
- loadSettings();
- } catch (Exception e) {
- // Ignore
- }
+ // Load configuration
+ try {
+ loadSettings();
+ } catch (Exception e) {
+ // Ignore
+ }
- updateColumns();
- updateFilterLabel();
- table.setSortDirection(SWT.UP);
- }
+ updateColumns();
+ updateFilterLabel();
+ table.setSortDirection(SWT.UP);
+ }
- protected void updateFilterLabel() {
- if (filterOptions.filterPlugins
- || filterOptions.keysWithMissingEntriesOnly) {
- filteredLabel.setText("(filtered)");
- } else {
- filteredLabel.setText(""); //$NON-NLS-1$
- }
- filteredLabel.getParent().layout(true);
- }
+ protected void updateFilterLabel() {
+ if (filterOptions.filterPlugins
+ || filterOptions.keysWithMissingEntriesOnly) {
+ filteredLabel.setText("(filtered)");
+ } else {
+ filteredLabel.setText(""); //$NON-NLS-1$
+ }
+ filteredLabel.getParent().layout(true);
+ }
- private void loadSettings() {
- // TODO Move this to the preferences?
- IDialogSettings dialogSettings = MessagesEditorPlugin.getDefault()
- .getDialogSettings();
- IDialogSettings section = dialogSettings.getSection(PREF_SECTION_NAME);
- if (section == null) {
- return;
- }
+ private void loadSettings() {
+ // TODO Move this to the preferences?
+ IDialogSettings dialogSettings = MessagesEditorPlugin.getDefault()
+ .getDialogSettings();
+ IDialogSettings section = dialogSettings.getSection(PREF_SECTION_NAME);
+ if (section == null) {
+ return;
+ }
- // Sort order
- String sortOrderString = section.get(PREF_SORT_ORDER);
- if (sortOrderString != null) {
- if (sortOrderString.equals(KEY)) {
- sortOrder = KEY;
- } else {
- try {
- sortOrder = LocaleUtil.parseLocale(sortOrderString);
- } catch (IllegalArgumentException e) {
- // Should never happen
- }
- }
- }
+ // Sort order
+ String sortOrderString = section.get(PREF_SORT_ORDER);
+ if (sortOrderString != null) {
+ if (sortOrderString.equals(KEY)) {
+ sortOrder = KEY;
+ } else {
+ try {
+ sortOrder = LocaleUtil.parseLocale(sortOrderString);
+ } catch (IllegalArgumentException e) {
+ // Should never happen
+ }
+ }
+ }
- // Columns
- String columns = section.get(PREF_COLUMNS);
- if (columns != null) {
- String[] cols = columns.substring(1, columns.length() - 1).split(
- ","); //$NON-NLS-1$
- columnConfigs = new Object[cols.length];
- for (int i = 0; i < cols.length; i++) {
- String value = cols[i].trim();
- if (value.equals(KEY)) {
- columnConfigs[i] = KEY;
- } else if (value.equals("default")) { //$NON-NLS-1$
- columnConfigs[i] = new Locale(""); //$NON-NLS-1$
- } else {
- try {
- columnConfigs[i] = LocaleUtil.parseLocale(value);
- } catch (IllegalArgumentException e) {
- columnConfigs[i] = null;
- }
- }
- }
- }
+ // Columns
+ String columns = section.get(PREF_COLUMNS);
+ if (columns != null) {
+ String[] cols = columns.substring(1, columns.length() - 1).split(
+ ","); //$NON-NLS-1$
+ columnConfigs = new Object[cols.length];
+ for (int i = 0; i < cols.length; i++) {
+ String value = cols[i].trim();
+ if (value.equals(KEY)) {
+ columnConfigs[i] = KEY;
+ } else if (value.equals("default")) { //$NON-NLS-1$
+ columnConfigs[i] = new Locale(""); //$NON-NLS-1$
+ } else {
+ try {
+ columnConfigs[i] = LocaleUtil.parseLocale(value);
+ } catch (IllegalArgumentException e) {
+ columnConfigs[i] = null;
+ }
+ }
+ }
+ }
- // Filter options
- String filterOptions = section.get(PREF_FILTER_OPTIONS_FILTER_PLUGINS);
- this.filterOptions.filterPlugins = "true".equals(filterOptions); //$NON-NLS-1$
- String patterns = section.get(PREF_FILTER_OPTIONS_PLUGIN_PATTERNS);
- if (patterns != null) {
- String[] split = patterns.substring(1, patterns.length() - 1)
- .split(","); //$NON-NLS-1$
- for (int i = 0; i < split.length; i++) {
- split[i] = split[i].trim();
- }
- this.filterOptions.pluginPatterns = split;
- }
- this.filterOptions.keysWithMissingEntriesOnly = "true".equals(section.get(PREF_FILTER_OPTIONS_MISSING_ONLY)); //$NON-NLS-1$
+ // Filter options
+ String filterOptions = section.get(PREF_FILTER_OPTIONS_FILTER_PLUGINS);
+ this.filterOptions.filterPlugins = "true".equals(filterOptions); //$NON-NLS-1$
+ String patterns = section.get(PREF_FILTER_OPTIONS_PLUGIN_PATTERNS);
+ if (patterns != null) {
+ String[] split = patterns.substring(1, patterns.length() - 1)
+ .split(","); //$NON-NLS-1$
+ for (int i = 0; i < split.length; i++) {
+ split[i] = split[i].trim();
+ }
+ this.filterOptions.pluginPatterns = split;
+ }
+ this.filterOptions.keysWithMissingEntriesOnly = "true".equals(section.get(PREF_FILTER_OPTIONS_MISSING_ONLY)); //$NON-NLS-1$
- // TODO Save column widths
- }
+ // TODO Save column widths
+ }
- private void saveSettings() {
- IDialogSettings dialogSettings = MessagesEditorPlugin.getDefault()
- .getDialogSettings();
- IDialogSettings section = dialogSettings.getSection(PREF_SECTION_NAME);
- if (section == null) {
- section = dialogSettings.addNewSection(PREF_SECTION_NAME);
- }
- // Sort order
- section.put(PREF_SORT_ORDER, sortOrder.toString());
+ private void saveSettings() {
+ IDialogSettings dialogSettings = MessagesEditorPlugin.getDefault()
+ .getDialogSettings();
+ IDialogSettings section = dialogSettings.getSection(PREF_SECTION_NAME);
+ if (section == null) {
+ section = dialogSettings.addNewSection(PREF_SECTION_NAME);
+ }
+ // Sort order
+ section.put(PREF_SORT_ORDER, sortOrder.toString());
- // Columns
- section.put(PREF_COLUMNS, Arrays.toString(columnConfigs));
+ // Columns
+ section.put(PREF_COLUMNS, Arrays.toString(columnConfigs));
- // Filter options
- section.put(PREF_FILTER_OPTIONS_FILTER_PLUGINS,
- filterOptions.filterPlugins);
- section.put(PREF_FILTER_OPTIONS_PLUGIN_PATTERNS,
- Arrays.toString(filterOptions.pluginPatterns));
- section.put(PREF_FILTER_OPTIONS_MISSING_ONLY,
- filterOptions.keysWithMissingEntriesOnly);
- }
+ // Filter options
+ section.put(PREF_FILTER_OPTIONS_FILTER_PLUGINS,
+ filterOptions.filterPlugins);
+ section.put(PREF_FILTER_OPTIONS_PLUGIN_PATTERNS,
+ Arrays.toString(filterOptions.pluginPatterns));
+ section.put(PREF_FILTER_OPTIONS_MISSING_ONLY,
+ filterOptions.keysWithMissingEntriesOnly);
+ }
- private void createTableViewer() {
- table = new Table(tableComposite, SWT.VIRTUAL | SWT.FULL_SELECTION
- | SWT.MULTI);
- tableViewer = new TableViewer(table);
- table.setHeaderVisible(true);
- toolkit.adapt(table);
- toolkit.paintBordersFor(table);
- toolkit.adapt(table, true, true);
+ private void createTableViewer() {
+ table = new Table(tableComposite, SWT.VIRTUAL | SWT.FULL_SELECTION
+ | SWT.MULTI);
+ tableViewer = new TableViewer(table);
+ table.setHeaderVisible(true);
+ toolkit.adapt(table);
+ toolkit.paintBordersFor(table);
+ toolkit.adapt(table, true, true);
- tableViewer.setContentProvider(new ILazyContentProvider() {
- public void updateElement(int index) {
- tableViewer.replace(entryList.getKey(index), index);
- }
+ tableViewer.setContentProvider(new ILazyContentProvider() {
+ public void updateElement(int index) {
+ tableViewer.replace(entryList.getKey(index), index);
+ }
- public void dispose() {
- }
+ public void dispose() {
+ }
- public void inputChanged(Viewer viewer, Object oldInput,
- Object newInput) {
- }
- });
- tableViewer.addDoubleClickListener(new IDoubleClickListener() {
- public void doubleClick(DoubleClickEvent event) {
- new EditEntryAction().run();
- }
- });
- }
+ public void inputChanged(Viewer viewer, Object oldInput,
+ Object newInput) {
+ }
+ });
+ tableViewer.addDoubleClickListener(new IDoubleClickListener() {
+ public void doubleClick(DoubleClickEvent event) {
+ new EditEntryAction().run();
+ }
+ });
+ }
- private void registerContextMenu() {
- MenuManager menuManager = new MenuManager("#PopupMenu"); //$NON-NLS-1$
- menuManager.setRemoveAllWhenShown(true);
- menuManager.addMenuListener(new IMenuListener() {
- public void menuAboutToShow(IMenuManager menu) {
- fillContextMenu(menu);
- }
- });
- Menu contextMenu = menuManager.createContextMenu(table);
- table.setMenu(contextMenu);
- getSite().registerContextMenu(menuManager,
- getSite().getSelectionProvider());
- }
+ private void registerContextMenu() {
+ MenuManager menuManager = new MenuManager("#PopupMenu"); //$NON-NLS-1$
+ menuManager.setRemoveAllWhenShown(true);
+ menuManager.addMenuListener(new IMenuListener() {
+ public void menuAboutToShow(IMenuManager menu) {
+ fillContextMenu(menu);
+ }
+ });
+ Menu contextMenu = menuManager.createContextMenu(table);
+ table.setMenu(contextMenu);
+ getSite().registerContextMenu(menuManager,
+ getSite().getSelectionProvider());
+ }
- protected void fillContextMenu(IMenuManager menu) {
- int selectionCount = table.getSelectionCount();
- if (selectionCount == 1) {
- menu.add(new EditEntryAction());
- menu.add(new Separator());
- }
- MenuManager showInSubMenu = new MenuManager("&Show In");
- IWorkbenchWindow window = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow();
- IContributionItem item = ContributionItemFactory.VIEWS_SHOW_IN
- .create(window);
- showInSubMenu.add(item);
- menu.add(showInSubMenu);
- }
+ protected void fillContextMenu(IMenuManager menu) {
+ int selectionCount = table.getSelectionCount();
+ if (selectionCount == 1) {
+ menu.add(new EditEntryAction());
+ menu.add(new Separator());
+ }
+ MenuManager showInSubMenu = new MenuManager("&Show In");
+ IWorkbenchWindow window = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow();
+ IContributionItem item = ContributionItemFactory.VIEWS_SHOW_IN
+ .create(window);
+ showInSubMenu.add(item);
+ menu.add(showInSubMenu);
+ }
- @Override
- public void setFocus() {
- queryText.setFocus();
- }
+ @Override
+ public void setFocus() {
+ queryText.setFocus();
+ }
- @Override
- public void doSave(IProgressMonitor monitor) {
- }
+ @Override
+ public void doSave(IProgressMonitor monitor) {
+ }
- @Override
- public void doSaveAs() {
- }
+ @Override
+ public void doSaveAs() {
+ }
- @Override
- public void init(IEditorSite site, IEditorInput input)
- throws PartInitException {
- setSite(site);
- setInput(input);
- this.input = (LocalizationEditorInput) input;
- }
+ @Override
+ public void init(IEditorSite site, IEditorInput input)
+ throws PartInitException {
+ setSite(site);
+ setInput(input);
+ this.input = (LocalizationEditorInput) input;
+ }
- @Override
- public boolean isDirty() {
- return false;
- }
+ @Override
+ public boolean isDirty() {
+ return false;
+ }
- @Override
- public boolean isSaveAsAllowed() {
- return false;
- }
+ @Override
+ public boolean isSaveAsAllowed() {
+ return false;
+ }
- /*
- * @see org.eclipse.ui.part.WorkbenchPart#dispose()
- */
- @Override
- public void dispose() {
- saveSettings();
- if (formImage != null) {
- formImage.dispose();
- formImage = null;
- }
- MessagesEditorPlugin.disposeModel();
- }
+ /*
+ * @see org.eclipse.ui.part.WorkbenchPart#dispose()
+ */
+ @Override
+ public void dispose() {
+ saveSettings();
+ if (formImage != null) {
+ formImage.dispose();
+ formImage = null;
+ }
+ MessagesEditorPlugin.disposeModel();
+ }
- protected void executeQuery() {
- String pattern = queryText.getText();
- lastQuery = pattern;
- executeQuery(pattern);
- }
+ protected void executeQuery() {
+ String pattern = queryText.getText();
+ lastQuery = pattern;
+ executeQuery(pattern);
+ }
- protected void executeQuery(final String pattern) {
- if (searchJob != null) {
- searchJob.cancel();
- }
- searchJob = new Job("Localization Editor Search...") {
+ protected void executeQuery(final String pattern) {
+ if (searchJob != null) {
+ searchJob.cancel();
+ }
+ searchJob = new Job("Localization Editor Search...") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- Display.getDefault().syncExec(new Runnable() {
- public void run() {
- form.setBusy(true);
- }
- });
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ Display.getDefault().syncExec(new Runnable() {
+ public void run() {
+ form.setBusy(true);
+ }
+ });
- String keyPattern = pattern;
- if (!pattern.endsWith("*")) { //$NON-NLS-1$
- keyPattern = pattern.concat("*"); //$NON-NLS-1$
- }
- String strPattern = keyPattern;
- if (strPattern.length() > 0 && !strPattern.startsWith("*")) { //$NON-NLS-1$
- strPattern = "*".concat(strPattern); //$NON-NLS-1$
- }
+ String keyPattern = pattern;
+ if (!pattern.endsWith("*")) { //$NON-NLS-1$
+ keyPattern = pattern.concat("*"); //$NON-NLS-1$
+ }
+ String strPattern = keyPattern;
+ if (strPattern.length() > 0 && !strPattern.startsWith("*")) { //$NON-NLS-1$
+ strPattern = "*".concat(strPattern); //$NON-NLS-1$
+ }
- ResourceBundleModel model = MessagesEditorPlugin
- .getModel(new NullProgressMonitor());
- Locale[] locales = getLocales();
+ ResourceBundleModel model = MessagesEditorPlugin
+ .getModel(new NullProgressMonitor());
+ Locale[] locales = getLocales();
- // Collect keys
- ResourceBundleKey[] keys;
- if (!filterOptions.filterPlugins
- || filterOptions.pluginPatterns == null
- || filterOptions.pluginPatterns.length == 0) {
+ // Collect keys
+ ResourceBundleKey[] keys;
+ if (!filterOptions.filterPlugins
+ || filterOptions.pluginPatterns == null
+ || filterOptions.pluginPatterns.length == 0) {
- // Ensure the bundles are loaded
- for (Locale locale : locales) {
- try {
- model.loadBundles(locale);
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- }
- }
+ // Ensure the bundles are loaded
+ for (Locale locale : locales) {
+ try {
+ model.loadBundles(locale);
+ } catch (CoreException e) {
+ MessagesEditorPlugin.log(e);
+ }
+ }
- try {
- keys = model.getAllKeys();
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- keys = new ResourceBundleKey[0];
- }
- } else {
- String[] patterns = filterOptions.pluginPatterns;
- StringMatcher[] matchers = new StringMatcher[patterns.length];
- for (int i = 0; i < matchers.length; i++) {
- matchers[i] = new StringMatcher(patterns[i], true,
- false);
- }
+ try {
+ keys = model.getAllKeys();
+ } catch (CoreException e) {
+ MessagesEditorPlugin.log(e);
+ keys = new ResourceBundleKey[0];
+ }
+ } else {
+ String[] patterns = filterOptions.pluginPatterns;
+ StringMatcher[] matchers = new StringMatcher[patterns.length];
+ for (int i = 0; i < matchers.length; i++) {
+ matchers[i] = new StringMatcher(patterns[i], true,
+ false);
+ }
- int size = 0;
- ResourceBundleFamily[] allFamilies = model.getFamilies();
- ArrayList<ResourceBundleFamily> families = new ArrayList<ResourceBundleFamily>();
- for (int i = 0; i < allFamilies.length; i++) {
- ResourceBundleFamily family = allFamilies[i];
- String pluginId = family.getPluginId();
- for (StringMatcher matcher : matchers) {
- if (matcher.match(pluginId)) {
- families.add(family);
- break;
- }
- }
+ int size = 0;
+ ResourceBundleFamily[] allFamilies = model.getFamilies();
+ ArrayList<ResourceBundleFamily> families = new ArrayList<ResourceBundleFamily>();
+ for (int i = 0; i < allFamilies.length; i++) {
+ ResourceBundleFamily family = allFamilies[i];
+ String pluginId = family.getPluginId();
+ for (StringMatcher matcher : matchers) {
+ if (matcher.match(pluginId)) {
+ families.add(family);
+ break;
+ }
+ }
- }
- for (ResourceBundleFamily family : families) {
- size += family.getKeyCount();
- }
+ }
+ for (ResourceBundleFamily family : families) {
+ size += family.getKeyCount();
+ }
- ArrayList<ResourceBundleKey> filteredKeys = new ArrayList<ResourceBundleKey>(
- size);
- for (ResourceBundleFamily family : families) {
- // Ensure the bundles are loaded
- for (Locale locale : locales) {
- try {
- ResourceBundle bundle = family
- .getBundle(locale);
- if (bundle != null) {
- bundle.load();
- }
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- }
- }
+ ArrayList<ResourceBundleKey> filteredKeys = new ArrayList<ResourceBundleKey>(
+ size);
+ for (ResourceBundleFamily family : families) {
+ // Ensure the bundles are loaded
+ for (Locale locale : locales) {
+ try {
+ ResourceBundle bundle = family
+ .getBundle(locale);
+ if (bundle != null) {
+ bundle.load();
+ }
+ } catch (CoreException e) {
+ MessagesEditorPlugin.log(e);
+ }
+ }
- ResourceBundleKey[] familyKeys = family.getKeys();
- for (ResourceBundleKey key : familyKeys) {
- filteredKeys.add(key);
- }
- }
- keys = filteredKeys
- .toArray(new ResourceBundleKey[filteredKeys.size()]);
- }
+ ResourceBundleKey[] familyKeys = family.getKeys();
+ for (ResourceBundleKey key : familyKeys) {
+ filteredKeys.add(key);
+ }
+ }
+ keys = filteredKeys
+ .toArray(new ResourceBundleKey[filteredKeys.size()]);
+ }
- // Filter keys
- ArrayList<ResourceBundleKey> filtered = new ArrayList<ResourceBundleKey>();
+ // Filter keys
+ ArrayList<ResourceBundleKey> filtered = new ArrayList<ResourceBundleKey>();
- StringMatcher keyMatcher = new StringMatcher(keyPattern, true,
- false);
- StringMatcher strMatcher = new StringMatcher(strPattern, true,
- false);
- for (ResourceBundleKey key : keys) {
- if (monitor.isCanceled()) {
- return Status.OK_STATUS;
- }
+ StringMatcher keyMatcher = new StringMatcher(keyPattern, true,
+ false);
+ StringMatcher strMatcher = new StringMatcher(strPattern, true,
+ false);
+ for (ResourceBundleKey key : keys) {
+ if (monitor.isCanceled()) {
+ return Status.OK_STATUS;
+ }
- // Missing entries
- if (filterOptions.keysWithMissingEntriesOnly) {
- boolean hasMissingEntry = false;
- // Check all columns for missing values
- for (Object config : columnConfigs) {
- if (config == KEY) {
- continue;
- }
- Locale locale = (Locale) config;
- String value = null;
- try {
- value = key.getValue(locale);
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- }
- if (value == null || value.length() == 0) {
- hasMissingEntry = true;
- break;
- }
- }
- if (!hasMissingEntry) {
- continue;
- }
- }
+ // Missing entries
+ if (filterOptions.keysWithMissingEntriesOnly) {
+ boolean hasMissingEntry = false;
+ // Check all columns for missing values
+ for (Object config : columnConfigs) {
+ if (config == KEY) {
+ continue;
+ }
+ Locale locale = (Locale) config;
+ String value = null;
+ try {
+ value = key.getValue(locale);
+ } catch (CoreException e) {
+ MessagesEditorPlugin.log(e);
+ }
+ if (value == null || value.length() == 0) {
+ hasMissingEntry = true;
+ break;
+ }
+ }
+ if (!hasMissingEntry) {
+ continue;
+ }
+ }
- // Match key
- if (keyMatcher.match(key.getName())) {
- filtered.add(key);
- continue;
- }
+ // Match key
+ if (keyMatcher.match(key.getName())) {
+ filtered.add(key);
+ continue;
+ }
- // Match entries
- for (Object config : columnConfigs) {
- if (config == KEY) {
- continue;
- }
- Locale locale = (Locale) config;
- String value = null;
- try {
- value = key.getValue(locale);
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- }
- if (strMatcher.match(value)) {
- filtered.add(key);
- break;
- }
- }
- }
+ // Match entries
+ for (Object config : columnConfigs) {
+ if (config == KEY) {
+ continue;
+ }
+ Locale locale = (Locale) config;
+ String value = null;
+ try {
+ value = key.getValue(locale);
+ } catch (CoreException e) {
+ MessagesEditorPlugin.log(e);
+ }
+ if (strMatcher.match(value)) {
+ filtered.add(key);
+ break;
+ }
+ }
+ }
- ResourceBundleKey[] array = filtered
- .toArray(new ResourceBundleKey[filtered.size()]);
- if (sortOrder == KEY) {
- Arrays.sort(array, new Comparator<ResourceBundleKey>() {
- public int compare(ResourceBundleKey o1,
- ResourceBundleKey o2) {
- return o1.getName().compareToIgnoreCase(
- o2.getName());
- }
- });
- } else {
- Locale locale = (Locale) sortOrder;
- Arrays.sort(array, new BundleStringComparator(locale));
- }
- entryList = new ResourceBundleKeyList(array);
+ ResourceBundleKey[] array = filtered
+ .toArray(new ResourceBundleKey[filtered.size()]);
+ if (sortOrder == KEY) {
+ Arrays.sort(array, new Comparator<ResourceBundleKey>() {
+ public int compare(ResourceBundleKey o1,
+ ResourceBundleKey o2) {
+ return o1.getName().compareToIgnoreCase(
+ o2.getName());
+ }
+ });
+ } else {
+ Locale locale = (Locale) sortOrder;
+ Arrays.sort(array, new BundleStringComparator(locale));
+ }
+ entryList = new ResourceBundleKeyList(array);
- if (monitor.isCanceled()) {
- return Status.OK_STATUS;
- }
+ if (monitor.isCanceled()) {
+ return Status.OK_STATUS;
+ }
- final ResourceBundleKeyList entryList2 = entryList;
- Display.getDefault().syncExec(new Runnable() {
- public void run() {
- form.setBusy(false);
- if (entryList2 != null) {
- entryList = entryList2;
- }
- setSearchResult(entryList);
- }
- });
- return Status.OK_STATUS;
- }
- };
- searchJob.setSystem(true);
- searchJob.setRule(mutexRule);
- searchJob.schedule();
- }
+ final ResourceBundleKeyList entryList2 = entryList;
+ Display.getDefault().syncExec(new Runnable() {
+ public void run() {
+ form.setBusy(false);
+ if (entryList2 != null) {
+ entryList = entryList2;
+ }
+ setSearchResult(entryList);
+ }
+ });
+ return Status.OK_STATUS;
+ }
+ };
+ searchJob.setSystem(true);
+ searchJob.setRule(mutexRule);
+ searchJob.schedule();
+ }
- protected void updateTableLayout() {
- table.getParent().layout(true, true);
- }
+ protected void updateTableLayout() {
+ table.getParent().layout(true, true);
+ }
- protected void setSearchResult(ResourceBundleKeyList entryList) {
- table.removeAll();
- if (entryList != null) {
- table.setItemCount(entryList.getSize());
- } else {
- table.setItemCount(0);
- }
- updateTableLayout();
- }
+ protected void setSearchResult(ResourceBundleKeyList entryList) {
+ table.removeAll();
+ if (entryList != null) {
+ table.setItemCount(entryList.getSize());
+ } else {
+ table.setItemCount(0);
+ }
+ updateTableLayout();
+ }
- public void refresh() {
- executeQuery(lastQuery);
- }
+ public void refresh() {
+ executeQuery(lastQuery);
+ }
- public void updateLabels() {
- table.redraw();
- table.update();
- }
+ public void updateLabels() {
+ table.redraw();
+ table.update();
+ }
- /**
- * @param columnConfigs
- * an array containing <code>KEY</code> and {@link Locale} values
- */
- public void setColumns(Object[] columnConfigs) {
- this.columnConfigs = columnConfigs;
- updateColumns();
- }
+ /**
+ * @param columnConfigs
+ * an array containing <code>KEY</code> and {@link Locale} values
+ */
+ public void setColumns(Object[] columnConfigs) {
+ this.columnConfigs = columnConfigs;
+ updateColumns();
+ }
- public void updateColumns() {
- for (TableColumn column : columns) {
- column.dispose();
- }
- columns.clear();
+ public void updateColumns() {
+ for (TableColumn column : columns) {
+ column.dispose();
+ }
+ columns.clear();
- TableColumnLayout tableColumnLayout = new TableColumnLayout();
- tableComposite.setLayout(tableColumnLayout);
+ TableColumnLayout tableColumnLayout = new TableColumnLayout();
+ tableComposite.setLayout(tableColumnLayout);
- HashSet<Locale> localesToUnload = new HashSet<Locale>(4);
- Locale[] currentLocales = getLocales();
- for (Locale locale : currentLocales) {
- localesToUnload.add(locale);
- }
+ HashSet<Locale> localesToUnload = new HashSet<Locale>(4);
+ Locale[] currentLocales = getLocales();
+ for (Locale locale : currentLocales) {
+ localesToUnload.add(locale);
+ }
- // Create columns
- for (Object config : columnConfigs) {
- if (config == null) {
- continue;
- }
+ // Create columns
+ for (Object config : columnConfigs) {
+ if (config == null) {
+ continue;
+ }
- final TableViewerColumn viewerColumn = new TableViewerColumn(
- tableViewer, SWT.NONE);
- TableColumn column = viewerColumn.getColumn();
- if (config == KEY) {
- column.setText("Key");
- } else {
- Locale locale = (Locale) config;
- if (locale.getLanguage().equals("")) { //$NON-NLS-1$
- column.setText("Default Bundle");
- } else {
- String displayName = locale.getDisplayName();
- if (displayName.equals("")) {
- displayName = locale.toString();
- }
- column.setText(displayName);
- localesToUnload.remove(locale);
- }
- }
+ final TableViewerColumn viewerColumn = new TableViewerColumn(
+ tableViewer, SWT.NONE);
+ TableColumn column = viewerColumn.getColumn();
+ if (config == KEY) {
+ column.setText("Key");
+ } else {
+ Locale locale = (Locale) config;
+ if (locale.getLanguage().equals("")) { //$NON-NLS-1$
+ column.setText("Default Bundle");
+ } else {
+ String displayName = locale.getDisplayName();
+ if (displayName.equals("")) {
+ displayName = locale.toString();
+ }
+ column.setText(displayName);
+ localesToUnload.remove(locale);
+ }
+ }
- viewerColumn
- .setLabelProvider(new LocalizationLabelProvider(config));
- tableColumnLayout.setColumnData(column, new ColumnWeightData(33));
- columns.add(column);
- column.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- int size = columns.size();
- for (int i = 0; i < size; i++) {
- TableColumn column = columns.get(i);
- if (column == e.widget) {
- Object config = columnConfigs[i];
- sortOrder = config;
- table.setSortColumn(column);
- table.setSortDirection(SWT.UP);
- refresh();
- break;
- }
- }
- }
- });
- }
+ viewerColumn
+ .setLabelProvider(new LocalizationLabelProvider(config));
+ tableColumnLayout.setColumnData(column, new ColumnWeightData(33));
+ columns.add(column);
+ column.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ int size = columns.size();
+ for (int i = 0; i < size; i++) {
+ TableColumn column = columns.get(i);
+ if (column == e.widget) {
+ Object config = columnConfigs[i];
+ sortOrder = config;
+ table.setSortColumn(column);
+ table.setSortDirection(SWT.UP);
+ refresh();
+ break;
+ }
+ }
+ }
+ });
+ }
- // Update sort order
- List<Object> configs = Arrays.asList(columnConfigs);
- if (!configs.contains(sortOrder)) {
- sortOrder = KEY; // fall back to default sort order
- }
- int index = configs.indexOf(sortOrder);
- if (index != -1) {
- table.setSortColumn(columns.get(index));
- }
+ // Update sort order
+ List<Object> configs = Arrays.asList(columnConfigs);
+ if (!configs.contains(sortOrder)) {
+ sortOrder = KEY; // fall back to default sort order
+ }
+ int index = configs.indexOf(sortOrder);
+ if (index != -1) {
+ table.setSortColumn(columns.get(index));
+ }
- refresh();
- }
+ refresh();
+ }
- /*
- * @see org.eclipse.ui.part.WorkbenchPart#getAdapter(java.lang.Class)
- */
- @SuppressWarnings("unchecked")
- @Override
- public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
- if (IShowInSource.class == adapter) {
- return new IShowInSource() {
- public ShowInContext getShowInContext() {
- ResourceBundleKey entry = getSelectedEntry();
- if (entry == null) {
- return null;
- }
- ResourceBundle bundle = entry.getParent().getBundle(
- new Locale(""));
- if (bundle == null) {
- return null;
- }
- Object resource = bundle.getUnderlyingResource();
- return new ShowInContext(resource, new StructuredSelection(
- resource));
- }
- };
- }
- return super.getAdapter(adapter);
- }
+ /*
+ * @see org.eclipse.ui.part.WorkbenchPart#getAdapter(java.lang.Class)
+ */
+ @SuppressWarnings("unchecked")
+ @Override
+ public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
+ if (IShowInSource.class == adapter) {
+ return new IShowInSource() {
+ public ShowInContext getShowInContext() {
+ ResourceBundleKey entry = getSelectedEntry();
+ if (entry == null) {
+ return null;
+ }
+ ResourceBundle bundle = entry.getParent().getBundle(
+ new Locale(""));
+ if (bundle == null) {
+ return null;
+ }
+ Object resource = bundle.getUnderlyingResource();
+ return new ShowInContext(resource, new StructuredSelection(
+ resource));
+ }
+ };
+ }
+ return super.getAdapter(adapter);
+ }
- /**
- * Returns the currently displayed locales.
- *
- * @return the currently displayed locales
- */
- public Locale[] getLocales() {
- ArrayList<Locale> locales = new ArrayList<Locale>(columnConfigs.length);
- for (Object config : columnConfigs) {
- if (config instanceof Locale) {
- Locale locale = (Locale) config;
- locales.add(locale);
- }
- }
- return locales.toArray(new Locale[locales.size()]);
- }
+ /**
+ * Returns the currently displayed locales.
+ *
+ * @return the currently displayed locales
+ */
+ public Locale[] getLocales() {
+ ArrayList<Locale> locales = new ArrayList<Locale>(columnConfigs.length);
+ for (Object config : columnConfigs) {
+ if (config instanceof Locale) {
+ Locale locale = (Locale) config;
+ locales.add(locale);
+ }
+ }
+ return locales.toArray(new Locale[locales.size()]);
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInput.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInput.java
index 2ad8c7e..faa09b9 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInput.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInput.java
@@ -15,65 +15,66 @@
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPersistableElement;
-public class LocalizationEditorInput implements IEditorInput, IPersistableElement {
+public class LocalizationEditorInput implements IEditorInput,
+ IPersistableElement {
- public LocalizationEditorInput() {
- }
+ public LocalizationEditorInput() {
+ }
- /*
- * @see org.eclipse.ui.IEditorInput#exists()
- */
- public boolean exists() {
- return true;
- }
+ /*
+ * @see org.eclipse.ui.IEditorInput#exists()
+ */
+ public boolean exists() {
+ return true;
+ }
- /*
- * @see org.eclipse.ui.IEditorInput#getImageDescriptor()
- */
- public ImageDescriptor getImageDescriptor() {
- return ImageDescriptor.getMissingImageDescriptor();
- }
+ /*
+ * @see org.eclipse.ui.IEditorInput#getImageDescriptor()
+ */
+ public ImageDescriptor getImageDescriptor() {
+ return ImageDescriptor.getMissingImageDescriptor();
+ }
- /*
- * @see org.eclipse.ui.IEditorInput#getName()
- */
- public String getName() {
- return "Localization Editor";
- }
+ /*
+ * @see org.eclipse.ui.IEditorInput#getName()
+ */
+ public String getName() {
+ return "Localization Editor";
+ }
- /*
- * @see org.eclipse.ui.IEditorInput#getPersistable()
- */
- public IPersistableElement getPersistable() {
- return this;
- }
+ /*
+ * @see org.eclipse.ui.IEditorInput#getPersistable()
+ */
+ public IPersistableElement getPersistable() {
+ return this;
+ }
- /*
- * @see org.eclipse.ui.IEditorInput#getToolTipText()
- */
- public String getToolTipText() {
- return getName();
- }
+ /*
+ * @see org.eclipse.ui.IEditorInput#getToolTipText()
+ */
+ public String getToolTipText() {
+ return getName();
+ }
- /*
- * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
- */
- @SuppressWarnings("unchecked")
- public Object getAdapter(Class adapter) {
- return null;
- }
+ /*
+ * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
+ */
+ @SuppressWarnings("unchecked")
+ public Object getAdapter(Class adapter) {
+ return null;
+ }
- /*
- * @see org.eclipse.ui.IPersistableElement#getFactoryId()
- */
- public String getFactoryId() {
- return LocalizationEditorInputFactory.FACTORY_ID;
- }
-
- /*
- * @see org.eclipse.ui.IPersistable#saveState(org.eclipse.ui.IMemento)
- */
- public void saveState(IMemento memento) {
- }
-
+ /*
+ * @see org.eclipse.ui.IPersistableElement#getFactoryId()
+ */
+ public String getFactoryId() {
+ return LocalizationEditorInputFactory.FACTORY_ID;
+ }
+
+ /*
+ * @see org.eclipse.ui.IPersistable#saveState(org.eclipse.ui.IMemento)
+ */
+ public void saveState(IMemento memento) {
+ }
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInputFactory.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInputFactory.java
index 698c218..5655079 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInputFactory.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInputFactory.java
@@ -16,16 +16,17 @@
public class LocalizationEditorInputFactory implements IElementFactory {
- public static final String FACTORY_ID = "org.eclipse.pde.nls.ui.LocalizationEditorInputFactory"; //$NON-NLS-1$
+ public static final String FACTORY_ID = "org.eclipse.pde.nls.ui.LocalizationEditorInputFactory"; //$NON-NLS-1$
- public LocalizationEditorInputFactory() {
- }
+ public LocalizationEditorInputFactory() {
+ }
- /*
- * @see org.eclipse.ui.IElementFactory#createElement(org.eclipse.ui.IMemento)
- */
- public IAdaptable createElement(IMemento memento) {
- return new LocalizationEditorInput();
- }
+ /*
+ * @see
+ * org.eclipse.ui.IElementFactory#createElement(org.eclipse.ui.IMemento)
+ */
+ public IAdaptable createElement(IMemento memento) {
+ return new LocalizationEditorInput();
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundle.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundle.java
index c6b8a43..c576dda 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundle.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundle.java
@@ -25,147 +25,153 @@
import org.eclipse.jdt.core.IJarEntryResource;
/**
- * A <code>ResourceBundle</code> represents a single <code>.properties</code> file.
+ * A <code>ResourceBundle</code> represents a single <code>.properties</code>
+ * file.
* <p>
* <code>ResourceBundle</code> implements lazy loading. A bundle will be loaded
- * automatically when its entries are accessed. It can through the parent model by
- * calling {@link ResourceBundleModel#unloadBundles(Locale)} with the proper locale.
+ * automatically when its entries are accessed. It can through the parent model
+ * by calling {@link ResourceBundleModel#unloadBundles(Locale)} with the proper
+ * locale.
* </p>
*/
public class ResourceBundle extends ResourceBundleElement {
- private static boolean debug = false;
-
- /**
- * The bundle's locale.
- */
- private Locale locale;
- /**
- * The underlying resource. Either an {@link IFile} or an {@link IJarEntryResource}.
- */
- private Object resource;
+ private static boolean debug = false;
- private HashMap<String, String> entries;
+ /**
+ * The bundle's locale.
+ */
+ private Locale locale;
+ /**
+ * The underlying resource. Either an {@link IFile} or an
+ * {@link IJarEntryResource}.
+ */
+ private Object resource;
- public ResourceBundle(ResourceBundleFamily parent, Object resource, Locale locale) {
- super(parent);
- this.resource = resource;
- this.locale = locale;
- if (locale == null)
- throw new IllegalArgumentException("Locale may not be null.");
- }
+ private HashMap<String, String> entries;
- /**
- * Returns the family to which this bundle belongs.
- *
- * @return the family to which this bundle belongs
- */
- public ResourceBundleFamily getFamily() {
- return (ResourceBundleFamily) super.getParent();
- }
+ public ResourceBundle(ResourceBundleFamily parent, Object resource,
+ Locale locale) {
+ super(parent);
+ this.resource = resource;
+ this.locale = locale;
+ if (locale == null)
+ throw new IllegalArgumentException("Locale may not be null.");
+ }
- /**
- * Returns the locale.
- *
- * @return the locale
- */
- public Locale getLocale() {
- return locale;
- }
+ /**
+ * Returns the family to which this bundle belongs.
+ *
+ * @return the family to which this bundle belongs
+ */
+ public ResourceBundleFamily getFamily() {
+ return (ResourceBundleFamily) super.getParent();
+ }
- public String getString(String key) throws CoreException {
- load();
- return entries.get(key);
- }
+ /**
+ * Returns the locale.
+ *
+ * @return the locale
+ */
+ public Locale getLocale() {
+ return locale;
+ }
- /**
- * Returns the underlying resource. This may be an {@link IFile}
- * or an {@link IJarEntryResource}.
- *
- * @return the underlying resource (an {@link IFile} or an {@link IJarEntryResource})
- */
- public Object getUnderlyingResource() {
- return resource;
- }
+ public String getString(String key) throws CoreException {
+ load();
+ return entries.get(key);
+ }
- protected boolean isLoaded() {
- return entries != null;
- }
+ /**
+ * Returns the underlying resource. This may be an {@link IFile} or an
+ * {@link IJarEntryResource}.
+ *
+ * @return the underlying resource (an {@link IFile} or an
+ * {@link IJarEntryResource})
+ */
+ public Object getUnderlyingResource() {
+ return resource;
+ }
- public void load() throws CoreException {
- if (isLoaded())
- return;
- entries = new HashMap<String, String>();
+ protected boolean isLoaded() {
+ return entries != null;
+ }
- if (resource instanceof IFile) {
- if (debug) {
- System.out.println("Loading " + resource + "...");
- }
- IFile file = (IFile) resource;
- InputStream inputStream = file.getContents();
- Properties properties = new Properties();
- try {
- properties.load(inputStream);
- putAll(properties);
- } catch (IOException e) {
- MessagesEditorPlugin.log("Error reading property file.", e);
- }
- } else if (resource instanceof IJarEntryResource) {
- IJarEntryResource jarEntryResource = (IJarEntryResource) resource;
- InputStream inputStream = jarEntryResource.getContents();
- Properties properties = new Properties();
- try {
- properties.load(inputStream);
- putAll(properties);
- } catch (IOException e) {
- MessagesEditorPlugin.log("Error reading property file.", e);
- }
- } else {
- MessagesEditorPlugin.log("Unknown resource type.", new RuntimeException());
- }
- }
+ public void load() throws CoreException {
+ if (isLoaded())
+ return;
+ entries = new HashMap<String, String>();
- protected void unload() {
- entries = null;
- }
+ if (resource instanceof IFile) {
+ if (debug) {
+ System.out.println("Loading " + resource + "...");
+ }
+ IFile file = (IFile) resource;
+ InputStream inputStream = file.getContents();
+ Properties properties = new Properties();
+ try {
+ properties.load(inputStream);
+ putAll(properties);
+ } catch (IOException e) {
+ MessagesEditorPlugin.log("Error reading property file.", e);
+ }
+ } else if (resource instanceof IJarEntryResource) {
+ IJarEntryResource jarEntryResource = (IJarEntryResource) resource;
+ InputStream inputStream = jarEntryResource.getContents();
+ Properties properties = new Properties();
+ try {
+ properties.load(inputStream);
+ putAll(properties);
+ } catch (IOException e) {
+ MessagesEditorPlugin.log("Error reading property file.", e);
+ }
+ } else {
+ MessagesEditorPlugin.log("Unknown resource type.",
+ new RuntimeException());
+ }
+ }
- public boolean isReadOnly() {
- if (resource instanceof IJarEntryResource)
- return true;
- if (resource instanceof IFile) {
- IFile file = (IFile) resource;
- return file.isReadOnly() || file.isLinked();
- }
- return false;
- }
+ protected void unload() {
+ entries = null;
+ }
- protected void putAll(Properties properties) throws CoreException {
- Set<Entry<Object, Object>> entrySet = properties.entrySet();
- Iterator<Entry<Object, Object>> iter = entrySet.iterator();
- ResourceBundleFamily family = getFamily();
- while (iter.hasNext()) {
- Entry<Object, Object> next = iter.next();
- Object key = next.getKey();
- Object value = next.getValue();
- if (key instanceof String && value instanceof String) {
- String stringKey = (String) key;
- entries.put(stringKey, (String) value);
- family.addKey(stringKey);
- }
- }
- }
+ public boolean isReadOnly() {
+ if (resource instanceof IJarEntryResource)
+ return true;
+ if (resource instanceof IFile) {
+ IFile file = (IFile) resource;
+ return file.isReadOnly() || file.isLinked();
+ }
+ return false;
+ }
- public void put(String key, String value) throws CoreException {
- load();
- ResourceBundleFamily family = getFamily();
- entries.put(key, value);
- family.addKey(key);
- }
+ protected void putAll(Properties properties) throws CoreException {
+ Set<Entry<Object, Object>> entrySet = properties.entrySet();
+ Iterator<Entry<Object, Object>> iter = entrySet.iterator();
+ ResourceBundleFamily family = getFamily();
+ while (iter.hasNext()) {
+ Entry<Object, Object> next = iter.next();
+ Object key = next.getKey();
+ Object value = next.getValue();
+ if (key instanceof String && value instanceof String) {
+ String stringKey = (String) key;
+ entries.put(stringKey, (String) value);
+ family.addKey(stringKey);
+ }
+ }
+ }
- public String[] getKeys() throws CoreException {
- load();
- Set<String> keySet = entries.keySet();
- return keySet.toArray(new String[keySet.size()]);
- }
+ public void put(String key, String value) throws CoreException {
+ load();
+ ResourceBundleFamily family = getFamily();
+ entries.put(key, value);
+ family.addKey(key);
+ }
+
+ public String[] getKeys() throws CoreException {
+ load();
+ Set<String> keySet = entries.keySet();
+ return keySet.toArray(new String[keySet.size()]);
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleElement.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleElement.java
index 4025bda..e9276de 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleElement.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleElement.java
@@ -12,14 +12,14 @@
public abstract class ResourceBundleElement {
- private final ResourceBundleElement parent;
+ private final ResourceBundleElement parent;
- public ResourceBundleElement(ResourceBundleElement parent) {
- this.parent = parent;
- }
-
- public ResourceBundleElement getParent() {
- return parent;
- }
+ public ResourceBundleElement(ResourceBundleElement parent) {
+ this.parent = parent;
+ }
+
+ public ResourceBundleElement getParent() {
+ return parent;
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleFamily.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleFamily.java
index 10dbe7f..e563441 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleFamily.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleFamily.java
@@ -20,113 +20,116 @@
/**
* A <code>ResourceBundleFamily</code> represents a group of resource bundles
- * that belong together. Member resource bundles may reside in the same project as the
- * default resource bundle, or in case of a plugin project, in a separate fragment
- * project.
+ * that belong together. Member resource bundles may reside in the same project
+ * as the default resource bundle, or in case of a plugin project, in a separate
+ * fragment project.
*/
public class ResourceBundleFamily extends ResourceBundleElement {
- /**
- * The project name of the default bundle.
- */
- private String projectName;
- /**
- * The plugin id of the default bundle, or <code>null</code> if not a plugin or fragment project.
- */
- private String pluginId;
- /**
- * The package name or path.
- */
- private String packageName;
- /**
- * The base name that all family members have in common.
- */
- private String baseName;
- /**
- * The members that belong to this resource bundle family (excluding the default bundle).
- */
- private ArrayList<ResourceBundle> members = new ArrayList<ResourceBundle>();
- /**
- * A collection of known keys.
- */
- private HashMap<String, ResourceBundleKey> keys = new HashMap<String, ResourceBundleKey>();
+ /**
+ * The project name of the default bundle.
+ */
+ private String projectName;
+ /**
+ * The plugin id of the default bundle, or <code>null</code> if not a plugin
+ * or fragment project.
+ */
+ private String pluginId;
+ /**
+ * The package name or path.
+ */
+ private String packageName;
+ /**
+ * The base name that all family members have in common.
+ */
+ private String baseName;
+ /**
+ * The members that belong to this resource bundle family (excluding the
+ * default bundle).
+ */
+ private ArrayList<ResourceBundle> members = new ArrayList<ResourceBundle>();
+ /**
+ * A collection of known keys.
+ */
+ private HashMap<String, ResourceBundleKey> keys = new HashMap<String, ResourceBundleKey>();
- public ResourceBundleFamily(ResourceBundleModel parent, String projectName, String pluginId,
- String packageName, String baseName) {
- super(parent);
- this.projectName = projectName;
- this.pluginId = pluginId;
- this.packageName = packageName;
- this.baseName = baseName;
- }
+ public ResourceBundleFamily(ResourceBundleModel parent, String projectName,
+ String pluginId, String packageName, String baseName) {
+ super(parent);
+ this.projectName = projectName;
+ this.pluginId = pluginId;
+ this.packageName = packageName;
+ this.baseName = baseName;
+ }
- public String getProjectName() {
- return projectName;
- }
+ public String getProjectName() {
+ return projectName;
+ }
- public String getPluginId() {
- return pluginId;
- }
+ public String getPluginId() {
+ return pluginId;
+ }
- public String getPackageName() {
- return packageName;
- }
+ public String getPackageName() {
+ return packageName;
+ }
- public String getBaseName() {
- return baseName;
- }
+ public String getBaseName() {
+ return baseName;
+ }
- public ResourceBundle[] getBundles() {
- return members.toArray(new ResourceBundle[members.size()]);
- }
+ public ResourceBundle[] getBundles() {
+ return members.toArray(new ResourceBundle[members.size()]);
+ }
- public ResourceBundle getBundle(Locale locale) {
- for (ResourceBundle bundle : members) {
- if (bundle.getLocale().equals(locale)) {
- return bundle;
- }
- }
- return null;
- }
+ public ResourceBundle getBundle(Locale locale) {
+ for (ResourceBundle bundle : members) {
+ if (bundle.getLocale().equals(locale)) {
+ return bundle;
+ }
+ }
+ return null;
+ }
- /*
- * @see java.lang.Object#hashCode()
- */
- @Override
- public int hashCode() {
- if (pluginId != null) {
- return baseName.hashCode() ^ pluginId.hashCode();
- } else {
- return baseName.hashCode() ^ projectName.hashCode();
- }
- }
+ /*
+ * @see java.lang.Object#hashCode()
+ */
+ @Override
+ public int hashCode() {
+ if (pluginId != null) {
+ return baseName.hashCode() ^ pluginId.hashCode();
+ } else {
+ return baseName.hashCode() ^ projectName.hashCode();
+ }
+ }
- protected void addBundle(ResourceBundle bundle) throws CoreException {
- Assert.isTrue(bundle.getParent() == this);
- members.add(bundle);
- }
+ protected void addBundle(ResourceBundle bundle) throws CoreException {
+ Assert.isTrue(bundle.getParent() == this);
+ members.add(bundle);
+ }
- protected void addKey(String key) {
- if (keys.get(key) == null) {
- keys.put(key, new ResourceBundleKey(this, key));
- }
- }
+ protected void addKey(String key) {
+ if (keys.get(key) == null) {
+ keys.put(key, new ResourceBundleKey(this, key));
+ }
+ }
- public ResourceBundleKey[] getKeys() {
- Collection<ResourceBundleKey> values = keys.values();
- return values.toArray(new ResourceBundleKey[values.size()]);
- }
+ public ResourceBundleKey[] getKeys() {
+ Collection<ResourceBundleKey> values = keys.values();
+ return values.toArray(new ResourceBundleKey[values.size()]);
+ }
- public int getKeyCount() {
- return keys.size();
- }
+ public int getKeyCount() {
+ return keys.size();
+ }
- /*
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- return "projectName=" + projectName + ", packageName=" + packageName + ", baseName=" + baseName;
- }
+ /*
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ return "projectName=" + projectName + ", packageName=" + packageName
+ + ", baseName=" + baseName;
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKey.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKey.java
index 04cff98..3856669 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKey.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKey.java
@@ -15,50 +15,50 @@
import org.eclipse.core.runtime.CoreException;
/**
- * A <code>ResourceBundleKey</code> represents a key used in one or more bundles of
- * a {@link ResourceBundleFamily}.
+ * A <code>ResourceBundleKey</code> represents a key used in one or more bundles
+ * of a {@link ResourceBundleFamily}.
*/
public class ResourceBundleKey extends ResourceBundleElement {
- private String key;
+ private String key;
- public ResourceBundleKey(ResourceBundleFamily parent, String key) {
- super(parent);
- this.key = key;
- }
-
- /*
- * @see org.eclipse.nls.ui.model.ResourceBundleElement#getParent()
- */
- @Override
- public ResourceBundleFamily getParent() {
- return (ResourceBundleFamily) super.getParent();
- }
+ public ResourceBundleKey(ResourceBundleFamily parent, String key) {
+ super(parent);
+ this.key = key;
+ }
- public ResourceBundleFamily getFamily() {
- return getParent();
- }
+ /*
+ * @see org.eclipse.nls.ui.model.ResourceBundleElement#getParent()
+ */
+ @Override
+ public ResourceBundleFamily getParent() {
+ return (ResourceBundleFamily) super.getParent();
+ }
- public String getName() {
- return key;
- }
+ public ResourceBundleFamily getFamily() {
+ return getParent();
+ }
- public String getValue(Locale locale) throws CoreException {
- ResourceBundle bundle = getFamily().getBundle(locale);
- if (bundle == null)
- return null;
- return bundle.getString(key);
- }
+ public String getName() {
+ return key;
+ }
- public boolean hasValue(Locale locale) throws CoreException {
- return getValue(locale) != null;
- }
+ public String getValue(Locale locale) throws CoreException {
+ ResourceBundle bundle = getFamily().getBundle(locale);
+ if (bundle == null)
+ return null;
+ return bundle.getString(key);
+ }
- /*
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return "ResourceBundleKey {" + key + "}";
- }
+ public boolean hasValue(Locale locale) throws CoreException {
+ return getValue(locale) != null;
+ }
+
+ /*
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ return "ResourceBundleKey {" + key + "}";
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKeyList.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKeyList.java
index 8683638..c89a7b1 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKeyList.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKeyList.java
@@ -12,18 +12,18 @@
public class ResourceBundleKeyList {
- private final ResourceBundleKey[] keys;
+ private final ResourceBundleKey[] keys;
- public ResourceBundleKeyList(ResourceBundleKey[] keys) {
- this.keys = keys;
- }
+ public ResourceBundleKeyList(ResourceBundleKey[] keys) {
+ this.keys = keys;
+ }
- public ResourceBundleKey getKey(int index) {
- return keys[index];
- }
+ public ResourceBundleKey getKey(int index) {
+ return keys[index];
+ }
- public int getSize() {
- return keys.length;
- }
+ public int getSize() {
+ return keys.length;
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleModel.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleModel.java
index e2f8107..d3ed467 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleModel.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleModel.java
@@ -54,12 +54,12 @@
private HashSet<Locale> loadedLocales = new HashSet<Locale>();
public ResourceBundleModel(IProgressMonitor monitor) {
- super(null);
- try {
- populateFromWorkspace(monitor);
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- }
+ super(null);
+ try {
+ populateFromWorkspace(monitor);
+ } catch (CoreException e) {
+ MessagesEditorPlugin.log(e);
+ }
}
/**
@@ -68,32 +68,32 @@
* @return all resource bundle families contained in this model
*/
public ResourceBundleFamily[] getFamilies() {
- return bundleFamilies.toArray(new ResourceBundleFamily[bundleFamilies
- .size()]);
+ return bundleFamilies.toArray(new ResourceBundleFamily[bundleFamilies
+ .size()]);
}
public ResourceBundleFamily[] getFamiliesForPluginId(String pluginId) {
- ArrayList<ResourceBundleFamily> found = new ArrayList<ResourceBundleFamily>();
- for (ResourceBundleFamily family : bundleFamilies) {
- if (family.getPluginId().equals(pluginId)) {
- found.add(family);
- }
- }
- return found.toArray(new ResourceBundleFamily[found.size()]);
+ ArrayList<ResourceBundleFamily> found = new ArrayList<ResourceBundleFamily>();
+ for (ResourceBundleFamily family : bundleFamilies) {
+ if (family.getPluginId().equals(pluginId)) {
+ found.add(family);
+ }
+ }
+ return found.toArray(new ResourceBundleFamily[found.size()]);
}
public ResourceBundleFamily[] getFamiliesForProjectName(String projectName) {
- ArrayList<ResourceBundleFamily> found = new ArrayList<ResourceBundleFamily>();
- for (ResourceBundleFamily family : bundleFamilies) {
- if (family.getProjectName().equals(projectName)) {
- found.add(family);
- }
- }
- return found.toArray(new ResourceBundleFamily[found.size()]);
+ ArrayList<ResourceBundleFamily> found = new ArrayList<ResourceBundleFamily>();
+ for (ResourceBundleFamily family : bundleFamilies) {
+ if (family.getProjectName().equals(projectName)) {
+ found.add(family);
+ }
+ }
+ return found.toArray(new ResourceBundleFamily[found.size()]);
}
public ResourceBundleFamily[] getFamiliesForProject(IProject project) {
- return getFamiliesForProjectName(project.getName());
+ return getFamiliesForProjectName(project.getName());
}
/**
@@ -107,27 +107,27 @@
* @throws CoreException
*/
public ResourceBundleKey[] getAllKeys() throws CoreException {
- Locale root = new Locale("", "", "");
+ Locale root = new Locale("", "", "");
- // Ensure default bundle is loaded and count keys
- int size = 0;
- for (ResourceBundleFamily family : bundleFamilies) {
- ResourceBundle bundle = family.getBundle(root);
- if (bundle != null)
- bundle.load();
- size += family.getKeyCount();
- }
+ // Ensure default bundle is loaded and count keys
+ int size = 0;
+ for (ResourceBundleFamily family : bundleFamilies) {
+ ResourceBundle bundle = family.getBundle(root);
+ if (bundle != null)
+ bundle.load();
+ size += family.getKeyCount();
+ }
- ArrayList<ResourceBundleKey> allKeys = new ArrayList<ResourceBundleKey>(
- size);
- for (ResourceBundleFamily family : bundleFamilies) {
- ResourceBundleKey[] keys = family.getKeys();
- for (ResourceBundleKey key : keys) {
- allKeys.add(key);
- }
- }
+ ArrayList<ResourceBundleKey> allKeys = new ArrayList<ResourceBundleKey>(
+ size);
+ for (ResourceBundleFamily family : bundleFamilies) {
+ ResourceBundleKey[] keys = family.getKeys();
+ for (ResourceBundleKey key : keys) {
+ allKeys.add(key);
+ }
+ }
- return allKeys.toArray(new ResourceBundleKey[allKeys.size()]);
+ return allKeys.toArray(new ResourceBundleKey[allKeys.size()]);
}
/**
@@ -138,13 +138,13 @@
* @throws CoreException
*/
public void loadBundles(Locale locale) throws CoreException {
- ResourceBundleFamily[] families = getFamilies();
- for (ResourceBundleFamily family : families) {
- ResourceBundle bundle = family.getBundle(locale);
- if (bundle != null)
- bundle.load();
- }
- loadedLocales.add(locale);
+ ResourceBundleFamily[] families = getFamilies();
+ for (ResourceBundleFamily family : families) {
+ ResourceBundle bundle = family.getBundle(locale);
+ if (bundle != null)
+ bundle.load();
+ }
+ loadedLocales.add(locale);
}
/**
@@ -155,16 +155,16 @@
* the locale of the bundles to unload
*/
public void unloadBundles(Locale locale) {
- if ("".equals(locale.getLanguage()))
- return; // never unload the default bundles
+ if ("".equals(locale.getLanguage()))
+ return; // never unload the default bundles
- ResourceBundleFamily[] families = getFamilies();
- for (ResourceBundleFamily family : families) {
- ResourceBundle bundle = family.getBundle(locale);
- if (bundle != null)
- bundle.unload();
- }
- loadedLocales.remove(locale);
+ ResourceBundleFamily[] families = getFamilies();
+ for (ResourceBundleFamily family : families) {
+ ResourceBundle bundle = family.getBundle(locale);
+ if (bundle != null)
+ bundle.unload();
+ }
+ loadedLocales.remove(locale);
}
/**
@@ -172,401 +172,401 @@
* @throws CoreException
*/
private void populateFromWorkspace(IProgressMonitor monitor)
- throws CoreException {
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IWorkspaceRoot root = workspace.getRoot();
- IProject[] projects = root.getProjects();
- for (IProject project : projects) {
- try {
- if (!project.isOpen())
- continue;
+ throws CoreException {
+ IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ IWorkspaceRoot root = workspace.getRoot();
+ IProject[] projects = root.getProjects();
+ for (IProject project : projects) {
+ try {
+ if (!project.isOpen())
+ continue;
- IJavaProject javaProject = (IJavaProject) project
- .getNature(JAVA_NATURE);
- String pluginId = null;
+ IJavaProject javaProject = (IJavaProject) project
+ .getNature(JAVA_NATURE);
+ String pluginId = null;
- try {
- Class IFragmentModel = Class
- .forName("org.eclipse.pde.core.plugin.IFragmentModel");
- Class IPluginModelBase = Class
- .forName("org.eclipse.pde.core.plugin.IPluginModelBase");
- Class PluginRegistry = Class
- .forName("org.eclipse.pde.core.plugin.PluginRegistry");
- Class IPluginBase = Class
- .forName("org.eclipse.pde.core.plugin.IPluginBase");
- Class PluginFragmentModel = Class
- .forName("org.eclipse.core.runtime.model.PluginFragmentModel");
+ try {
+ Class IFragmentModel = Class
+ .forName("org.eclipse.pde.core.plugin.IFragmentModel");
+ Class IPluginModelBase = Class
+ .forName("org.eclipse.pde.core.plugin.IPluginModelBase");
+ Class PluginRegistry = Class
+ .forName("org.eclipse.pde.core.plugin.PluginRegistry");
+ Class IPluginBase = Class
+ .forName("org.eclipse.pde.core.plugin.IPluginBase");
+ Class PluginFragmentModel = Class
+ .forName("org.eclipse.core.runtime.model.PluginFragmentModel");
- // Plugin and fragment projects
- Class pluginModel = (Class) PluginRegistry.getMethod(
- "findModel", IProject.class).invoke(null, project);
- if (pluginModel != null) {
- // Get plugin id
- BundleDescription bd = (BundleDescription) IPluginModelBase
- .getMethod("getBundleDescription").invoke(
- pluginModel);
- pluginId = bd.getName();
- // OSGi bundle name
- if (pluginId == null) {
- Object pluginBase = IPluginModelBase.getMethod(
- "getPluginBase").invoke(pluginModel);
- pluginId = (String) IPluginBase.getMethod("getId")
- .invoke(pluginBase); // non-OSGi
- // plug-in id
- }
+ // Plugin and fragment projects
+ Class pluginModel = (Class) PluginRegistry.getMethod(
+ "findModel", IProject.class).invoke(null, project);
+ if (pluginModel != null) {
+ // Get plugin id
+ BundleDescription bd = (BundleDescription) IPluginModelBase
+ .getMethod("getBundleDescription").invoke(
+ pluginModel);
+ pluginId = bd.getName();
+ // OSGi bundle name
+ if (pluginId == null) {
+ Object pluginBase = IPluginModelBase.getMethod(
+ "getPluginBase").invoke(pluginModel);
+ pluginId = (String) IPluginBase.getMethod("getId")
+ .invoke(pluginBase); // non-OSGi
+ // plug-in id
+ }
- boolean isFragment = IFragmentModel
- .isInstance(pluginModel);
- if (isFragment) {
- Object pfm = IFragmentModel
- .getMethod("getFragment");
- pluginId = (String) PluginFragmentModel.getMethod(
- "getPluginId").invoke(pfm);
- }
+ boolean isFragment = IFragmentModel
+ .isInstance(pluginModel);
+ if (isFragment) {
+ Object pfm = IFragmentModel
+ .getMethod("getFragment");
+ pluginId = (String) PluginFragmentModel.getMethod(
+ "getPluginId").invoke(pfm);
+ }
- // Look for additional 'nl' resources
- IFolder nl = project.getFolder("nl"); //$NON-NLS-1$
- if (isFragment && nl.exists()) {
- IResource[] members = nl.members();
- for (IResource member : members) {
- if (member instanceof IFolder) {
- IFolder langFolder = (IFolder) member;
- String language = langFolder.getName();
+ // Look for additional 'nl' resources
+ IFolder nl = project.getFolder("nl"); //$NON-NLS-1$
+ if (isFragment && nl.exists()) {
+ IResource[] members = nl.members();
+ for (IResource member : members) {
+ if (member instanceof IFolder) {
+ IFolder langFolder = (IFolder) member;
+ String language = langFolder.getName();
- // Collect property files
- IFile[] propertyFiles = collectPropertyFiles(langFolder);
- for (IFile file : propertyFiles) {
- // Compute path name
- IPath path = file
- .getProjectRelativePath();
- String country = ""; //$NON-NLS-1$
- String packageName = null;
- int segmentCount = path.segmentCount();
- if (segmentCount > 1) {
- StringBuilder builder = new StringBuilder();
+ // Collect property files
+ IFile[] propertyFiles = collectPropertyFiles(langFolder);
+ for (IFile file : propertyFiles) {
+ // Compute path name
+ IPath path = file
+ .getProjectRelativePath();
+ String country = ""; //$NON-NLS-1$
+ String packageName = null;
+ int segmentCount = path.segmentCount();
+ if (segmentCount > 1) {
+ StringBuilder builder = new StringBuilder();
- // Segment 0: 'nl'
- // Segment 1: language code
- // Segment 2: (country code)
- int begin = 2;
- if (segmentCount > 2
- && isCountry(path
- .segment(2))) {
- begin = 3;
- country = path.segment(2);
- }
+ // Segment 0: 'nl'
+ // Segment 1: language code
+ // Segment 2: (country code)
+ int begin = 2;
+ if (segmentCount > 2
+ && isCountry(path
+ .segment(2))) {
+ begin = 3;
+ country = path.segment(2);
+ }
- for (int i = begin; i < segmentCount - 1; i++) {
- if (i > begin)
- builder.append('.');
- builder.append(path.segment(i));
- }
- packageName = builder.toString();
- }
+ for (int i = begin; i < segmentCount - 1; i++) {
+ if (i > begin)
+ builder.append('.');
+ builder.append(path.segment(i));
+ }
+ packageName = builder.toString();
+ }
- String baseName = getBaseName(file
- .getName());
+ String baseName = getBaseName(file
+ .getName());
- ResourceBundleFamily family = getOrCreateFamily(
- project.getName(), pluginId,
- packageName, baseName);
- addBundle(family,
- getLocale(language, country),
- file);
- }
- }
- }
- }
+ ResourceBundleFamily family = getOrCreateFamily(
+ project.getName(), pluginId,
+ packageName, baseName);
+ addBundle(family,
+ getLocale(language, country),
+ file);
+ }
+ }
+ }
+ }
- // Collect property files
- if (isFragment || javaProject == null) {
- IFile[] propertyFiles = collectPropertyFiles(project);
- for (IFile file : propertyFiles) {
- IPath path = file.getProjectRelativePath();
- int segmentCount = path.segmentCount();
+ // Collect property files
+ if (isFragment || javaProject == null) {
+ IFile[] propertyFiles = collectPropertyFiles(project);
+ for (IFile file : propertyFiles) {
+ IPath path = file.getProjectRelativePath();
+ int segmentCount = path.segmentCount();
- if (segmentCount > 0
- && path.segment(0).equals("nl")) //$NON-NLS-1$
- continue; // 'nl' resource have been
- // processed
- // above
+ if (segmentCount > 0
+ && path.segment(0).equals("nl")) //$NON-NLS-1$
+ continue; // 'nl' resource have been
+ // processed
+ // above
- // Guess package name
- String packageName = null;
- if (segmentCount > 1) {
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < segmentCount - 1; i++) {
- if (i > 0)
- builder.append('.');
- builder.append(path.segment(i));
- }
- packageName = builder.toString();
- }
+ // Guess package name
+ String packageName = null;
+ if (segmentCount > 1) {
+ StringBuilder builder = new StringBuilder();
+ for (int i = 0; i < segmentCount - 1; i++) {
+ if (i > 0)
+ builder.append('.');
+ builder.append(path.segment(i));
+ }
+ packageName = builder.toString();
+ }
- String baseName = getBaseName(file.getName());
- String language = getLanguage(file.getName());
- String country = getCountry(file.getName());
+ String baseName = getBaseName(file.getName());
+ String language = getLanguage(file.getName());
+ String country = getCountry(file.getName());
- ResourceBundleFamily family = getOrCreateFamily(
- project.getName(), pluginId,
- packageName, baseName);
- addBundle(family, getLocale(language, country),
- file);
- }
- }
+ ResourceBundleFamily family = getOrCreateFamily(
+ project.getName(), pluginId,
+ packageName, baseName);
+ addBundle(family, getLocale(language, country),
+ file);
+ }
+ }
- }
- } catch (Throwable e) {
- // MessagesEditorPlugin.log(e);
- }
+ }
+ } catch (Throwable e) {
+ // MessagesEditorPlugin.log(e);
+ }
- // Look for resource bundles in Java packages (output folders,
- // e.g. 'bin', will be ignored)
- if (javaProject != null) {
- IClasspathEntry[] classpathEntries = javaProject
- .getResolvedClasspath(true);
- for (IClasspathEntry entry : classpathEntries) {
- if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
- IPath path = entry.getPath();
- IFolder folder = workspace.getRoot()
- .getFolder(path);
- IFile[] propertyFiles = collectPropertyFiles(folder);
+ // Look for resource bundles in Java packages (output folders,
+ // e.g. 'bin', will be ignored)
+ if (javaProject != null) {
+ IClasspathEntry[] classpathEntries = javaProject
+ .getResolvedClasspath(true);
+ for (IClasspathEntry entry : classpathEntries) {
+ if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
+ IPath path = entry.getPath();
+ IFolder folder = workspace.getRoot()
+ .getFolder(path);
+ IFile[] propertyFiles = collectPropertyFiles(folder);
- for (IFile file : propertyFiles) {
- String name = file.getName();
- String baseName = getBaseName(name);
- String language = getLanguage(name);
- String country = getCountry(name);
- IPackageFragment pf = javaProject
- .findPackageFragment(file.getParent()
- .getFullPath());
- String packageName = pf.getElementName();
+ for (IFile file : propertyFiles) {
+ String name = file.getName();
+ String baseName = getBaseName(name);
+ String language = getLanguage(name);
+ String country = getCountry(name);
+ IPackageFragment pf = javaProject
+ .findPackageFragment(file.getParent()
+ .getFullPath());
+ String packageName = pf.getElementName();
- ResourceBundleFamily family = getOrCreateFamily(
- project.getName(), pluginId,
- packageName, baseName);
+ ResourceBundleFamily family = getOrCreateFamily(
+ project.getName(), pluginId,
+ packageName, baseName);
- addBundle(family, getLocale(language, country),
- file);
- }
- } else if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
- IPackageFragmentRoot[] findPackageFragmentRoots = javaProject
- .findPackageFragmentRoots(entry);
- for (IPackageFragmentRoot packageFragmentRoot : findPackageFragmentRoots) {
- IJavaElement[] children = packageFragmentRoot
- .getChildren();
- for (IJavaElement child : children) {
- IPackageFragment pf = (IPackageFragment) child;
- Object[] nonJavaResources = pf
- .getNonJavaResources();
+ addBundle(family, getLocale(language, country),
+ file);
+ }
+ } else if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
+ IPackageFragmentRoot[] findPackageFragmentRoots = javaProject
+ .findPackageFragmentRoots(entry);
+ for (IPackageFragmentRoot packageFragmentRoot : findPackageFragmentRoots) {
+ IJavaElement[] children = packageFragmentRoot
+ .getChildren();
+ for (IJavaElement child : children) {
+ IPackageFragment pf = (IPackageFragment) child;
+ Object[] nonJavaResources = pf
+ .getNonJavaResources();
- for (Object resource : nonJavaResources) {
- if (resource instanceof IJarEntryResource) {
- IJarEntryResource jarEntryResource = (IJarEntryResource) resource;
- String name = jarEntryResource
- .getName();
- if (name.endsWith(PROPERTIES_SUFFIX)) {
- String baseName = getBaseName(name);
- String language = getLanguage(name);
- String country = getCountry(name);
- String packageName = pf
- .getElementName();
+ for (Object resource : nonJavaResources) {
+ if (resource instanceof IJarEntryResource) {
+ IJarEntryResource jarEntryResource = (IJarEntryResource) resource;
+ String name = jarEntryResource
+ .getName();
+ if (name.endsWith(PROPERTIES_SUFFIX)) {
+ String baseName = getBaseName(name);
+ String language = getLanguage(name);
+ String country = getCountry(name);
+ String packageName = pf
+ .getElementName();
- ResourceBundleFamily family = getOrCreateFamily(
- project.getName(),
- pluginId, packageName,
- baseName);
+ ResourceBundleFamily family = getOrCreateFamily(
+ project.getName(),
+ pluginId, packageName,
+ baseName);
- addBundle(
- family,
- getLocale(language,
- country),
- jarEntryResource);
- }
- }
- }
- }
- }
- }
- }
+ addBundle(
+ family,
+ getLocale(language,
+ country),
+ jarEntryResource);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
- // Collect non-Java resources
- Object[] nonJavaResources = javaProject
- .getNonJavaResources();
- ArrayList<IFile> files = new ArrayList<IFile>();
- for (Object resource : nonJavaResources) {
- if (resource instanceof IContainer) {
- IContainer container = (IContainer) resource;
- collectPropertyFiles(container, files);
- } else if (resource instanceof IFile) {
- IFile file = (IFile) resource;
- String name = file.getName();
- if (isIgnoredFilename(name))
- continue;
- if (name.endsWith(PROPERTIES_SUFFIX)) {
- files.add(file);
- }
- }
- }
- for (IFile file : files) {
+ // Collect non-Java resources
+ Object[] nonJavaResources = javaProject
+ .getNonJavaResources();
+ ArrayList<IFile> files = new ArrayList<IFile>();
+ for (Object resource : nonJavaResources) {
+ if (resource instanceof IContainer) {
+ IContainer container = (IContainer) resource;
+ collectPropertyFiles(container, files);
+ } else if (resource instanceof IFile) {
+ IFile file = (IFile) resource;
+ String name = file.getName();
+ if (isIgnoredFilename(name))
+ continue;
+ if (name.endsWith(PROPERTIES_SUFFIX)) {
+ files.add(file);
+ }
+ }
+ }
+ for (IFile file : files) {
- // Convert path to package name format
- IPath path = file.getProjectRelativePath();
- String packageName = null;
- int segmentCount = path.segmentCount();
- if (segmentCount > 1) {
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < segmentCount - 1; i++) {
- if (i > 0)
- builder.append('.');
- builder.append(path.segment(i));
- }
- packageName = builder.toString();
- }
+ // Convert path to package name format
+ IPath path = file.getProjectRelativePath();
+ String packageName = null;
+ int segmentCount = path.segmentCount();
+ if (segmentCount > 1) {
+ StringBuilder builder = new StringBuilder();
+ for (int i = 0; i < segmentCount - 1; i++) {
+ if (i > 0)
+ builder.append('.');
+ builder.append(path.segment(i));
+ }
+ packageName = builder.toString();
+ }
- String baseName = getBaseName(file.getName());
- String language = getLanguage(file.getName());
- String country = getCountry(file.getName());
+ String baseName = getBaseName(file.getName());
+ String language = getLanguage(file.getName());
+ String country = getCountry(file.getName());
- ResourceBundleFamily family = getOrCreateFamily(
- project.getName(), pluginId, packageName,
- baseName);
- addBundle(family, getLocale(language, country), file);
- }
+ ResourceBundleFamily family = getOrCreateFamily(
+ project.getName(), pluginId, packageName,
+ baseName);
+ addBundle(family, getLocale(language, country), file);
+ }
- }
- } catch (Exception e) {
- MessagesEditorPlugin.log(e);
- }
- }
+ }
+ } catch (Exception e) {
+ MessagesEditorPlugin.log(e);
+ }
+ }
}
private IFile[] collectPropertyFiles(IContainer container)
- throws CoreException {
- ArrayList<IFile> files = new ArrayList<IFile>();
- collectPropertyFiles(container, files);
- return files.toArray(new IFile[files.size()]);
+ throws CoreException {
+ ArrayList<IFile> files = new ArrayList<IFile>();
+ collectPropertyFiles(container, files);
+ return files.toArray(new IFile[files.size()]);
}
private void collectPropertyFiles(IContainer container,
- ArrayList<IFile> files) throws CoreException {
- IResource[] members = container.members();
- for (IResource resource : members) {
- if (!resource.exists())
- continue;
- if (resource instanceof IContainer) {
- IContainer childContainer = (IContainer) resource;
- collectPropertyFiles(childContainer, files);
- } else if (resource instanceof IFile) {
- IFile file = (IFile) resource;
- String name = file.getName();
- if (file.getProjectRelativePath().segmentCount() == 0
- && isIgnoredFilename(name))
- continue;
- if (name.endsWith(PROPERTIES_SUFFIX)) {
- files.add(file);
- }
- }
- }
+ ArrayList<IFile> files) throws CoreException {
+ IResource[] members = container.members();
+ for (IResource resource : members) {
+ if (!resource.exists())
+ continue;
+ if (resource instanceof IContainer) {
+ IContainer childContainer = (IContainer) resource;
+ collectPropertyFiles(childContainer, files);
+ } else if (resource instanceof IFile) {
+ IFile file = (IFile) resource;
+ String name = file.getName();
+ if (file.getProjectRelativePath().segmentCount() == 0
+ && isIgnoredFilename(name))
+ continue;
+ if (name.endsWith(PROPERTIES_SUFFIX)) {
+ files.add(file);
+ }
+ }
+ }
}
private boolean isCountry(String name) {
- if (name == null || name.length() != 2)
- return false;
- char c1 = name.charAt(0);
- char c2 = name.charAt(1);
- return 'A' <= c1 && c1 <= 'Z' && 'A' <= c2 && c2 <= 'Z';
+ if (name == null || name.length() != 2)
+ return false;
+ char c1 = name.charAt(0);
+ char c2 = name.charAt(1);
+ return 'A' <= c1 && c1 <= 'Z' && 'A' <= c2 && c2 <= 'Z';
}
private Locale getLocale(String language, String country) {
- if (language == null)
- language = ""; //$NON-NLS-1$
- if (country == null)
- country = ""; //$NON-NLS-1$
- return new Locale(language, country);
+ if (language == null)
+ language = ""; //$NON-NLS-1$
+ if (country == null)
+ country = ""; //$NON-NLS-1$
+ return new Locale(language, country);
}
private void addBundle(ResourceBundleFamily family, Locale locale,
- Object resource) throws CoreException {
- ResourceBundle bundle = new ResourceBundle(family, resource, locale);
- if ("".equals(locale.getLanguage()))
- bundle.load();
- family.addBundle(bundle);
+ Object resource) throws CoreException {
+ ResourceBundle bundle = new ResourceBundle(family, resource, locale);
+ if ("".equals(locale.getLanguage()))
+ bundle.load();
+ family.addBundle(bundle);
}
private String getBaseName(String filename) {
- if (!filename.endsWith(PROPERTIES_SUFFIX))
- throw new IllegalArgumentException();
- String name = filename.substring(0, filename.length() - 11);
- int len = name.length();
- if (len > 3 && name.charAt(len - 3) == '_') {
- if (len > 6 && name.charAt(len - 6) == '_') {
- return name.substring(0, len - 6);
- } else {
- return name.substring(0, len - 3);
- }
- }
- return name;
+ if (!filename.endsWith(PROPERTIES_SUFFIX))
+ throw new IllegalArgumentException();
+ String name = filename.substring(0, filename.length() - 11);
+ int len = name.length();
+ if (len > 3 && name.charAt(len - 3) == '_') {
+ if (len > 6 && name.charAt(len - 6) == '_') {
+ return name.substring(0, len - 6);
+ } else {
+ return name.substring(0, len - 3);
+ }
+ }
+ return name;
}
private String getLanguage(String filename) {
- if (!filename.endsWith(PROPERTIES_SUFFIX))
- throw new IllegalArgumentException();
- String name = filename.substring(0, filename.length() - 11);
- int len = name.length();
- if (len > 3 && name.charAt(len - 3) == '_') {
- if (len > 6 && name.charAt(len - 6) == '_') {
- return name.substring(len - 5, len - 3);
- } else {
- return name.substring(len - 2);
- }
- }
- return ""; //$NON-NLS-1$
+ if (!filename.endsWith(PROPERTIES_SUFFIX))
+ throw new IllegalArgumentException();
+ String name = filename.substring(0, filename.length() - 11);
+ int len = name.length();
+ if (len > 3 && name.charAt(len - 3) == '_') {
+ if (len > 6 && name.charAt(len - 6) == '_') {
+ return name.substring(len - 5, len - 3);
+ } else {
+ return name.substring(len - 2);
+ }
+ }
+ return ""; //$NON-NLS-1$
}
private String getCountry(String filename) {
- if (!filename.endsWith(PROPERTIES_SUFFIX))
- throw new IllegalArgumentException();
- String name = filename.substring(0, filename.length() - 11);
- int len = name.length();
- if (len > 3 && name.charAt(len - 3) == '_') {
- if (len > 6 && name.charAt(len - 6) == '_') {
- return name.substring(len - 2);
- } else {
- return ""; //$NON-NLS-1$
- }
- }
- return ""; //$NON-NLS-1$
+ if (!filename.endsWith(PROPERTIES_SUFFIX))
+ throw new IllegalArgumentException();
+ String name = filename.substring(0, filename.length() - 11);
+ int len = name.length();
+ if (len > 3 && name.charAt(len - 3) == '_') {
+ if (len > 6 && name.charAt(len - 6) == '_') {
+ return name.substring(len - 2);
+ } else {
+ return ""; //$NON-NLS-1$
+ }
+ }
+ return ""; //$NON-NLS-1$
}
private ResourceBundleFamily getOrCreateFamily(String projectName,
- String pluginId, String packageName, String baseName) {
+ String pluginId, String packageName, String baseName) {
- // Ignore project name
- if (pluginId != null)
- projectName = null;
+ // Ignore project name
+ if (pluginId != null)
+ projectName = null;
- for (ResourceBundleFamily family : bundleFamilies) {
- if (areEqual(family.getProjectName(), projectName)
- && areEqual(family.getPluginId(), pluginId)
- && areEqual(family.getPackageName(), packageName)
- && areEqual(family.getBaseName(), baseName)) {
- return family;
- }
- }
- ResourceBundleFamily family = new ResourceBundleFamily(this,
- projectName, pluginId, packageName, baseName);
- bundleFamilies.add(family);
- return family;
+ for (ResourceBundleFamily family : bundleFamilies) {
+ if (areEqual(family.getProjectName(), projectName)
+ && areEqual(family.getPluginId(), pluginId)
+ && areEqual(family.getPackageName(), packageName)
+ && areEqual(family.getBaseName(), baseName)) {
+ return family;
+ }
+ }
+ ResourceBundleFamily family = new ResourceBundleFamily(this,
+ projectName, pluginId, packageName, baseName);
+ bundleFamilies.add(family);
+ return family;
}
private boolean isIgnoredFilename(String filename) {
- return filename.equals("build.properties") || filename.equals("logging.properties"); //$NON-NLS-1$ //$NON-NLS-2$
+ return filename.equals("build.properties") || filename.equals("logging.properties"); //$NON-NLS-1$ //$NON-NLS-2$
}
private boolean areEqual(String str1, String str2) {
- return str1 == null && str2 == null || str1 != null
- && str1.equals(str2);
+ return str1 == null && str2 == null || str1 != null
+ && str1.equals(str2);
}
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/CharArraySource.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/CharArraySource.java
index e111b69..9bb8bd8 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/CharArraySource.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/CharArraySource.java
@@ -18,245 +18,244 @@
*/
public class CharArraySource implements IScannerSource {
- private char[] cbuf;
+ private char[] cbuf;
- /** The end position of this source. */
- private int end;
+ /** The end position of this source. */
+ private int end;
- private int[] lineEnds = new int[2048];
+ private int[] lineEnds = new int[2048];
- /**
- * The current position at which the next character will be read.
- * The value <code>Integer.MAX_VALUE</code> indicates, that the end
- * of the source has been reached (the EOF character has been returned).
- */
- int currentPosition = 0;
+ /**
+ * The current position at which the next character will be read. The value
+ * <code>Integer.MAX_VALUE</code> indicates, that the end of the source has
+ * been reached (the EOF character has been returned).
+ */
+ int currentPosition = 0;
- /** The number of the current line. (Line numbers are one-based.) */
- int currentLineNumber = 1;
+ /** The number of the current line. (Line numbers are one-based.) */
+ int currentLineNumber = 1;
- protected CharArraySource() {
- }
+ protected CharArraySource() {
+ }
- /**
- * Constructs a scanner source from a char array.
- */
- public CharArraySource(char[] cbuf) {
- this.cbuf = cbuf;
- this.end = cbuf.length;
- }
+ /**
+ * Constructs a scanner source from a char array.
+ */
+ public CharArraySource(char[] cbuf) {
+ this.cbuf = cbuf;
+ this.end = cbuf.length;
+ }
- /**
- * Resets this source on the given array.
- *
- * @param cbuf the array to read from
- * @param begin where to begin reading
- * @param end where to end reading
- */
- protected void reset(char[] cbuf, int begin, int end) {
- if (cbuf == null) {
- this.cbuf = null;
- this.end = -1;
- currentPosition = -1;
- currentLineNumber = -1;
- lineEnds = null;
- } else {
- this.cbuf = cbuf;
- this.end = end;
- currentPosition = begin;
- currentLineNumber = 1;
- lineEnds = new int[2];
- }
- }
+ /**
+ * Resets this source on the given array.
+ *
+ * @param cbuf
+ * the array to read from
+ * @param begin
+ * where to begin reading
+ * @param end
+ * where to end reading
+ */
+ protected void reset(char[] cbuf, int begin, int end) {
+ if (cbuf == null) {
+ this.cbuf = null;
+ this.end = -1;
+ currentPosition = -1;
+ currentLineNumber = -1;
+ lineEnds = null;
+ } else {
+ this.cbuf = cbuf;
+ this.end = end;
+ currentPosition = begin;
+ currentLineNumber = 1;
+ lineEnds = new int[2];
+ }
+ }
- /*
- * @see scanner.IScannerSource#charAt(int)
- */
- public int charAt(int index) {
- if (index < end) {
- return cbuf[index];
- } else {
- return -1;
- }
- }
+ /*
+ * @see scanner.IScannerSource#charAt(int)
+ */
+ public int charAt(int index) {
+ if (index < end) {
+ return cbuf[index];
+ } else {
+ return -1;
+ }
+ }
- /*
- * @see scanner.IScannerSource#currentChar()
- */
- public int lookahead() {
- if (currentPosition < end) {
- return cbuf[currentPosition];
- } else {
- return -1;
- }
- }
+ /*
+ * @see scanner.IScannerSource#currentChar()
+ */
+ public int lookahead() {
+ if (currentPosition < end) {
+ return cbuf[currentPosition];
+ } else {
+ return -1;
+ }
+ }
- /*
- * @see scanner.IScannerSource#lookahead(int)
- */
- public int lookahead(int n) {
- int pos = currentPosition + n - 1;
- if (pos < end) {
- return cbuf[pos];
- } else {
- return -1;
- }
- }
+ /*
+ * @see scanner.IScannerSource#lookahead(int)
+ */
+ public int lookahead(int n) {
+ int pos = currentPosition + n - 1;
+ if (pos < end) {
+ return cbuf[pos];
+ } else {
+ return -1;
+ }
+ }
- /*
- * @see core.IScannerSource#readChar()
- */
- public int readChar() {
- if (currentPosition < end) {
- return cbuf[currentPosition++];
- } else {
- currentPosition++;
- return -1;
- }
- }
+ /*
+ * @see core.IScannerSource#readChar()
+ */
+ public int readChar() {
+ if (currentPosition < end) {
+ return cbuf[currentPosition++];
+ } else {
+ currentPosition++;
+ return -1;
+ }
+ }
- /*
- * @see core.IScannerSource#readChar(int)
- */
- public int readChar(int expected) {
- int c = readChar();
- if (c == expected) {
- return c;
- } else {
- String message = "Expected char '"
- + (char) expected
- + "' (0x"
- + hexDigit((expected >> 4) & 0xf)
- + hexDigit(expected & 0xf)
- + ") but got '" + (char) c + "' (0x" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- + hexDigit((c >> 4) & 0xf)
- + hexDigit(c & 0xf)
- + ")"; //$NON-NLS-1$
- throw new LexicalErrorException(this, message);
- }
- }
+ /*
+ * @see core.IScannerSource#readChar(int)
+ */
+ public int readChar(int expected) {
+ int c = readChar();
+ if (c == expected) {
+ return c;
+ } else {
+ String message = "Expected char '" + (char) expected + "' (0x"
+ + hexDigit((expected >> 4) & 0xf)
+ + hexDigit(expected & 0xf)
+ + ") but got '" + (char) c + "' (0x" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ + hexDigit((c >> 4) & 0xf) + hexDigit(c & 0xf) + ")"; //$NON-NLS-1$
+ throw new LexicalErrorException(this, message);
+ }
+ }
- /*
- * @see scanner.IScannerSource#unreadChar()
- */
- public void unreadChar() {
- currentPosition--;
- }
+ /*
+ * @see scanner.IScannerSource#unreadChar()
+ */
+ public void unreadChar() {
+ currentPosition--;
+ }
- /*
- * @see core.IScannerSource#hasMoreChars()
- */
- public boolean hasMoreChars() {
- return currentPosition < end;
- }
+ /*
+ * @see core.IScannerSource#hasMoreChars()
+ */
+ public boolean hasMoreChars() {
+ return currentPosition < end;
+ }
- /*
- * @see scanner.IScannerSource#getPosition()
- */
- public int getPosition() {
- if (currentPosition < end)
- return currentPosition;
- else
- return end;
- }
+ /*
+ * @see scanner.IScannerSource#getPosition()
+ */
+ public int getPosition() {
+ if (currentPosition < end)
+ return currentPosition;
+ else
+ return end;
+ }
- /*
- * @see core.IScannerSource#isAtLineBegin()
- */
- public boolean isAtLineBegin() {
- return currentPosition == lineEnds[currentLineNumber - 1];
- }
+ /*
+ * @see core.IScannerSource#isAtLineBegin()
+ */
+ public boolean isAtLineBegin() {
+ return currentPosition == lineEnds[currentLineNumber - 1];
+ }
- /*
- * @see scanner.IScannerSource#getCurrentLineNumber()
- */
- public int getCurrentLineNumber() {
- return currentLineNumber;
- }
+ /*
+ * @see scanner.IScannerSource#getCurrentLineNumber()
+ */
+ public int getCurrentLineNumber() {
+ return currentLineNumber;
+ }
- /*
- * @see scanner.IScannerSource#getCurrentColumnNumber()
- */
- public int getCurrentColumnNumber() {
- return currentPosition - lineEnds[currentLineNumber - 1] + 1;
- }
+ /*
+ * @see scanner.IScannerSource#getCurrentColumnNumber()
+ */
+ public int getCurrentColumnNumber() {
+ return currentPosition - lineEnds[currentLineNumber - 1] + 1;
+ }
- /*
- * @see scanner.IScannerSource#getLineEnds()
- */
- public int[] getLineEnds() {
- return lineEnds;
- }
- /*
- * @see scanner.IScannerSource#pushLineSeparator()
- */
- public void pushLineSeparator() {
- if (currentLineNumber >= lineEnds.length) {
- int[] newLineEnds = new int[lineEnds.length * 2];
- System.arraycopy(lineEnds, 0, newLineEnds, 0, lineEnds.length);
- lineEnds = newLineEnds;
- }
- lineEnds[currentLineNumber++] = currentPosition;
- }
+ /*
+ * @see scanner.IScannerSource#getLineEnds()
+ */
+ public int[] getLineEnds() {
+ return lineEnds;
+ }
- /*
- * @see scanner.IScannerSource#length()
- */
- public int length() {
- return cbuf.length;
- }
+ /*
+ * @see scanner.IScannerSource#pushLineSeparator()
+ */
+ public void pushLineSeparator() {
+ if (currentLineNumber >= lineEnds.length) {
+ int[] newLineEnds = new int[lineEnds.length * 2];
+ System.arraycopy(lineEnds, 0, newLineEnds, 0, lineEnds.length);
+ lineEnds = newLineEnds;
+ }
+ lineEnds[currentLineNumber++] = currentPosition;
+ }
- /**
- * Returns a string that contains the characters of the source specified
- * by the range <code>beginIndex</code> and the current position as the
- * end index.
- *
- * @param beginIndex
- * @return the String
- */
- public String toString(int beginIndex) {
- return toString(beginIndex, currentPosition);
- }
+ /*
+ * @see scanner.IScannerSource#length()
+ */
+ public int length() {
+ return cbuf.length;
+ }
- /*
- * @see scanner.IScannerSource#toString(int, int)
- */
- public String toString(int beginIndex, int endIndex) {
- return new String(cbuf, beginIndex, endIndex - beginIndex);
- }
+ /**
+ * Returns a string that contains the characters of the source specified by
+ * the range <code>beginIndex</code> and the current position as the end
+ * index.
+ *
+ * @param beginIndex
+ * @return the String
+ */
+ public String toString(int beginIndex) {
+ return toString(beginIndex, currentPosition);
+ }
- /**
- * Returns the original character array that backs the scanner source.
- * All subsequent changes to the returned array will affect the scanner
- * source.
- *
- * @return the array
- */
- public char[] getArray() {
- return cbuf;
- }
+ /*
+ * @see scanner.IScannerSource#toString(int, int)
+ */
+ public String toString(int beginIndex, int endIndex) {
+ return new String(cbuf, beginIndex, endIndex - beginIndex);
+ }
- /*
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return "Line=" + getCurrentLineNumber() + ", Column=" + getCurrentColumnNumber(); //$NON-NLS-1$ //$NON-NLS-2$
- }
+ /**
+ * Returns the original character array that backs the scanner source. All
+ * subsequent changes to the returned array will affect the scanner source.
+ *
+ * @return the array
+ */
+ public char[] getArray() {
+ return cbuf;
+ }
- private static char hexDigit(int digit) {
- return "0123456789abcdef".charAt(digit); //$NON-NLS-1$
- }
+ /*
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ return "Line=" + getCurrentLineNumber() + ", Column=" + getCurrentColumnNumber(); //$NON-NLS-1$ //$NON-NLS-2$
+ }
- public static CharArraySource createFrom(Reader reader) throws IOException {
- StringBuffer buffer = new StringBuffer();
- int BUF_SIZE = 4096;
- char[] array = new char[BUF_SIZE];
- for (int read = 0; (read = reader.read(array, 0, BUF_SIZE)) > 0;) {
- buffer.append(array, 0, read);
- }
- char[] result = new char[buffer.length()];
- buffer.getChars(0, buffer.length(), result, 0);
- return new CharArraySource(result);
- }
+ private static char hexDigit(int digit) {
+ return "0123456789abcdef".charAt(digit); //$NON-NLS-1$
+ }
+
+ public static CharArraySource createFrom(Reader reader) throws IOException {
+ StringBuffer buffer = new StringBuffer();
+ int BUF_SIZE = 4096;
+ char[] array = new char[BUF_SIZE];
+ for (int read = 0; (read = reader.read(array, 0, BUF_SIZE)) > 0;) {
+ buffer.append(array, 0, read);
+ }
+ char[] result = new char[buffer.length()];
+ buffer.getChars(0, buffer.length(), result, 0);
+ return new CharArraySource(result);
+ }
}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/IScannerSource.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/IScannerSource.java
index 6ae6dce..dd4e391 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/IScannerSource.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/IScannerSource.java
@@ -12,128 +12,138 @@
public interface IScannerSource {
- /**
- * Returns the character at the specified position.
- *
- * @param position the index of the character to be returned
- * @return the character at the specified position (0-based)
- */
- public int charAt(int position);
+ /**
+ * Returns the character at the specified position.
+ *
+ * @param position
+ * the index of the character to be returned
+ * @return the character at the specified position (0-based)
+ */
+ public int charAt(int position);
- /**
- * Returns the character that will be returned by the next call
- * to <code>readChar()</code>. Calling this method is equal to the
- * following calls:
- * <pre>
- * lookahead(1)
- * charAt(getPosition())
- * </pre>
- *
- * @return the character at the current position
- */
- public int lookahead();
+ /**
+ * Returns the character that will be returned by the next call to
+ * <code>readChar()</code>. Calling this method is equal to the following
+ * calls:
+ *
+ * <pre>
+ * lookahead(1)
+ * charAt(getPosition())
+ * </pre>
+ *
+ * @return the character at the current position
+ */
+ public int lookahead();
- /**
- * Returns the character at the given lookahead position. Calling this
- * method is equal to the following call:
- * <pre>
- * charAt(currentPosition + n - 1)
- * </pre>
- *
- * @param n the number of characters to look ahead
- *
- * @return the character
- */
- public int lookahead(int n);
+ /**
+ * Returns the character at the given lookahead position. Calling this
+ * method is equal to the following call:
+ *
+ * <pre>
+ * charAt(currentPosition + n - 1)
+ * </pre>
+ *
+ * @param n
+ * the number of characters to look ahead
+ *
+ * @return the character
+ */
+ public int lookahead(int n);
- /**
- * Reads a single character.
- *
- * @return the character read, or -1 if the end of the source
- * has been reached
- */
- public int readChar();
-
- /**
- * Reads a single character.
- *
- * @param expected the expected character; if the character read does not
- * match this character, a <code>LexcialErrorException</code> will be thrown
- * @return the character read, or -1 if the end of the source
- * has been reached
- */
- public int readChar(int expected);
-
- /**
- * Unreads a single character. The current position will be decreased
- * by 1. If -1 has been read multiple times, it will be unread multiple
- * times.
- */
- public void unreadChar();
+ /**
+ * Reads a single character.
+ *
+ * @return the character read, or -1 if the end of the source has been
+ * reached
+ */
+ public int readChar();
- /**
- * Retruns the current position of the source.
- *
- * @return the position (0-based)
- */
- public int getPosition();
+ /**
+ * Reads a single character.
+ *
+ * @param expected
+ * the expected character; if the character read does not match
+ * this character, a <code>LexcialErrorException</code> will be
+ * thrown
+ * @return the character read, or -1 if the end of the source has been
+ * reached
+ */
+ public int readChar(int expected);
- /**
- * Returns <code>true</code> if the current position is at the beginning of a line.
- *
- * @return <code>true</code> if the current position is at the beginning of a line
- */
- public boolean isAtLineBegin();
+ /**
+ * Unreads a single character. The current position will be decreased by 1.
+ * If -1 has been read multiple times, it will be unread multiple times.
+ */
+ public void unreadChar();
- /**
- * Returns the current line number.
- *
- * @return the current line number (1-based)
- */
- public int getCurrentLineNumber();
-
- /**
- * Returns the current column number.
- *
- * @return the current column number (1-based)
- */
- public int getCurrentColumnNumber();
+ /**
+ * Retruns the current position of the source.
+ *
+ * @return the position (0-based)
+ */
+ public int getPosition();
- /**
- * Records the next line end position. This method has to be called
- * just after the line separator has been read.
- *
- * @see IScannerSource#getLineEnds()
- */
- public void pushLineSeparator();
+ /**
+ * Returns <code>true</code> if the current position is at the beginning of
+ * a line.
+ *
+ * @return <code>true</code> if the current position is at the beginning of
+ * a line
+ */
+ public boolean isAtLineBegin();
- /**
- * Returns an array of the line end positions recorded so far. Each value points
- * to first character following the line end (and is thus an exclusive index
- * to the line end). By definition the value <code>lineEnds[0]</code> is 0.
- * <code>lineEnds[1]</code> contains the line end position of the first line.
- *
- * @return an array containing the line end positions
- *
- * @see IScannerSource#pushLineSeparator()
- */
- public int[] getLineEnds();
+ /**
+ * Returns the current line number.
+ *
+ * @return the current line number (1-based)
+ */
+ public int getCurrentLineNumber();
- /**
- * Returns <code>true</code> if more characters are available.
- *
- * @return <code>true</code> if more characters are available
- */
- public boolean hasMoreChars();
+ /**
+ * Returns the current column number.
+ *
+ * @return the current column number (1-based)
+ */
+ public int getCurrentColumnNumber();
- /**
- * Returns a String that contains the characters in the specified range
- * of the source.
- *
- * @param beginIndex the beginning index, inclusive
- * @param endIndex the ending index, exclusive
- * @return the newly created <code>String</code>
- */
- public String toString(int beginIndex, int endIndex);
+ /**
+ * Records the next line end position. This method has to be called just
+ * after the line separator has been read.
+ *
+ * @see IScannerSource#getLineEnds()
+ */
+ public void pushLineSeparator();
+
+ /**
+ * Returns an array of the line end positions recorded so far. Each value
+ * points to first character following the line end (and is thus an
+ * exclusive index to the line end). By definition the value
+ * <code>lineEnds[0]</code> is 0. <code>lineEnds[1]</code> contains the line
+ * end position of the first line.
+ *
+ * @return an array containing the line end positions
+ *
+ * @see IScannerSource#pushLineSeparator()
+ */
+ public int[] getLineEnds();
+
+ /**
+ * Returns <code>true</code> if more characters are available.
+ *
+ * @return <code>true</code> if more characters are available
+ */
+ public boolean hasMoreChars();
+
+ /**
+ * Returns a String that contains the characters in the specified range of
+ * the source.
+ *
+ * @param beginIndex
+ * the beginning index, inclusive
+ * @param endIndex
+ * the ending index, exclusive
+ * @return the newly created <code>String</code>
+ */
+ public String toString(int beginIndex, int endIndex);
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LexicalErrorException.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LexicalErrorException.java
index 4b5439a..5b7f727 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LexicalErrorException.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LexicalErrorException.java
@@ -15,66 +15,73 @@
*/
public class LexicalErrorException extends RuntimeException {
- private int lineNumber;
- private int columnNumber;
+ private int lineNumber;
+ private int columnNumber;
- /**
- * Creates a <code>LexicalErrorException</code> without a detailed message.
- *
- * @param source the scanner source the error occured on
- */
- public LexicalErrorException(IScannerSource source) {
- this(source.getCurrentLineNumber(), source.getCurrentColumnNumber(), null);
- }
+ /**
+ * Creates a <code>LexicalErrorException</code> without a detailed message.
+ *
+ * @param source
+ * the scanner source the error occured on
+ */
+ public LexicalErrorException(IScannerSource source) {
+ this(source.getCurrentLineNumber(), source.getCurrentColumnNumber(),
+ null);
+ }
- /**
- * @param source the scanner source the error occured on
- * @param message the error message
- */
- public LexicalErrorException(IScannerSource source, String message) {
- this(source.getCurrentLineNumber(), source.getCurrentColumnNumber(), message);
- }
+ /**
+ * @param source
+ * the scanner source the error occured on
+ * @param message
+ * the error message
+ */
+ public LexicalErrorException(IScannerSource source, String message) {
+ this(source.getCurrentLineNumber(), source.getCurrentColumnNumber(),
+ message);
+ }
- /**
- * @param line the number of the line where the error occured
- * @param column the numer of the column where the error occured
- * @param message the error message
- */
- public LexicalErrorException(int line, int column, String message) {
- super("Lexical error (" + line + ", " + column + (message == null ? ")" : "): " + message)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- this.lineNumber = line;
- this.columnNumber = column;
- }
+ /**
+ * @param line
+ * the number of the line where the error occured
+ * @param column
+ * the numer of the column where the error occured
+ * @param message
+ * the error message
+ */
+ public LexicalErrorException(int line, int column, String message) {
+ super(
+ "Lexical error (" + line + ", " + column + (message == null ? ")" : "): " + message)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ this.lineNumber = line;
+ this.columnNumber = column;
+ }
- /**
- * Returns the line number where the error occured.
- *
- * @return the line number where the error occured
- */
- public int getLineNumber() {
- return lineNumber;
- }
+ /**
+ * Returns the line number where the error occured.
+ *
+ * @return the line number where the error occured
+ */
+ public int getLineNumber() {
+ return lineNumber;
+ }
- /**
- * Returns the column number where the error occured.
- *
- * @return the column number where the error occured
- */
- public int getColumnNumber() {
- return columnNumber;
- }
+ /**
+ * Returns the column number where the error occured.
+ *
+ * @return the column number where the error occured
+ */
+ public int getColumnNumber() {
+ return columnNumber;
+ }
- public static LexicalErrorException unexpectedCharacter(IScannerSource source, int c) {
- return new LexicalErrorException(source, "Unexpected character: '" //$NON-NLS-1$
- + (char) c
- + "' (0x" //$NON-NLS-1$
- + hexDigit((c >> 4) & 0xf)
- + hexDigit(c & 0xf)
- + ")"); //$NON-NLS-1$
- }
+ public static LexicalErrorException unexpectedCharacter(
+ IScannerSource source, int c) {
+ return new LexicalErrorException(source, "Unexpected character: '" //$NON-NLS-1$
+ + (char) c + "' (0x" //$NON-NLS-1$
+ + hexDigit((c >> 4) & 0xf) + hexDigit(c & 0xf) + ")"); //$NON-NLS-1$
+ }
- private static char hexDigit(int digit) {
- return "0123456789abcdef".charAt(digit); //$NON-NLS-1$
- }
+ private static char hexDigit(int digit) {
+ return "0123456789abcdef".charAt(digit); //$NON-NLS-1$
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LocaleUtil.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LocaleUtil.java
index d5ecba3..e02b02c 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LocaleUtil.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LocaleUtil.java
@@ -15,42 +15,43 @@
public class LocaleUtil {
- private LocaleUtil() {
- }
+ private LocaleUtil() {
+ }
- public static Locale parseLocale(String name) throws IllegalArgumentException {
- String language = ""; //$NON-NLS-1$
- String country = ""; //$NON-NLS-1$
- String variant = ""; //$NON-NLS-1$
+ public static Locale parseLocale(String name)
+ throws IllegalArgumentException {
+ String language = ""; //$NON-NLS-1$
+ String country = ""; //$NON-NLS-1$
+ String variant = ""; //$NON-NLS-1$
- StringTokenizer tokenizer = new StringTokenizer(name, "_"); //$NON-NLS-1$
- if (tokenizer.hasMoreTokens())
- language = tokenizer.nextToken();
- if (tokenizer.hasMoreTokens())
- country = tokenizer.nextToken();
- if (tokenizer.hasMoreTokens())
- variant = tokenizer.nextToken();
+ StringTokenizer tokenizer = new StringTokenizer(name, "_"); //$NON-NLS-1$
+ if (tokenizer.hasMoreTokens())
+ language = tokenizer.nextToken();
+ if (tokenizer.hasMoreTokens())
+ country = tokenizer.nextToken();
+ if (tokenizer.hasMoreTokens())
+ variant = tokenizer.nextToken();
- if (!language.equals("") && language.length() != 2) //$NON-NLS-1$
- throw new IllegalArgumentException();
- if (!country.equals("") && country.length() != 2) //$NON-NLS-1$
- throw new IllegalArgumentException();
+ if (!language.equals("") && language.length() != 2) //$NON-NLS-1$
+ throw new IllegalArgumentException();
+ if (!country.equals("") && country.length() != 2) //$NON-NLS-1$
+ throw new IllegalArgumentException();
- if (!language.equals("")) { //$NON-NLS-1$
- char l1 = language.charAt(0);
- char l2 = language.charAt(1);
- if (!('a' <= l1 && l1 <= 'z' && 'a' <= l2 && l2 <= 'z'))
- throw new IllegalArgumentException();
- }
+ if (!language.equals("")) { //$NON-NLS-1$
+ char l1 = language.charAt(0);
+ char l2 = language.charAt(1);
+ if (!('a' <= l1 && l1 <= 'z' && 'a' <= l2 && l2 <= 'z'))
+ throw new IllegalArgumentException();
+ }
- if (!country.equals("")) { //$NON-NLS-1$
- char c1 = country.charAt(0);
- char c2 = country.charAt(1);
- if (!('A' <= c1 && c1 <= 'Z' && 'A' <= c2 && c2 <= 'Z'))
- throw new IllegalArgumentException();
- }
+ if (!country.equals("")) { //$NON-NLS-1$
+ char c1 = country.charAt(0);
+ char c2 = country.charAt(1);
+ if (!('A' <= c1 && c1 <= 'Z' && 'A' <= c2 && c2 <= 'Z'))
+ throw new IllegalArgumentException();
+ }
- return new Locale(language, country, variant);
- }
+ return new Locale(language, country, variant);
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/RawBundle.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/RawBundle.java
index 7958772..8e7870e 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/RawBundle.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/RawBundle.java
@@ -24,299 +24,309 @@
*/
public class RawBundle {
- public static abstract class RawLine {
- String rawData;
- public RawLine(String rawData) {
- this.rawData = rawData;
- }
- public String getRawData() {
- return rawData;
- }
- }
- public static class CommentLine extends RawLine {
- public CommentLine(String line) {
- super(line);
- }
- }
- public static class EmptyLine extends RawLine {
- public EmptyLine(String line) {
- super(line);
- }
- }
- public static class EntryLine extends RawLine {
- String key;
- public EntryLine(String key, String lineData) {
- super(lineData);
- this.key = key;
- }
- }
+ public static abstract class RawLine {
+ String rawData;
- /**
- * The logical lines of the resource bundle.
- */
- private ArrayList<RawLine> lines = new ArrayList<RawLine>();
+ public RawLine(String rawData) {
+ this.rawData = rawData;
+ }
- public RawBundle() {
- }
+ public String getRawData() {
+ return rawData;
+ }
+ }
- public EntryLine getEntryLine(String key) {
- for (RawLine line : lines) {
- if (line instanceof EntryLine) {
- EntryLine entryLine = (EntryLine) line;
- if (entryLine.key.equals(key))
- return entryLine;
- }
- }
- return null;
- }
+ public static class CommentLine extends RawLine {
+ public CommentLine(String line) {
+ super(line);
+ }
+ }
- public void put(String key, String value) {
+ public static class EmptyLine extends RawLine {
+ public EmptyLine(String line) {
+ super(line);
+ }
+ }
- // Find insertion position
- int size = lines.size();
- int pos = -1;
- for (int i = 0; i < size; i++) {
- RawLine line = lines.get(i);
- if (line instanceof EntryLine) {
- EntryLine entryLine = (EntryLine) line;
- int compare = key.compareToIgnoreCase(entryLine.key);
- if (compare < 0) {
- if (pos == -1) {
- pos = i; // possible insertion position
- }
- } else if (compare > 0) {
- continue;
- } else if (key.equals(entryLine.key)) {
- entryLine.rawData = key + "=" + escape(value) + "\r\n";
- return;
- } else {
- pos = i; // possible insertion position
- }
- }
- }
- if (pos == -1)
- pos = lines.size();
+ public static class EntryLine extends RawLine {
+ String key;
- // Append new entry
- lines.add(pos, new EntryLine(key, key + "=" + escape(value) + "\r\n"));
- }
+ public EntryLine(String key, String lineData) {
+ super(lineData);
+ this.key = key;
+ }
+ }
- private String escape(String str) {
- StringBuilder builder = new StringBuilder();
- int len = str.length();
- for (int i = 0; i < len; i++) {
- char c = str.charAt(i);
- switch (c) {
- case ' ' :
- if (i == 0) {
- builder.append("\\ ");
- } else {
- builder.append(c);
- }
- break;
- case '\t' :
- builder.append("\\t");
- break;
- case '=' :
- case ':' :
- case '#' :
- case '!' :
- case '\\' :
- builder.append('\\').append(c);
- break;
- default :
- if (31 <= c && c <= 255) {
- builder.append(c);
- } else {
- builder.append("\\u");
- builder.append(hexDigit((c >> 12) & 0x0f));
- builder.append(hexDigit((c >> 8) & 0x0f));
- builder.append(hexDigit((c >> 4) & 0x0f));
- builder.append(hexDigit(c & 0x0f));
- }
- break;
- }
- }
- return builder.toString();
- }
+ /**
+ * The logical lines of the resource bundle.
+ */
+ private ArrayList<RawLine> lines = new ArrayList<RawLine>();
- private static char hexDigit(int digit) {
- return "0123456789ABCDEF".charAt(digit); //$NON-NLS-1$
- }
+ public RawBundle() {
+ }
- public void writeTo(OutputStream out) throws IOException {
- OutputStreamWriter writer = new OutputStreamWriter(out, "ISO-8859-1");
- writeTo(writer);
- }
+ public EntryLine getEntryLine(String key) {
+ for (RawLine line : lines) {
+ if (line instanceof EntryLine) {
+ EntryLine entryLine = (EntryLine) line;
+ if (entryLine.key.equals(key))
+ return entryLine;
+ }
+ }
+ return null;
+ }
- public void writeTo(Writer writer) throws IOException {
- for (RawLine line : lines) {
- writer.write(line.rawData);
- }
- }
+ public void put(String key, String value) {
- public static RawBundle createFrom(InputStream in) throws IOException {
- IScannerSource source = CharArraySource.createFrom(new InputStreamReader(in, "ISO-8859-1"));
- return RawBundle.createFrom(source);
- }
+ // Find insertion position
+ int size = lines.size();
+ int pos = -1;
+ for (int i = 0; i < size; i++) {
+ RawLine line = lines.get(i);
+ if (line instanceof EntryLine) {
+ EntryLine entryLine = (EntryLine) line;
+ int compare = key.compareToIgnoreCase(entryLine.key);
+ if (compare < 0) {
+ if (pos == -1) {
+ pos = i; // possible insertion position
+ }
+ } else if (compare > 0) {
+ continue;
+ } else if (key.equals(entryLine.key)) {
+ entryLine.rawData = key + "=" + escape(value) + "\r\n";
+ return;
+ } else {
+ pos = i; // possible insertion position
+ }
+ }
+ }
+ if (pos == -1)
+ pos = lines.size();
- public static RawBundle createFrom(Reader reader) throws IOException {
- IScannerSource source = CharArraySource.createFrom(reader);
- return RawBundle.createFrom(source);
- }
+ // Append new entry
+ lines.add(pos, new EntryLine(key, key + "=" + escape(value) + "\r\n"));
+ }
- public static RawBundle createFrom(IScannerSource source) throws IOException {
- RawBundle rawBundle = new RawBundle();
- StringBuilder builder = new StringBuilder();
+ private String escape(String str) {
+ StringBuilder builder = new StringBuilder();
+ int len = str.length();
+ for (int i = 0; i < len; i++) {
+ char c = str.charAt(i);
+ switch (c) {
+ case ' ':
+ if (i == 0) {
+ builder.append("\\ ");
+ } else {
+ builder.append(c);
+ }
+ break;
+ case '\t':
+ builder.append("\\t");
+ break;
+ case '=':
+ case ':':
+ case '#':
+ case '!':
+ case '\\':
+ builder.append('\\').append(c);
+ break;
+ default:
+ if (31 <= c && c <= 255) {
+ builder.append(c);
+ } else {
+ builder.append("\\u");
+ builder.append(hexDigit((c >> 12) & 0x0f));
+ builder.append(hexDigit((c >> 8) & 0x0f));
+ builder.append(hexDigit((c >> 4) & 0x0f));
+ builder.append(hexDigit(c & 0x0f));
+ }
+ break;
+ }
+ }
+ return builder.toString();
+ }
- while (source.hasMoreChars()) {
- int begin = source.getPosition();
- skipAllOf(" \t\u000c", source);
+ private static char hexDigit(int digit) {
+ return "0123456789ABCDEF".charAt(digit); //$NON-NLS-1$
+ }
- // Comment line
- if (source.lookahead() == '#' || source.lookahead() == '!') {
- skipToOneOf("\r\n", false, source);
- consumeLineSeparator(source);
- int end = source.getPosition();
- String line = source.toString(begin, end);
- rawBundle.lines.add(new CommentLine(line));
- continue;
- }
+ public void writeTo(OutputStream out) throws IOException {
+ OutputStreamWriter writer = new OutputStreamWriter(out, "ISO-8859-1");
+ writeTo(writer);
+ }
- // Empty line
- if (isAtLineEnd(source)) {
- consumeLineSeparator(source);
- int end = source.getPosition();
- String line = source.toString(begin, end);
- rawBundle.lines.add(new EmptyLine(line));
- continue;
- }
+ public void writeTo(Writer writer) throws IOException {
+ for (RawLine line : lines) {
+ writer.write(line.rawData);
+ }
+ }
- // Entry line
- {
- // Key
- builder.setLength(0);
- loop : while (source.hasMoreChars()) {
- char c = (char) source.readChar();
- switch (c) {
- case ' ' :
- case '\t' :
- case '\u000c' :
- case '=' :
- case '\r' :
- case '\n' :
- break loop;
- case '\\' :
- source.unreadChar();
- builder.append(readEscapedChar(source));
- break;
- default :
- builder.append(c);
- break;
- }
- }
- String key = builder.toString();
+ public static RawBundle createFrom(InputStream in) throws IOException {
+ IScannerSource source = CharArraySource
+ .createFrom(new InputStreamReader(in, "ISO-8859-1"));
+ return RawBundle.createFrom(source);
+ }
- // Value
- int end = 0;
- loop : while (source.hasMoreChars()) {
- char c = (char) source.readChar();
- switch (c) {
- case '\r' :
- case '\n' :
- consumeLineSeparator(source);
- end = source.getPosition();
- break loop;
- case '\\' :
- if (isAtLineEnd(source)) {
- consumeLineSeparator(source);
- } else {
- source.unreadChar();
- readEscapedChar(source);
- }
- break;
- default :
- break;
- }
- }
- if (end == 0)
- end = source.getPosition();
+ public static RawBundle createFrom(Reader reader) throws IOException {
+ IScannerSource source = CharArraySource.createFrom(reader);
+ return RawBundle.createFrom(source);
+ }
- String lineData = source.toString(begin, end);
- EntryLine entryLine = new EntryLine(key, lineData);
- rawBundle.lines.add(entryLine);
- }
- }
+ public static RawBundle createFrom(IScannerSource source)
+ throws IOException {
+ RawBundle rawBundle = new RawBundle();
+ StringBuilder builder = new StringBuilder();
- return rawBundle;
- }
+ while (source.hasMoreChars()) {
+ int begin = source.getPosition();
+ skipAllOf(" \t\u000c", source);
- private static char readEscapedChar(IScannerSource source) {
- source.readChar('\\');
- char c = (char) source.readChar();
- switch (c) {
- case ' ' :
- case '=' :
- case ':' :
- case '#' :
- case '!' :
- case '\\' :
- return c;
- case 't' :
- return '\t';
- case 'n' :
- return '\n';
- case 'u' :
- int d1 = Character.digit(source.readChar(), 16);
- int d2 = Character.digit(source.readChar(), 16);
- int d3 = Character.digit(source.readChar(), 16);
- int d4 = Character.digit(source.readChar(), 16);
- if (d1 == -1 || d2 == -1 || d3 == -1 || d4 == -1)
- throw new LexicalErrorException(source, "Illegal escape sequence");
- return (char) (d1 << 12 | d2 << 8 | d3 << 4 | d4);
- default :
- throw new LexicalErrorException(source, "Unknown escape sequence");
- }
- }
+ // Comment line
+ if (source.lookahead() == '#' || source.lookahead() == '!') {
+ skipToOneOf("\r\n", false, source);
+ consumeLineSeparator(source);
+ int end = source.getPosition();
+ String line = source.toString(begin, end);
+ rawBundle.lines.add(new CommentLine(line));
+ continue;
+ }
- private static boolean isAtLineEnd(IScannerSource source) {
- return source.lookahead() == '\r' || source.lookahead() == '\n';
- }
+ // Empty line
+ if (isAtLineEnd(source)) {
+ consumeLineSeparator(source);
+ int end = source.getPosition();
+ String line = source.toString(begin, end);
+ rawBundle.lines.add(new EmptyLine(line));
+ continue;
+ }
- private static void consumeLineSeparator(IScannerSource source) {
- if (source.lookahead() == '\n') {
- source.readChar();
- source.pushLineSeparator();
- } else if (source.lookahead() == '\r') {
- source.readChar();
- if (source.lookahead() == '\n') {
- source.readChar();
- }
- source.pushLineSeparator();
- }
- }
-
- private static void skipToOneOf(String delimiters, boolean readDelimiter, IScannerSource source) {
- loop : while (source.hasMoreChars()) {
- int c = source.readChar();
- if (delimiters.indexOf(c) != -1) {
- if (!readDelimiter) {
- source.unreadChar();
- }
- break loop;
- }
- if (c == '\r') {
- source.readChar('\n');
- source.pushLineSeparator();
- }
- }
- }
+ // Entry line
+ {
+ // Key
+ builder.setLength(0);
+ loop: while (source.hasMoreChars()) {
+ char c = (char) source.readChar();
+ switch (c) {
+ case ' ':
+ case '\t':
+ case '\u000c':
+ case '=':
+ case '\r':
+ case '\n':
+ break loop;
+ case '\\':
+ source.unreadChar();
+ builder.append(readEscapedChar(source));
+ break;
+ default:
+ builder.append(c);
+ break;
+ }
+ }
+ String key = builder.toString();
- private static void skipAllOf(String string, IScannerSource source) {
- while (source.hasMoreChars() && string.indexOf(source.lookahead()) != -1) {
- source.readChar();
- }
- }
-
+ // Value
+ int end = 0;
+ loop: while (source.hasMoreChars()) {
+ char c = (char) source.readChar();
+ switch (c) {
+ case '\r':
+ case '\n':
+ consumeLineSeparator(source);
+ end = source.getPosition();
+ break loop;
+ case '\\':
+ if (isAtLineEnd(source)) {
+ consumeLineSeparator(source);
+ } else {
+ source.unreadChar();
+ readEscapedChar(source);
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ if (end == 0)
+ end = source.getPosition();
+
+ String lineData = source.toString(begin, end);
+ EntryLine entryLine = new EntryLine(key, lineData);
+ rawBundle.lines.add(entryLine);
+ }
+ }
+
+ return rawBundle;
+ }
+
+ private static char readEscapedChar(IScannerSource source) {
+ source.readChar('\\');
+ char c = (char) source.readChar();
+ switch (c) {
+ case ' ':
+ case '=':
+ case ':':
+ case '#':
+ case '!':
+ case '\\':
+ return c;
+ case 't':
+ return '\t';
+ case 'n':
+ return '\n';
+ case 'u':
+ int d1 = Character.digit(source.readChar(), 16);
+ int d2 = Character.digit(source.readChar(), 16);
+ int d3 = Character.digit(source.readChar(), 16);
+ int d4 = Character.digit(source.readChar(), 16);
+ if (d1 == -1 || d2 == -1 || d3 == -1 || d4 == -1)
+ throw new LexicalErrorException(source,
+ "Illegal escape sequence");
+ return (char) (d1 << 12 | d2 << 8 | d3 << 4 | d4);
+ default:
+ throw new LexicalErrorException(source, "Unknown escape sequence");
+ }
+ }
+
+ private static boolean isAtLineEnd(IScannerSource source) {
+ return source.lookahead() == '\r' || source.lookahead() == '\n';
+ }
+
+ private static void consumeLineSeparator(IScannerSource source) {
+ if (source.lookahead() == '\n') {
+ source.readChar();
+ source.pushLineSeparator();
+ } else if (source.lookahead() == '\r') {
+ source.readChar();
+ if (source.lookahead() == '\n') {
+ source.readChar();
+ }
+ source.pushLineSeparator();
+ }
+ }
+
+ private static void skipToOneOf(String delimiters, boolean readDelimiter,
+ IScannerSource source) {
+ loop: while (source.hasMoreChars()) {
+ int c = source.readChar();
+ if (delimiters.indexOf(c) != -1) {
+ if (!readDelimiter) {
+ source.unreadChar();
+ }
+ break loop;
+ }
+ if (c == '\r') {
+ source.readChar('\n');
+ source.pushLineSeparator();
+ }
+ }
+ }
+
+ private static void skipAllOf(String string, IScannerSource source) {
+ while (source.hasMoreChars()
+ && string.indexOf(source.lookahead()) != -1) {
+ source.readChar();
+ }
+ }
}
diff --git a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/PropertiesTest.java b/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/PropertiesTest.java
index 43bfe0f..61e2453 100644
--- a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/PropertiesTest.java
+++ b/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/PropertiesTest.java
@@ -18,48 +18,44 @@
public class PropertiesTest extends TestCase {
- private Properties properties;
+ private Properties properties;
- public void test() throws IOException {
- String input = " # a comment line\r\n"
- + "key1=value1\r\n"
- + "key2=a value \\\r\n"
- + " on two lines\r\n"
- + "key3=a value \\\r\n"
- + " "
- + " with an empty line in between\r\n";
- properties = readProperties(input);
- assertValue("value1", "key1");
- assertValue("a value on two lines", "key2");
- assertValue("a value with an empty line in between", "key3");
- }
+ public void test() throws IOException {
+ String input = " # a comment line\r\n" + "key1=value1\r\n"
+ + "key2=a value \\\r\n" + " on two lines\r\n"
+ + "key3=a value \\\r\n" + " "
+ + " with an empty line in between\r\n";
+ properties = readProperties(input);
+ assertValue("value1", "key1");
+ assertValue("a value on two lines", "key2");
+ assertValue("a value with an empty line in between", "key3");
+ }
- public void testKeysWithWhitespace() throws IOException {
- String input = ""
- + "key1\t=key with tab\r\n"
- + "key\\ 2 =key with escaped space\r\n"
- + "key 3 =key with space\r\n";
- properties = readProperties(input);
- assertValue("key with tab", "key1");
- assertValue("key with escaped space", "key 2");
- assertValue("3 =key with space", "key");
- }
+ public void testKeysWithWhitespace() throws IOException {
+ String input = "" + "key1\t=key with tab\r\n"
+ + "key\\ 2 =key with escaped space\r\n"
+ + "key 3 =key with space\r\n";
+ properties = readProperties(input);
+ assertValue("key with tab", "key1");
+ assertValue("key with escaped space", "key 2");
+ assertValue("3 =key with space", "key");
+ }
- public void testKeysWithMissingValue() throws IOException {
- String input = "" + "keyWithoutValue\r\n" + "key=value\r\n";
- properties = readProperties(input);
- assertValue("", "keyWithoutValue");
- assertValue("value", "key");
- }
+ public void testKeysWithMissingValue() throws IOException {
+ String input = "" + "keyWithoutValue\r\n" + "key=value\r\n";
+ properties = readProperties(input);
+ assertValue("", "keyWithoutValue");
+ assertValue("value", "key");
+ }
- private void assertValue(String expected, String key) {
- assertEquals(expected, properties.get(key));
- }
+ private void assertValue(String expected, String key) {
+ assertEquals(expected, properties.get(key));
+ }
- private Properties readProperties(String input) throws IOException {
- Properties properties = new Properties();
- properties.load(new ByteArrayInputStream(input.getBytes()));
- return properties;
- }
+ private Properties readProperties(String input) throws IOException {
+ Properties properties = new Properties();
+ properties.load(new ByteArrayInputStream(input.getBytes()));
+ return properties;
+ }
}
diff --git a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/RawBundleTest.java b/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/RawBundleTest.java
index 579ee4d..c5f2a64 100644
--- a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/RawBundleTest.java
+++ b/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/RawBundleTest.java
@@ -21,64 +21,58 @@
public class RawBundleTest extends TestCase {
- private RawBundle rawBundle;
+ private RawBundle rawBundle;
- public void test() throws IOException {
- String input = " # a comment line\r\n"
- + "key1=value1\r\n"
- + "key2=a value \\\r\n"
- + " on two lines\r\n"
- + "key3=a value \\\r\n"
- + " "
- + " with an empty line in between\r\n";
- rawBundle = readRawBundle(input);
- assertRawData("key1=value1\r\n", "key1");
- assertRawData("key2=a value \\\r\n" + " on two lines\r\n", "key2");
- assertRawData("key3=a value \\\r\n" + " " + " with an empty line in between\r\n", "key3");
- }
+ public void test() throws IOException {
+ String input = " # a comment line\r\n" + "key1=value1\r\n"
+ + "key2=a value \\\r\n" + " on two lines\r\n"
+ + "key3=a value \\\r\n" + " "
+ + " with an empty line in between\r\n";
+ rawBundle = readRawBundle(input);
+ assertRawData("key1=value1\r\n", "key1");
+ assertRawData("key2=a value \\\r\n" + " on two lines\r\n", "key2");
+ assertRawData("key3=a value \\\r\n" + " "
+ + " with an empty line in between\r\n", "key3");
+ }
- public void testKeysWithWhitespace() throws IOException {
- String input = ""
- + "key1\t=key with tab\r\n"
- + "key\\ 2 =key with escaped space\r\n"
- + "key 3 =key with space\r\n";
- rawBundle = readRawBundle(input);
- assertRawData("key1\t=key with tab\r\n", "key1");
- assertRawData("key\\ 2 =key with escaped space\r\n", "key 2");
- assertRawData("key 3 =key with space\r\n", "key");
- }
+ public void testKeysWithWhitespace() throws IOException {
+ String input = "" + "key1\t=key with tab\r\n"
+ + "key\\ 2 =key with escaped space\r\n"
+ + "key 3 =key with space\r\n";
+ rawBundle = readRawBundle(input);
+ assertRawData("key1\t=key with tab\r\n", "key1");
+ assertRawData("key\\ 2 =key with escaped space\r\n", "key 2");
+ assertRawData("key 3 =key with space\r\n", "key");
+ }
- public void testKeysWithMissingValue() throws IOException {
- String input = "keyWithoutValue\r\n" + "key=value\r\n";
- rawBundle = readRawBundle(input);
- assertRawData("keyWithoutValue\r\n", "keyWithoutValue");
- assertRawData("key=value\r\n", "key");
- }
+ public void testKeysWithMissingValue() throws IOException {
+ String input = "keyWithoutValue\r\n" + "key=value\r\n";
+ rawBundle = readRawBundle(input);
+ assertRawData("keyWithoutValue\r\n", "keyWithoutValue");
+ assertRawData("key=value\r\n", "key");
+ }
- public void testPut() throws IOException {
- String input = "" + "key1=value1\r\n" + "key3=value3\r\n";
- rawBundle = readRawBundle(input);
- rawBundle.put("key2", "value2");
- rawBundle.put("key4", "value4");
- rawBundle.put("key0", "value0\\\t");
- StringWriter stringWriter = new StringWriter();
- rawBundle.writeTo(stringWriter);
- assertEquals(""
- + "key0=value0\\\\\\t\r\n"
- + "key1=value1\r\n"
- + "key2=value2\r\n"
- + "key3=value3\r\n"
- + "key4=value4\r\n", stringWriter.toString());
+ public void testPut() throws IOException {
+ String input = "" + "key1=value1\r\n" + "key3=value3\r\n";
+ rawBundle = readRawBundle(input);
+ rawBundle.put("key2", "value2");
+ rawBundle.put("key4", "value4");
+ rawBundle.put("key0", "value0\\\t");
+ StringWriter stringWriter = new StringWriter();
+ rawBundle.writeTo(stringWriter);
+ assertEquals("" + "key0=value0\\\\\\t\r\n" + "key1=value1\r\n"
+ + "key2=value2\r\n" + "key3=value3\r\n" + "key4=value4\r\n",
+ stringWriter.toString());
- }
-
- private void assertRawData(String expected, String key) {
- EntryLine entryLine = rawBundle.getEntryLine(key);
- assertEquals(expected, entryLine.getRawData());
- }
+ }
- private RawBundle readRawBundle(String input) throws IOException {
- return RawBundle.createFrom(new StringReader(input));
- }
+ private void assertRawData(String expected, String key) {
+ EntryLine entryLine = rawBundle.getEntryLine(key);
+ assertEquals(expected, entryLine.getRawData());
+ }
+
+ private RawBundle readRawBundle(String input) throws IOException {
+ return RawBundle.createFrom(new StringReader(input));
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/Activator.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/Activator.java
index c3fdae7..1453eab 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/Activator.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/Activator.java
@@ -40,11 +40,11 @@
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
- if (path.indexOf("icons/") < 0) {
- path = "icons/" + path;
- }
+ if (path.indexOf("icons/") < 0) {
+ path = "icons/" + path;
+ }
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
+ return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
/*
@@ -56,8 +56,8 @@
*/
@Override
public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
+ super.start(context);
+ plugin = this;
}
/*
@@ -69,11 +69,11 @@
*/
@Override
public void stop(BundleContext context) throws Exception {
- // save state of ResourceBundleManager
- ResourceBundleManager.saveManagerState();
+ // save state of ResourceBundleManager
+ ResourceBundleManager.saveManagerState();
- plugin = null;
- super.stop(context);
+ plugin = null;
+ super.stop(context);
}
/**
@@ -82,7 +82,7 @@
* @return the shared instance
*/
public static Activator getDefault() {
- return plugin;
+ return plugin;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java
index 05abe44..0700ff5 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java
@@ -90,7 +90,7 @@
public static final String NATURE_ID = "org.eclipse.babel.tapiji.tools.core.ui.nature";
public static final String BUILDER_ID = Activator.PLUGIN_ID
- + ".I18NBuilder";
+ + ".I18NBuilder";
/* Host project */
private IProject project = null;
@@ -102,717 +102,717 @@
// Define private constructor
private ResourceBundleManager(IProject project) {
- this.project = project;
+ this.project = project;
- RBManager.getInstance(project).addResourceDeltaListener(
- new IResourceDeltaListener() {
+ RBManager.getInstance(project).addResourceDeltaListener(
+ new IResourceDeltaListener() {
- /**
- * {@inheritDoc}
- */
- @Override
- public void onDelete(IMessagesBundleGroup bundleGroup) {
- resources.remove(bundleGroup.getResourceBundleId());
- }
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void onDelete(IMessagesBundleGroup bundleGroup) {
+ resources.remove(bundleGroup.getResourceBundleId());
+ }
- /**
- * {@inheritDoc}
- */
- @Override
- public void onDelete(String resourceBundleId,
- IResource resource) {
- resources.get(resourceBundleId).remove(resource);
- }
- });
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void onDelete(String resourceBundleId,
+ IResource resource) {
+ resources.get(resourceBundleId).remove(resource);
+ }
+ });
}
public static ResourceBundleManager getManager(IProject project) {
- // check if persistant state has been loaded
- if (!state_loaded) {
- stateLoader = getStateLoader();
- stateLoader.loadState();
- state_loaded = true;
- excludedResources = stateLoader.getExcludedResources();
- }
+ // check if persistant state has been loaded
+ if (!state_loaded) {
+ stateLoader = getStateLoader();
+ stateLoader.loadState();
+ state_loaded = true;
+ excludedResources = stateLoader.getExcludedResources();
+ }
- // set host-project
- if (FragmentProjectUtils.isFragment(project)) {
- project = FragmentProjectUtils.getFragmentHost(project);
- }
+ // set host-project
+ if (FragmentProjectUtils.isFragment(project)) {
+ project = FragmentProjectUtils.getFragmentHost(project);
+ }
- ResourceBundleManager manager = rbmanager.get(project);
- if (manager == null) {
- manager = new ResourceBundleManager(project);
- rbmanager.put(project, manager);
- manager.detectResourceBundles();
- }
- return manager;
+ ResourceBundleManager manager = rbmanager.get(project);
+ if (manager == null) {
+ manager = new ResourceBundleManager(project);
+ rbmanager.put(project, manager);
+ manager.detectResourceBundles();
+ }
+ return manager;
}
public Set<Locale> getProvidedLocales(String bundleName) {
- RBManager instance = RBManager.getInstance(project);
+ RBManager instance = RBManager.getInstance(project);
- Set<Locale> locales = new HashSet<Locale>();
- IMessagesBundleGroup group = instance
- .getMessagesBundleGroup(bundleName);
- if (group == null) {
- return locales;
- }
+ Set<Locale> locales = new HashSet<Locale>();
+ IMessagesBundleGroup group = instance
+ .getMessagesBundleGroup(bundleName);
+ if (group == null) {
+ return locales;
+ }
- for (IMessagesBundle bundle : group.getMessagesBundles()) {
- locales.add(bundle.getLocale());
- }
- return locales;
+ for (IMessagesBundle bundle : group.getMessagesBundles()) {
+ locales.add(bundle.getLocale());
+ }
+ return locales;
}
public static String getResourceBundleName(IResource res) {
- String name = res.getName();
- String regex = "^(.*?)" //$NON-NLS-1$
- + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
- + res.getFileExtension() + ")$"; //$NON-NLS-1$
- return name.replaceFirst(regex, "$1"); //$NON-NLS-1$
+ String name = res.getName();
+ String regex = "^(.*?)" //$NON-NLS-1$
+ + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
+ + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
+ + res.getFileExtension() + ")$"; //$NON-NLS-1$
+ return name.replaceFirst(regex, "$1"); //$NON-NLS-1$
}
protected boolean isResourceBundleLoaded(String bundleName) {
- return RBManager.getInstance(project).containsMessagesBundleGroup(
- bundleName);
+ return RBManager.getInstance(project).containsMessagesBundleGroup(
+ bundleName);
}
protected void unloadResource(String bundleName, IResource resource) {
- // TODO implement more efficient
- unloadResourceBundle(bundleName);
- // loadResourceBundle(bundleName);
+ // TODO implement more efficient
+ unloadResourceBundle(bundleName);
+ // loadResourceBundle(bundleName);
}
public static String getResourceBundleId(IResource resource) {
- String packageFragment = "";
+ String packageFragment = "";
- IJavaElement propertyFile = JavaCore.create(resource.getParent());
- if (propertyFile != null && propertyFile instanceof IPackageFragment) {
- packageFragment = ((IPackageFragment) propertyFile)
- .getElementName();
- }
+ IJavaElement propertyFile = JavaCore.create(resource.getParent());
+ if (propertyFile != null && propertyFile instanceof IPackageFragment) {
+ packageFragment = ((IPackageFragment) propertyFile)
+ .getElementName();
+ }
- return (packageFragment.length() > 0 ? packageFragment + "." : "")
- + getResourceBundleName(resource);
+ return (packageFragment.length() > 0 ? packageFragment + "." : "")
+ + getResourceBundleName(resource);
}
public void addBundleResource(IResource resource) {
- if (resource.isDerived()) {
- return;
- }
+ if (resource.isDerived()) {
+ return;
+ }
- String bundleName = getResourceBundleId(resource);
- Set<IResource> res;
+ String bundleName = getResourceBundleId(resource);
+ Set<IResource> res;
- if (!resources.containsKey(bundleName)) {
- res = new HashSet<IResource>();
- } else {
- res = resources.get(bundleName);
- }
+ if (!resources.containsKey(bundleName)) {
+ res = new HashSet<IResource>();
+ } else {
+ res = resources.get(bundleName);
+ }
- res.add(resource);
- resources.put(bundleName, res);
- allBundles.put(bundleName, new HashSet<IResource>(res));
- bundleNames.put(bundleName, getResourceBundleName(resource));
+ res.add(resource);
+ resources.put(bundleName, res);
+ allBundles.put(bundleName, new HashSet<IResource>(res));
+ bundleNames.put(bundleName, getResourceBundleName(resource));
- // Fire resource changed event
- ResourceBundleChangedEvent event = new ResourceBundleChangedEvent(
- ResourceBundleChangedEvent.ADDED, bundleName,
- resource.getProject());
- this.fireResourceBundleChangedEvent(bundleName, event);
+ // Fire resource changed event
+ ResourceBundleChangedEvent event = new ResourceBundleChangedEvent(
+ ResourceBundleChangedEvent.ADDED, bundleName,
+ resource.getProject());
+ this.fireResourceBundleChangedEvent(bundleName, event);
}
protected void removeAllBundleResources(String bundleName) {
- unloadResourceBundle(bundleName);
- resources.remove(bundleName);
- // allBundles.remove(bundleName);
- listeners.remove(bundleName);
+ unloadResourceBundle(bundleName);
+ resources.remove(bundleName);
+ // allBundles.remove(bundleName);
+ listeners.remove(bundleName);
}
public void unloadResourceBundle(String name) {
- RBManager instance = RBManager.getInstance(project);
- instance.deleteMessagesBundleGroup(name);
+ RBManager instance = RBManager.getInstance(project);
+ instance.deleteMessagesBundleGroup(name);
}
public IMessagesBundleGroup getResourceBundle(String name) {
- RBManager instance = RBManager.getInstance(project);
- return instance.getMessagesBundleGroup(name);
+ RBManager instance = RBManager.getInstance(project);
+ return instance.getMessagesBundleGroup(name);
}
public Collection<IResource> getResourceBundles(String bundleName) {
- return resources.get(bundleName);
+ return resources.get(bundleName);
}
public List<String> getResourceBundleNames() {
- List<String> returnList = new ArrayList<String>();
+ List<String> returnList = new ArrayList<String>();
- Iterator<String> it = resources.keySet().iterator();
- while (it.hasNext()) {
- returnList.add(it.next());
- }
- return returnList;
+ Iterator<String> it = resources.keySet().iterator();
+ while (it.hasNext()) {
+ returnList.add(it.next());
+ }
+ return returnList;
}
public IResource getResourceFile(String file) {
- String regex = "^(.*?)" + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." + "properties" + ")$";
- String bundleName = file.replaceFirst(regex, "$1");
- IResource resource = null;
+ String regex = "^(.*?)" + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
+ + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." + "properties" + ")$";
+ String bundleName = file.replaceFirst(regex, "$1");
+ IResource resource = null;
- for (IResource res : resources.get(bundleName)) {
- if (res.getName().equalsIgnoreCase(file)) {
- resource = res;
- break;
- }
- }
+ for (IResource res : resources.get(bundleName)) {
+ if (res.getName().equalsIgnoreCase(file)) {
+ resource = res;
+ break;
+ }
+ }
- return resource;
+ return resource;
}
public void fireResourceBundleChangedEvent(String bundleName,
- ResourceBundleChangedEvent event) {
- List<IResourceBundleChangedListener> l = listeners.get(bundleName);
+ ResourceBundleChangedEvent event) {
+ List<IResourceBundleChangedListener> l = listeners.get(bundleName);
- if (l == null) {
- return;
- }
+ if (l == null) {
+ return;
+ }
- for (IResourceBundleChangedListener listener : l) {
- listener.resourceBundleChanged(event);
- }
+ for (IResourceBundleChangedListener listener : l) {
+ listener.resourceBundleChanged(event);
+ }
}
public void registerResourceBundleChangeListener(String bundleName,
- IResourceBundleChangedListener listener) {
- List<IResourceBundleChangedListener> l = listeners.get(bundleName);
- if (l == null) {
- l = new ArrayList<IResourceBundleChangedListener>();
- }
- l.add(listener);
- listeners.put(bundleName, l);
+ IResourceBundleChangedListener listener) {
+ List<IResourceBundleChangedListener> l = listeners.get(bundleName);
+ if (l == null) {
+ l = new ArrayList<IResourceBundleChangedListener>();
+ }
+ l.add(listener);
+ listeners.put(bundleName, l);
}
public void unregisterResourceBundleChangeListener(String bundleName,
- IResourceBundleChangedListener listener) {
- List<IResourceBundleChangedListener> l = listeners.get(bundleName);
- if (l == null) {
- return;
- }
- l.remove(listener);
- listeners.put(bundleName, l);
+ IResourceBundleChangedListener listener) {
+ List<IResourceBundleChangedListener> l = listeners.get(bundleName);
+ if (l == null) {
+ return;
+ }
+ l.remove(listener);
+ listeners.put(bundleName, l);
}
protected void detectResourceBundles() {
- try {
- project.accept(new ResourceBundleDetectionVisitor(getProject()));
+ try {
+ project.accept(new ResourceBundleDetectionVisitor(getProject()));
- IProject[] fragments = FragmentProjectUtils.lookupFragment(project);
- if (fragments != null) {
- for (IProject p : fragments) {
- p.accept(new ResourceBundleDetectionVisitor(getProject()));
- }
- }
- } catch (CoreException e) {
- }
+ IProject[] fragments = FragmentProjectUtils.lookupFragment(project);
+ if (fragments != null) {
+ for (IProject p : fragments) {
+ p.accept(new ResourceBundleDetectionVisitor(getProject()));
+ }
+ }
+ } catch (CoreException e) {
+ }
}
public IProject getProject() {
- return project;
+ return project;
}
public List<String> getResourceBundleIdentifiers() {
- List<String> returnList = new ArrayList<String>();
+ List<String> returnList = new ArrayList<String>();
- // TODO check other resource bundles that are available on the curren
- // class path
- Iterator<String> it = this.resources.keySet().iterator();
- while (it.hasNext()) {
- returnList.add(it.next());
- }
+ // TODO check other resource bundles that are available on the curren
+ // class path
+ Iterator<String> it = this.resources.keySet().iterator();
+ while (it.hasNext()) {
+ returnList.add(it.next());
+ }
- return returnList;
+ return returnList;
}
public static List<String> getAllResourceBundleNames() {
- List<String> returnList = new ArrayList<String>();
+ List<String> returnList = new ArrayList<String>();
- for (IProject p : getAllSupportedProjects()) {
- if (!FragmentProjectUtils.isFragment(p)) {
- Iterator<String> it = getManager(p).resources.keySet()
- .iterator();
- while (it.hasNext()) {
- returnList.add(p.getName() + "/" + it.next());
- }
- }
- }
- return returnList;
+ for (IProject p : getAllSupportedProjects()) {
+ if (!FragmentProjectUtils.isFragment(p)) {
+ Iterator<String> it = getManager(p).resources.keySet()
+ .iterator();
+ while (it.hasNext()) {
+ returnList.add(p.getName() + "/" + it.next());
+ }
+ }
+ }
+ return returnList;
}
public static Set<IProject> getAllSupportedProjects() {
- IProject[] projects = ResourcesPlugin.getWorkspace().getRoot()
- .getProjects();
- Set<IProject> projs = new HashSet<IProject>();
+ IProject[] projects = ResourcesPlugin.getWorkspace().getRoot()
+ .getProjects();
+ Set<IProject> projs = new HashSet<IProject>();
- for (IProject p : projects) {
- try {
- if (p.isOpen() && p.hasNature(NATURE_ID)) {
- projs.add(p);
- }
- } catch (CoreException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- return projs;
+ for (IProject p : projects) {
+ try {
+ if (p.isOpen() && p.hasNature(NATURE_ID)) {
+ projs.add(p);
+ }
+ } catch (CoreException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ return projs;
}
public String getKeyHoverString(String rbName, String key) {
- try {
- RBManager instance = RBManager.getInstance(project);
- IMessagesBundleGroup bundleGroup = instance
- .getMessagesBundleGroup(rbName);
- if (!bundleGroup.containsKey(key)) {
- return null;
- }
+ try {
+ RBManager instance = RBManager.getInstance(project);
+ IMessagesBundleGroup bundleGroup = instance
+ .getMessagesBundleGroup(rbName);
+ if (!bundleGroup.containsKey(key)) {
+ return null;
+ }
- String hoverText = "<html><head></head><body>";
+ String hoverText = "<html><head></head><body>";
- for (IMessage message : bundleGroup.getMessages(key)) {
- String displayName = message.getLocale() == null ? "Default"
- : message.getLocale().getDisplayName();
- String value = message.getValue();
- hoverText += "<b><i>" + displayName + "</i></b><br/>"
- + value.replace("\n", "<br/>") + "<br/><br/>";
- }
- return hoverText + "</body></html>";
- } catch (Exception e) {
- // silent catch
- return "";
- }
+ for (IMessage message : bundleGroup.getMessages(key)) {
+ String displayName = message.getLocale() == null ? "Default"
+ : message.getLocale().getDisplayName();
+ String value = message.getValue();
+ hoverText += "<b><i>" + displayName + "</i></b><br/>"
+ + value.replace("\n", "<br/>") + "<br/><br/>";
+ }
+ return hoverText + "</body></html>";
+ } catch (Exception e) {
+ // silent catch
+ return "";
+ }
}
public boolean isKeyBroken(String rbName, String key) {
- IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(
- project).getMessagesBundleGroup(rbName);
- if (messagesBundleGroup == null) {
- return true;
- } else {
- return !messagesBundleGroup.containsKey(key);
- }
+ IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(
+ project).getMessagesBundleGroup(rbName);
+ if (messagesBundleGroup == null) {
+ return true;
+ } else {
+ return !messagesBundleGroup.containsKey(key);
+ }
- // if (!resourceBundles.containsKey(rbName))
- // return true;
- // return !this.isResourceExisting(rbName, key);
+ // if (!resourceBundles.containsKey(rbName))
+ // return true;
+ // return !this.isResourceExisting(rbName, key);
}
protected void excludeSingleResource(IResource res) {
- IResourceDescriptor rd = new ResourceDescriptor(res);
- org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils
- .deleteAuditMarkersForResource(res);
+ IResourceDescriptor rd = new ResourceDescriptor(res);
+ org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils
+ .deleteAuditMarkersForResource(res);
- // exclude resource
- excludedResources.add(rd);
- Collection<Object> changedExclusoins = new HashSet<Object>();
- changedExclusoins.add(res);
- fireResourceExclusionEvent(new ResourceExclusionEvent(changedExclusoins));
+ // exclude resource
+ excludedResources.add(rd);
+ Collection<Object> changedExclusoins = new HashSet<Object>();
+ changedExclusoins.add(res);
+ fireResourceExclusionEvent(new ResourceExclusionEvent(changedExclusoins));
- // Check if the excluded resource represents a resource-bundle
- if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils
- .isResourceBundleFile(res)) {
- String bundleName = getResourceBundleId(res);
- Set<IResource> resSet = resources.remove(bundleName);
- if (resSet != null) {
- resSet.remove(res);
+ // Check if the excluded resource represents a resource-bundle
+ if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils
+ .isResourceBundleFile(res)) {
+ String bundleName = getResourceBundleId(res);
+ Set<IResource> resSet = resources.remove(bundleName);
+ if (resSet != null) {
+ resSet.remove(res);
- if (!resSet.isEmpty()) {
- resources.put(bundleName, resSet);
- unloadResource(bundleName, res);
- } else {
- rd.setBundleId(bundleName);
- unloadResourceBundle(bundleName);
- try {
- res.getProject().build(
- IncrementalProjectBuilder.FULL_BUILD,
- BUILDER_ID, null, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
+ if (!resSet.isEmpty()) {
+ resources.put(bundleName, resSet);
+ unloadResource(bundleName, res);
+ } else {
+ rd.setBundleId(bundleName);
+ unloadResourceBundle(bundleName);
+ try {
+ res.getProject().build(
+ IncrementalProjectBuilder.FULL_BUILD,
+ BUILDER_ID, null, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
- fireResourceBundleChangedEvent(getResourceBundleId(res),
- new ResourceBundleChangedEvent(
- ResourceBundleChangedEvent.EXCLUDED,
- bundleName, res.getProject()));
- }
- }
+ fireResourceBundleChangedEvent(getResourceBundleId(res),
+ new ResourceBundleChangedEvent(
+ ResourceBundleChangedEvent.EXCLUDED,
+ bundleName, res.getProject()));
+ }
+ }
}
public void excludeResource(IResource res, IProgressMonitor monitor) {
- try {
- if (monitor == null) {
- monitor = new NullProgressMonitor();
- }
+ try {
+ if (monitor == null) {
+ monitor = new NullProgressMonitor();
+ }
- final List<IResource> resourceSubTree = new ArrayList<IResource>();
- res.accept(new IResourceVisitor() {
+ final List<IResource> resourceSubTree = new ArrayList<IResource>();
+ res.accept(new IResourceVisitor() {
- @Override
- public boolean visit(IResource resource) throws CoreException {
- Logger.logInfo("Excluding resource '"
- + resource.getFullPath().toOSString() + "'");
- resourceSubTree.add(resource);
- return true;
- }
+ @Override
+ public boolean visit(IResource resource) throws CoreException {
+ Logger.logInfo("Excluding resource '"
+ + resource.getFullPath().toOSString() + "'");
+ resourceSubTree.add(resource);
+ return true;
+ }
- });
+ });
- // Iterate previously retrieved resource and exclude them from
- // Internationalization
- monitor.beginTask(
- "Exclude resources from Internationalization context",
- resourceSubTree.size());
- try {
- for (IResource resource : resourceSubTree) {
- excludeSingleResource(resource);
- org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils
- .deleteAuditMarkersForResource(resource);
- monitor.worked(1);
- }
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- monitor.done();
- }
- } catch (CoreException e) {
- Logger.logError(e);
- }
+ // Iterate previously retrieved resource and exclude them from
+ // Internationalization
+ monitor.beginTask(
+ "Exclude resources from Internationalization context",
+ resourceSubTree.size());
+ try {
+ for (IResource resource : resourceSubTree) {
+ excludeSingleResource(resource);
+ org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils
+ .deleteAuditMarkersForResource(resource);
+ monitor.worked(1);
+ }
+ } catch (Exception e) {
+ Logger.logError(e);
+ } finally {
+ monitor.done();
+ }
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
}
public void includeResource(IResource res, IProgressMonitor monitor) {
- if (monitor == null) {
- monitor = new NullProgressMonitor();
- }
+ if (monitor == null) {
+ monitor = new NullProgressMonitor();
+ }
- final Collection<Object> changedResources = new HashSet<Object>();
- IResource resource = res;
+ final Collection<Object> changedResources = new HashSet<Object>();
+ IResource resource = res;
- if (!excludedResources.contains(new ResourceDescriptor(res))) {
- while (!(resource instanceof IProject || resource instanceof IWorkspaceRoot)) {
- if (excludedResources
- .contains(new ResourceDescriptor(resource))) {
- excludeResource(resource, monitor);
- changedResources.add(resource);
- break;
- } else {
- resource = resource.getParent();
- }
- }
- }
+ if (!excludedResources.contains(new ResourceDescriptor(res))) {
+ while (!(resource instanceof IProject || resource instanceof IWorkspaceRoot)) {
+ if (excludedResources
+ .contains(new ResourceDescriptor(resource))) {
+ excludeResource(resource, monitor);
+ changedResources.add(resource);
+ break;
+ } else {
+ resource = resource.getParent();
+ }
+ }
+ }
- try {
- res.accept(new IResourceVisitor() {
+ try {
+ res.accept(new IResourceVisitor() {
- @Override
- public boolean visit(IResource resource) throws CoreException {
- changedResources.add(resource);
- return true;
- }
- });
+ @Override
+ public boolean visit(IResource resource) throws CoreException {
+ changedResources.add(resource);
+ return true;
+ }
+ });
- monitor.beginTask("Add resources to Internationalization context",
- changedResources.size());
- try {
- for (Object r : changedResources) {
- excludedResources.remove(new ResourceDescriptor(
- (IResource) r));
- monitor.worked(1);
- }
+ monitor.beginTask("Add resources to Internationalization context",
+ changedResources.size());
+ try {
+ for (Object r : changedResources) {
+ excludedResources.remove(new ResourceDescriptor(
+ (IResource) r));
+ monitor.worked(1);
+ }
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- monitor.done();
- }
- } catch (Exception e) {
- Logger.logError(e);
- }
+ } catch (Exception e) {
+ Logger.logError(e);
+ } finally {
+ monitor.done();
+ }
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
- try {
- res.touch(null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
+ try {
+ res.touch(null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
- // Check if the included resource represents a resource-bundle
- if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils
- .isResourceBundleFile(res)) {
- String bundleName = getResourceBundleId(res);
- boolean newRB = resources.containsKey(bundleName);
+ // Check if the included resource represents a resource-bundle
+ if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils
+ .isResourceBundleFile(res)) {
+ String bundleName = getResourceBundleId(res);
+ boolean newRB = resources.containsKey(bundleName);
- this.addBundleResource(res);
- this.unloadResourceBundle(bundleName);
- // this.loadResourceBundle(bundleName);
+ this.addBundleResource(res);
+ this.unloadResourceBundle(bundleName);
+ // this.loadResourceBundle(bundleName);
- if (newRB) {
- try {
- resource.getProject().build(
- IncrementalProjectBuilder.FULL_BUILD, BUILDER_ID,
- null, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
- fireResourceBundleChangedEvent(getResourceBundleId(res),
- new ResourceBundleChangedEvent(
- ResourceBundleChangedEvent.INCLUDED, bundleName,
- res.getProject()));
- }
+ if (newRB) {
+ try {
+ resource.getProject().build(
+ IncrementalProjectBuilder.FULL_BUILD, BUILDER_ID,
+ null, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+ fireResourceBundleChangedEvent(getResourceBundleId(res),
+ new ResourceBundleChangedEvent(
+ ResourceBundleChangedEvent.INCLUDED, bundleName,
+ res.getProject()));
+ }
- fireResourceExclusionEvent(new ResourceExclusionEvent(changedResources));
+ fireResourceExclusionEvent(new ResourceExclusionEvent(changedResources));
}
protected void fireResourceExclusionEvent(ResourceExclusionEvent event) {
- for (IResourceExclusionListener listener : exclusionListeners) {
- listener.exclusionChanged(event);
- }
+ for (IResourceExclusionListener listener : exclusionListeners) {
+ listener.exclusionChanged(event);
+ }
}
public static boolean isResourceExcluded(IResource res) {
- IResource resource = res;
+ IResource resource = res;
- if (!state_loaded) {
- stateLoader.loadState();
- }
+ if (!state_loaded) {
+ stateLoader.loadState();
+ }
- boolean isExcluded = false;
+ boolean isExcluded = false;
- do {
- if (excludedResources.contains(new ResourceDescriptor(resource))) {
- if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils
- .isResourceBundleFile(resource)) {
- Set<IResource> resources = allBundles
- .remove(getResourceBundleName(resource));
- if (resources == null) {
- resources = new HashSet<IResource>();
- }
- resources.add(resource);
- allBundles.put(getResourceBundleName(resource), resources);
- }
+ do {
+ if (excludedResources.contains(new ResourceDescriptor(resource))) {
+ if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils
+ .isResourceBundleFile(resource)) {
+ Set<IResource> resources = allBundles
+ .remove(getResourceBundleName(resource));
+ if (resources == null) {
+ resources = new HashSet<IResource>();
+ }
+ resources.add(resource);
+ allBundles.put(getResourceBundleName(resource), resources);
+ }
- isExcluded = true;
- break;
- }
- resource = resource.getParent();
- } while (resource != null
- && !(resource instanceof IProject || resource instanceof IWorkspaceRoot)
- && checkResourceExclusionRoot);
+ isExcluded = true;
+ break;
+ }
+ resource = resource.getParent();
+ } while (resource != null
+ && !(resource instanceof IProject || resource instanceof IWorkspaceRoot)
+ && checkResourceExclusionRoot);
- return isExcluded; // excludedResources.contains(new
- // ResourceDescriptor(res));
+ return isExcluded; // excludedResources.contains(new
+ // ResourceDescriptor(res));
}
public IFile getRandomFile(String bundleName) {
- try {
- Collection<IMessagesBundle> messagesBundles = RBManager
- .getInstance(project).getMessagesBundleGroup(bundleName)
- .getMessagesBundles();
- IMessagesBundle bundle = messagesBundles.iterator().next();
- return FileUtils.getFile(bundle);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
+ try {
+ Collection<IMessagesBundle> messagesBundles = RBManager
+ .getInstance(project).getMessagesBundleGroup(bundleName)
+ .getMessagesBundles();
+ IMessagesBundle bundle = messagesBundles.iterator().next();
+ return FileUtils.getFile(bundle);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
}
@Deprecated
protected static boolean isResourceExcluded(IProject project, String bname) {
- Iterator<IResourceDescriptor> itExcl = excludedResources.iterator();
- while (itExcl.hasNext()) {
- IResourceDescriptor rd = itExcl.next();
- if (project.getName().equals(rd.getProjectName())
- && bname.equals(rd.getBundleId())) {
- return true;
- }
- }
- return false;
+ Iterator<IResourceDescriptor> itExcl = excludedResources.iterator();
+ while (itExcl.hasNext()) {
+ IResourceDescriptor rd = itExcl.next();
+ if (project.getName().equals(rd.getProjectName())
+ && bname.equals(rd.getBundleId())) {
+ return true;
+ }
+ }
+ return false;
}
public static ResourceBundleManager getManager(String projectName) {
- for (IProject p : getAllSupportedProjects()) {
- if (p.getName().equalsIgnoreCase(projectName)) {
- // check if the projectName is a fragment and return the manager
- // for the host
- if (FragmentProjectUtils.isFragment(p)) {
- return getManager(FragmentProjectUtils.getFragmentHost(p));
- } else {
- return getManager(p);
- }
- }
- }
- return null;
+ for (IProject p : getAllSupportedProjects()) {
+ if (p.getName().equalsIgnoreCase(projectName)) {
+ // check if the projectName is a fragment and return the manager
+ // for the host
+ if (FragmentProjectUtils.isFragment(p)) {
+ return getManager(FragmentProjectUtils.getFragmentHost(p));
+ } else {
+ return getManager(p);
+ }
+ }
+ }
+ return null;
}
public IFile getResourceBundleFile(String resourceBundle, Locale l) {
- IFile res = null;
- Set<IResource> resSet = resources.get(resourceBundle);
+ IFile res = null;
+ Set<IResource> resSet = resources.get(resourceBundle);
- if (resSet != null) {
- for (IResource resource : resSet) {
- Locale refLoc = NameUtils.getLocaleByName(resourceBundle,
- resource.getName());
- if (refLoc == null
- && l == null
- || (refLoc != null && refLoc.equals(l) || l != null
- && l.equals(refLoc))) {
- res = resource.getProject().getFile(
- resource.getProjectRelativePath());
- break;
- }
- }
- }
+ if (resSet != null) {
+ for (IResource resource : resSet) {
+ Locale refLoc = NameUtils.getLocaleByName(resourceBundle,
+ resource.getName());
+ if (refLoc == null
+ && l == null
+ || (refLoc != null && refLoc.equals(l) || l != null
+ && l.equals(refLoc))) {
+ res = resource.getProject().getFile(
+ resource.getProjectRelativePath());
+ break;
+ }
+ }
+ }
- return res;
+ return res;
}
public Set<IResource> getAllResourceBundleResources(String resourceBundle) {
- return allBundles.get(resourceBundle);
+ return allBundles.get(resourceBundle);
}
public void registerResourceExclusionListener(
- IResourceExclusionListener listener) {
- exclusionListeners.add(listener);
+ IResourceExclusionListener listener) {
+ exclusionListeners.add(listener);
}
public void unregisterResourceExclusionListener(
- IResourceExclusionListener listener) {
- exclusionListeners.remove(listener);
+ IResourceExclusionListener listener) {
+ exclusionListeners.remove(listener);
}
public boolean isResourceExclusionListenerRegistered(
- IResourceExclusionListener listener) {
- return exclusionListeners.contains(listener);
+ IResourceExclusionListener listener) {
+ return exclusionListeners.contains(listener);
}
public static void unregisterResourceExclusionListenerFromAllManagers(
- IResourceExclusionListener excludedResource) {
- for (ResourceBundleManager mgr : rbmanager.values()) {
- mgr.unregisterResourceExclusionListener(excludedResource);
- }
+ IResourceExclusionListener excludedResource) {
+ for (ResourceBundleManager mgr : rbmanager.values()) {
+ mgr.unregisterResourceExclusionListener(excludedResource);
+ }
}
public void addResourceBundleEntry(String resourceBundleId, String key,
- Locale locale, String message) throws ResourceBundleException {
+ Locale locale, String message) throws ResourceBundleException {
- RBManager instance = RBManager.getInstance(project);
- IMessagesBundleGroup bundleGroup = instance
- .getMessagesBundleGroup(resourceBundleId);
- IMessage entry = bundleGroup.getMessage(key, locale);
+ RBManager instance = RBManager.getInstance(project);
+ IMessagesBundleGroup bundleGroup = instance
+ .getMessagesBundleGroup(resourceBundleId);
+ IMessage entry = bundleGroup.getMessage(key, locale);
- if (entry == null) {
- DirtyHack.setFireEnabled(false);
+ if (entry == null) {
+ DirtyHack.setFireEnabled(false);
- IMessagesBundle messagesBundle = bundleGroup
- .getMessagesBundle(locale);
- IMessage m = MessageFactory.createMessage(key, locale);
- m.setText(message);
- messagesBundle.addMessage(m);
+ IMessagesBundle messagesBundle = bundleGroup
+ .getMessagesBundle(locale);
+ IMessage m = MessageFactory.createMessage(key, locale);
+ m.setText(message);
+ messagesBundle.addMessage(m);
- FileUtils.writeToFile(messagesBundle);
- instance.fireResourceChanged(messagesBundle);
+ FileUtils.writeToFile(messagesBundle);
+ instance.fireResourceChanged(messagesBundle);
- DirtyHack.setFireEnabled(true);
+ DirtyHack.setFireEnabled(true);
- // notify the PropertyKeySelectionTree
- instance.fireEditorChanged();
- }
+ // notify the PropertyKeySelectionTree
+ instance.fireEditorChanged();
+ }
}
public void saveResourceBundle(String resourceBundleId,
- IMessagesBundleGroup newBundleGroup) throws ResourceBundleException {
+ IMessagesBundleGroup newBundleGroup) throws ResourceBundleException {
- // RBManager.getInstance().
+ // RBManager.getInstance().
}
public void removeResourceBundleEntry(String resourceBundleId,
- List<String> keys) throws ResourceBundleException {
+ List<String> keys) throws ResourceBundleException {
- RBManager instance = RBManager.getInstance(project);
- IMessagesBundleGroup messagesBundleGroup = instance
- .getMessagesBundleGroup(resourceBundleId);
+ RBManager instance = RBManager.getInstance(project);
+ IMessagesBundleGroup messagesBundleGroup = instance
+ .getMessagesBundleGroup(resourceBundleId);
- DirtyHack.setFireEnabled(false);
+ DirtyHack.setFireEnabled(false);
- for (String key : keys) {
- messagesBundleGroup.removeMessages(key);
- }
+ for (String key : keys) {
+ messagesBundleGroup.removeMessages(key);
+ }
- instance.writeToFile(messagesBundleGroup);
+ instance.writeToFile(messagesBundleGroup);
- DirtyHack.setFireEnabled(true);
+ DirtyHack.setFireEnabled(true);
- // notify the PropertyKeySelectionTree
- instance.fireEditorChanged();
+ // notify the PropertyKeySelectionTree
+ instance.fireEditorChanged();
}
public boolean isResourceExisting(String bundleId, String key) {
- boolean keyExists = false;
- IMessagesBundleGroup bGroup = getResourceBundle(bundleId);
+ boolean keyExists = false;
+ IMessagesBundleGroup bGroup = getResourceBundle(bundleId);
- if (bGroup != null) {
- keyExists = bGroup.isKey(key);
- }
+ if (bGroup != null) {
+ keyExists = bGroup.isKey(key);
+ }
- return keyExists;
+ return keyExists;
}
public static void rebuildProject(IResource resource) {
- try {
- resource.touch(null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
+ try {
+ resource.touch(null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
}
public Set<Locale> getProjectProvidedLocales() {
- Set<Locale> locales = new HashSet<Locale>();
+ Set<Locale> locales = new HashSet<Locale>();
- for (String bundleId : getResourceBundleNames()) {
- Set<Locale> rb_l = getProvidedLocales(bundleId);
- if (!rb_l.isEmpty()) {
- Object[] bundlelocales = rb_l.toArray();
- for (Object l : bundlelocales) {
- /* TODO check if useful to add the default */
- if (!locales.contains(l)) {
- locales.add((Locale) l);
- }
- }
- }
- }
- return locales;
+ for (String bundleId : getResourceBundleNames()) {
+ Set<Locale> rb_l = getProvidedLocales(bundleId);
+ if (!rb_l.isEmpty()) {
+ Object[] bundlelocales = rb_l.toArray();
+ for (Object l : bundlelocales) {
+ /* TODO check if useful to add the default */
+ if (!locales.contains(l)) {
+ locales.add((Locale) l);
+ }
+ }
+ }
+ }
+ return locales;
}
private static IStateLoader getStateLoader() {
- IExtensionPoint extp = Platform.getExtensionRegistry()
- .getExtensionPoint(
- "org.eclipse.babel.tapiji.tools.core" + ".stateLoader");
- IConfigurationElement[] elements = extp.getConfigurationElements();
+ IExtensionPoint extp = Platform.getExtensionRegistry()
+ .getExtensionPoint(
+ "org.eclipse.babel.tapiji.tools.core" + ".stateLoader");
+ IConfigurationElement[] elements = extp.getConfigurationElements();
- if (elements.length != 0) {
- try {
- return (IStateLoader) elements[0]
- .createExecutableExtension("class");
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- return null;
+ if (elements.length != 0) {
+ try {
+ return (IStateLoader) elements[0]
+ .createExecutableExtension("class");
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ return null;
}
public static void saveManagerState() {
- stateLoader.saveState();
+ stateLoader.saveState();
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java
index 0cd1afc..f767964 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java
@@ -25,40 +25,40 @@
@Override
public void audit(IResource resource) {
- if (RBFileUtils.isResourceBundleFile(resource)) {
- ResourceBundleManager.getManager(resource.getProject())
- .addBundleResource(resource);
- }
+ if (RBFileUtils.isResourceBundleFile(resource)) {
+ ResourceBundleManager.getManager(resource.getProject())
+ .addBundleResource(resource);
+ }
}
@Override
public String[] getFileEndings() {
- return new String[] { "properties" };
+ return new String[] { "properties" };
}
@Override
public List<ILocation> getConstantStringLiterals() {
- return new ArrayList<ILocation>();
+ return new ArrayList<ILocation>();
}
@Override
public List<ILocation> getBrokenResourceReferences() {
- return new ArrayList<ILocation>();
+ return new ArrayList<ILocation>();
}
@Override
public List<ILocation> getBrokenBundleReferences() {
- return new ArrayList<ILocation>();
+ return new ArrayList<ILocation>();
}
@Override
public String getContextId() {
- return "resource_bundle";
+ return "resource_bundle";
}
@Override
public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
- return null;
+ return null;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceBundleDetectionVisitor.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceBundleDetectionVisitor.java
index 66fe8b5..3ef3150 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceBundleDetectionVisitor.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceBundleDetectionVisitor.java
@@ -21,43 +21,43 @@
import org.eclipse.core.runtime.CoreException;
public class ResourceBundleDetectionVisitor implements IResourceVisitor,
- IResourceDeltaVisitor {
+ IResourceDeltaVisitor {
private IProject project = null;
public ResourceBundleDetectionVisitor(IProject project) {
- this.project = project;
+ this.project = project;
}
@Override
public boolean visit(IResource resource) throws CoreException {
- try {
- if (RBFileUtils.isResourceBundleFile(resource)) {
- Logger.logInfo("Loading Resource-Bundle file '"
- + resource.getName() + "'");
- if (!ResourceBundleManager.isResourceExcluded(resource)) {
- ResourceBundleManager.getManager(project)
- .addBundleResource(resource);
- }
- return false;
- } else {
- return true;
- }
- } catch (Exception e) {
- return false;
- }
+ try {
+ if (RBFileUtils.isResourceBundleFile(resource)) {
+ Logger.logInfo("Loading Resource-Bundle file '"
+ + resource.getName() + "'");
+ if (!ResourceBundleManager.isResourceExcluded(resource)) {
+ ResourceBundleManager.getManager(project)
+ .addBundleResource(resource);
+ }
+ return false;
+ } else {
+ return true;
+ }
+ } catch (Exception e) {
+ return false;
+ }
}
@Override
public boolean visit(IResourceDelta delta) throws CoreException {
- IResource resource = delta.getResource();
+ IResource resource = delta.getResource();
- if (RBFileUtils.isResourceBundleFile(resource)) {
- // ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
- return false;
- }
+ if (RBFileUtils.isResourceBundleFile(resource)) {
+ // ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
+ return false;
+ }
- return true;
+ return true;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceFinder.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceFinder.java
index 61fe27b..0f73345 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceFinder.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceFinder.java
@@ -28,29 +28,29 @@
Set<String> supportedExtensions = null;
public ResourceFinder(Set<String> ext) {
- javaResources = new ArrayList<IResource>();
- supportedExtensions = ext;
+ javaResources = new ArrayList<IResource>();
+ supportedExtensions = ext;
}
@Override
public boolean visit(IResource resource) throws CoreException {
- if (I18nBuilder.isResourceAuditable(resource, supportedExtensions)) {
- Logger.logInfo("Audit necessary for resource '"
- + resource.getFullPath().toOSString() + "'");
- javaResources.add(resource);
- return false;
- } else
- return true;
+ if (I18nBuilder.isResourceAuditable(resource, supportedExtensions)) {
+ Logger.logInfo("Audit necessary for resource '"
+ + resource.getFullPath().toOSString() + "'");
+ javaResources.add(resource);
+ return false;
+ } else
+ return true;
}
public List<IResource> getResources() {
- return javaResources;
+ return javaResources;
}
@Override
public boolean visit(IResourceDelta delta) throws CoreException {
- visit(delta.getResource());
- return true;
+ visit(delta.getResource());
+ return true;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/BuilderPropertyChangeListener.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/BuilderPropertyChangeListener.java
index 3f3c7c1..313140e 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/BuilderPropertyChangeListener.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/BuilderPropertyChangeListener.java
@@ -33,102 +33,102 @@
@Override
public void propertyChange(PropertyChangeEvent event) {
- if (event.getNewValue().equals(true) && isTapiJIPropertyp(event))
- rebuild();
+ if (event.getNewValue().equals(true) && isTapiJIPropertyp(event))
+ rebuild();
- if (event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN))
- rebuild();
+ if (event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN))
+ rebuild();
- if (event.getNewValue().equals(false)) {
- if (event.getProperty().equals(TapiJIPreferences.AUDIT_RESOURCE)) {
- deleteMarkersByCause(EditorUtils.MARKER_ID, -1);
- }
- if (event.getProperty().equals(TapiJIPreferences.AUDIT_RB)) {
- deleteMarkersByCause(EditorUtils.RB_MARKER_ID, -1);
- }
- if (event.getProperty().equals(
- TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)) {
- deleteMarkersByCause(EditorUtils.RB_MARKER_ID,
- IMarkerConstants.CAUSE_UNSPEZIFIED_KEY);
- }
- if (event.getProperty().equals(TapiJIPreferences.AUDIT_SAME_VALUE)) {
- deleteMarkersByCause(EditorUtils.RB_MARKER_ID,
- IMarkerConstants.CAUSE_SAME_VALUE);
- }
- if (event.getProperty().equals(
- TapiJIPreferences.AUDIT_MISSING_LANGUAGE)) {
- deleteMarkersByCause(EditorUtils.RB_MARKER_ID,
- IMarkerConstants.CAUSE_MISSING_LANGUAGE);
- }
- }
+ if (event.getNewValue().equals(false)) {
+ if (event.getProperty().equals(TapiJIPreferences.AUDIT_RESOURCE)) {
+ deleteMarkersByCause(EditorUtils.MARKER_ID, -1);
+ }
+ if (event.getProperty().equals(TapiJIPreferences.AUDIT_RB)) {
+ deleteMarkersByCause(EditorUtils.RB_MARKER_ID, -1);
+ }
+ if (event.getProperty().equals(
+ TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)) {
+ deleteMarkersByCause(EditorUtils.RB_MARKER_ID,
+ IMarkerConstants.CAUSE_UNSPEZIFIED_KEY);
+ }
+ if (event.getProperty().equals(TapiJIPreferences.AUDIT_SAME_VALUE)) {
+ deleteMarkersByCause(EditorUtils.RB_MARKER_ID,
+ IMarkerConstants.CAUSE_SAME_VALUE);
+ }
+ if (event.getProperty().equals(
+ TapiJIPreferences.AUDIT_MISSING_LANGUAGE)) {
+ deleteMarkersByCause(EditorUtils.RB_MARKER_ID,
+ IMarkerConstants.CAUSE_MISSING_LANGUAGE);
+ }
+ }
}
private boolean isTapiJIPropertyp(PropertyChangeEvent event) {
- if (event.getProperty().equals(TapiJIPreferences.AUDIT_RESOURCE)
- || event.getProperty().equals(TapiJIPreferences.AUDIT_RB)
- || event.getProperty().equals(
- TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)
- || event.getProperty().equals(
- TapiJIPreferences.AUDIT_SAME_VALUE)
- || event.getProperty().equals(
- TapiJIPreferences.AUDIT_MISSING_LANGUAGE))
- return true;
- else
- return false;
+ if (event.getProperty().equals(TapiJIPreferences.AUDIT_RESOURCE)
+ || event.getProperty().equals(TapiJIPreferences.AUDIT_RB)
+ || event.getProperty().equals(
+ TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)
+ || event.getProperty().equals(
+ TapiJIPreferences.AUDIT_SAME_VALUE)
+ || event.getProperty().equals(
+ TapiJIPreferences.AUDIT_MISSING_LANGUAGE))
+ return true;
+ else
+ return false;
}
/*
* cause == -1 ignores the attribute 'case'
*/
private void deleteMarkersByCause(final String markertype, final int cause) {
- final IWorkspace workspace = ResourcesPlugin.getWorkspace();
- BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
- @Override
- public void run() {
- IMarker[] marker;
- try {
- marker = workspace.getRoot().findMarkers(markertype, true,
- IResource.DEPTH_INFINITE);
+ final IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
+ @Override
+ public void run() {
+ IMarker[] marker;
+ try {
+ marker = workspace.getRoot().findMarkers(markertype, true,
+ IResource.DEPTH_INFINITE);
- for (IMarker m : marker) {
- if (m.exists()) {
- if (m.getAttribute("cause", -1) == cause)
- m.delete();
- if (cause == -1)
- m.getResource().deleteMarkers(markertype, true,
- IResource.DEPTH_INFINITE);
- }
- }
- } catch (CoreException e) {
- }
- }
- });
+ for (IMarker m : marker) {
+ if (m.exists()) {
+ if (m.getAttribute("cause", -1) == cause)
+ m.delete();
+ if (cause == -1)
+ m.getResource().deleteMarkers(markertype, true,
+ IResource.DEPTH_INFINITE);
+ }
+ }
+ } catch (CoreException e) {
+ }
+ }
+ });
}
private void rebuild() {
- final IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ final IWorkspace workspace = ResourcesPlugin.getWorkspace();
- new Job("Audit source files") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- for (IResource res : workspace.getRoot().members()) {
- final IProject p = (IProject) res;
- try {
- p.build(I18nBuilder.FULL_BUILD,
- I18nBuilder.BUILDER_ID, null, monitor);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
- } catch (CoreException e) {
- Logger.logError(e);
- }
- return Status.OK_STATUS;
- }
+ new Job("Audit source files") {
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ try {
+ for (IResource res : workspace.getRoot().members()) {
+ final IProject p = (IProject) res;
+ try {
+ p.build(I18nBuilder.FULL_BUILD,
+ I18nBuilder.BUILDER_ID, null, monitor);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ return Status.OK_STATUS;
+ }
- }.schedule();
+ }.schedule();
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ExtensionManager.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ExtensionManager.java
index 0b1cc8c..59f277b 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ExtensionManager.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ExtensionManager.java
@@ -38,43 +38,43 @@
private static Set<String> supportedFileEndings = new HashSet<String>();
public static List<I18nAuditor> getRegisteredI18nAuditors() {
- if (extensions == null) {
- extensions = new ArrayList<I18nAuditor>();
+ if (extensions == null) {
+ extensions = new ArrayList<I18nAuditor>();
- // init default auditors
- extensions.add(new RBAuditor());
+ // init default auditors
+ extensions.add(new RBAuditor());
- // lookup registered auditor extensions
- IConfigurationElement[] config = Platform
- .getExtensionRegistry()
- .getConfigurationElementsFor(Activator.BUILDER_EXTENSION_ID);
+ // lookup registered auditor extensions
+ IConfigurationElement[] config = Platform
+ .getExtensionRegistry()
+ .getConfigurationElementsFor(Activator.BUILDER_EXTENSION_ID);
- try {
- for (IConfigurationElement e : config) {
- addExtensionPlugIn((I18nAuditor) e
- .createExecutableExtension("class"));
- }
- } catch (CoreException ex) {
- Logger.logError(ex);
- }
- }
+ try {
+ for (IConfigurationElement e : config) {
+ addExtensionPlugIn((I18nAuditor) e
+ .createExecutableExtension("class"));
+ }
+ } catch (CoreException ex) {
+ Logger.logError(ex);
+ }
+ }
- // init builder property change listener
- if (propertyChangeListener == null) {
- propertyChangeListener = new BuilderPropertyChangeListener();
- TapiJIPreferences.addPropertyChangeListener(propertyChangeListener);
- }
+ // init builder property change listener
+ if (propertyChangeListener == null) {
+ propertyChangeListener = new BuilderPropertyChangeListener();
+ TapiJIPreferences.addPropertyChangeListener(propertyChangeListener);
+ }
- return extensions;
+ return extensions;
}
public static Set<String> getSupportedFileEndings() {
- return supportedFileEndings;
+ return supportedFileEndings;
}
private static void addExtensionPlugIn(I18nAuditor extension) {
- I18nAuditor a = extension;
- extensions.add(a);
- supportedFileEndings.addAll(Arrays.asList(a.getFileEndings()));
+ I18nAuditor a = extension;
+ extensions.add(a);
+ supportedFileEndings.addAll(Arrays.asList(a.getFileEndings()));
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java
index 40bc2f3..3ba57ee 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java
@@ -47,419 +47,419 @@
public static final String BUILDER_ID = ResourceBundleManager.BUILDER_ID;
public static I18nAuditor getI18nAuditorByContext(String contextId)
- throws NoSuchResourceAuditorException {
- for (I18nAuditor auditor : ExtensionManager.getRegisteredI18nAuditors()) {
- if (auditor.getContextId().equals(contextId)) {
- return auditor;
- }
- }
- throw new NoSuchResourceAuditorException();
+ throws NoSuchResourceAuditorException {
+ for (I18nAuditor auditor : ExtensionManager.getRegisteredI18nAuditors()) {
+ if (auditor.getContextId().equals(contextId)) {
+ return auditor;
+ }
+ }
+ throw new NoSuchResourceAuditorException();
}
public static boolean isResourceAuditable(IResource resource,
- Set<String> supportedExtensions) {
- for (String ext : supportedExtensions) {
- if (resource.getType() == IResource.FILE && !resource.isDerived()
- && resource.getFileExtension() != null
- && (resource.getFileExtension().equalsIgnoreCase(ext))) {
- return true;
- }
- }
- return false;
+ Set<String> supportedExtensions) {
+ for (String ext : supportedExtensions) {
+ if (resource.getType() == IResource.FILE && !resource.isDerived()
+ && resource.getFileExtension() != null
+ && (resource.getFileExtension().equalsIgnoreCase(ext))) {
+ return true;
+ }
+ }
+ return false;
}
@Override
protected IProject[] build(final int kind, Map args,
- IProgressMonitor monitor) throws CoreException {
+ IProgressMonitor monitor) throws CoreException {
- ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
- @Override
- public void run(IProgressMonitor monitor) throws CoreException {
- if (kind == FULL_BUILD) {
- fullBuild(monitor);
- } else {
- // only perform audit if the resource delta is not empty
- IResourceDelta resDelta = getDelta(getProject());
+ ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
+ @Override
+ public void run(IProgressMonitor monitor) throws CoreException {
+ if (kind == FULL_BUILD) {
+ fullBuild(monitor);
+ } else {
+ // only perform audit if the resource delta is not empty
+ IResourceDelta resDelta = getDelta(getProject());
- if (resDelta == null) {
- return;
- }
+ if (resDelta == null) {
+ return;
+ }
- if (resDelta.getAffectedChildren() == null) {
- return;
- }
+ if (resDelta.getAffectedChildren() == null) {
+ return;
+ }
- incrementalBuild(monitor, resDelta);
- }
- }
- }, monitor);
+ incrementalBuild(monitor, resDelta);
+ }
+ }
+ }, monitor);
- return null;
+ return null;
}
private void incrementalBuild(IProgressMonitor monitor,
- IResourceDelta resDelta) throws CoreException {
- try {
- // inspect resource delta
- ResourceFinder csrav = new ResourceFinder(
- ExtensionManager.getSupportedFileEndings());
- resDelta.accept(csrav);
- auditResources(csrav.getResources(), monitor, getProject());
- } catch (CoreException e) {
- Logger.logError(e);
- }
+ IResourceDelta resDelta) throws CoreException {
+ try {
+ // inspect resource delta
+ ResourceFinder csrav = new ResourceFinder(
+ ExtensionManager.getSupportedFileEndings());
+ resDelta.accept(csrav);
+ auditResources(csrav.getResources(), monitor, getProject());
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
}
public void buildResource(IResource resource, IProgressMonitor monitor) {
- if (isResourceAuditable(resource,
- ExtensionManager.getSupportedFileEndings())) {
- List<IResource> resources = new ArrayList<IResource>();
- resources.add(resource);
- // TODO: create instance of progressmonitor and hand it over to
- // auditResources
- try {
- auditResources(resources, monitor, resource.getProject());
- } catch (Exception e) {
- Logger.logError(e);
- }
- }
+ if (isResourceAuditable(resource,
+ ExtensionManager.getSupportedFileEndings())) {
+ List<IResource> resources = new ArrayList<IResource>();
+ resources.add(resource);
+ // TODO: create instance of progressmonitor and hand it over to
+ // auditResources
+ try {
+ auditResources(resources, monitor, resource.getProject());
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+ }
}
public void buildProject(IProgressMonitor monitor, IProject proj) {
- try {
- ResourceFinder csrav = new ResourceFinder(
- ExtensionManager.getSupportedFileEndings());
- proj.accept(csrav);
- auditResources(csrav.getResources(), monitor, proj);
- } catch (CoreException e) {
- Logger.logError(e);
- }
+ try {
+ ResourceFinder csrav = new ResourceFinder(
+ ExtensionManager.getSupportedFileEndings());
+ proj.accept(csrav);
+ auditResources(csrav.getResources(), monitor, proj);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
}
private void fullBuild(IProgressMonitor monitor) {
- buildProject(monitor, getProject());
+ buildProject(monitor, getProject());
}
private void auditResources(List<IResource> resources,
- IProgressMonitor monitor, IProject project) {
- IConfiguration configuration = ConfigurationManager.getInstance()
- .getConfiguration();
+ IProgressMonitor monitor, IProject project) {
+ IConfiguration configuration = ConfigurationManager.getInstance()
+ .getConfiguration();
- int work = resources.size();
- int actWork = 0;
- if (monitor == null) {
- monitor = new NullProgressMonitor();
- }
+ int work = resources.size();
+ int actWork = 0;
+ if (monitor == null) {
+ monitor = new NullProgressMonitor();
+ }
- monitor.beginTask(
- "Audit resource file for Internationalization problems", work);
+ monitor.beginTask(
+ "Audit resource file for Internationalization problems", work);
- for (IResource resource : resources) {
- monitor.subTask("'" + resource.getFullPath().toOSString() + "'");
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
+ for (IResource resource : resources) {
+ monitor.subTask("'" + resource.getFullPath().toOSString() + "'");
+ if (monitor.isCanceled()) {
+ throw new OperationCanceledException();
+ }
- if (!EditorUtils.deleteAuditMarkersForResource(resource)) {
- continue;
- }
+ if (!EditorUtils.deleteAuditMarkersForResource(resource)) {
+ continue;
+ }
- if (ResourceBundleManager.isResourceExcluded(resource)) {
- continue;
- }
+ if (ResourceBundleManager.isResourceExcluded(resource)) {
+ continue;
+ }
- if (!resource.exists()) {
- continue;
- }
+ if (!resource.exists()) {
+ continue;
+ }
- for (I18nAuditor ra : ExtensionManager.getRegisteredI18nAuditors()) {
- if (ra instanceof I18nResourceAuditor
- && !(configuration.getAuditResource())) {
- continue;
- }
- if (ra instanceof I18nRBAuditor
- && !(configuration.getAuditRb())) {
- continue;
- }
+ for (I18nAuditor ra : ExtensionManager.getRegisteredI18nAuditors()) {
+ if (ra instanceof I18nResourceAuditor
+ && !(configuration.getAuditResource())) {
+ continue;
+ }
+ if (ra instanceof I18nRBAuditor
+ && !(configuration.getAuditRb())) {
+ continue;
+ }
- try {
- if (monitor.isCanceled()) {
- monitor.done();
- break;
- }
+ try {
+ if (monitor.isCanceled()) {
+ monitor.done();
+ break;
+ }
- if (ra.isResourceOfType(resource)) {
- ra.audit(resource);
- }
- } catch (Exception e) {
- Logger.logError(
- "Error during auditing '" + resource.getFullPath()
- + "'", e);
- }
- }
+ if (ra.isResourceOfType(resource)) {
+ ra.audit(resource);
+ }
+ } catch (Exception e) {
+ Logger.logError(
+ "Error during auditing '" + resource.getFullPath()
+ + "'", e);
+ }
+ }
- if (monitor != null) {
- monitor.worked(1);
- }
- }
+ if (monitor != null) {
+ monitor.worked(1);
+ }
+ }
- for (I18nAuditor a : ExtensionManager.getRegisteredI18nAuditors()) {
- if (a instanceof I18nResourceAuditor) {
- handleI18NAuditorMarkers((I18nResourceAuditor) a);
- }
- if (a instanceof I18nRBAuditor) {
- handleI18NAuditorMarkers((I18nRBAuditor) a);
- ((I18nRBAuditor) a).resetProblems();
- }
- }
+ for (I18nAuditor a : ExtensionManager.getRegisteredI18nAuditors()) {
+ if (a instanceof I18nResourceAuditor) {
+ handleI18NAuditorMarkers((I18nResourceAuditor) a);
+ }
+ if (a instanceof I18nRBAuditor) {
+ handleI18NAuditorMarkers((I18nRBAuditor) a);
+ ((I18nRBAuditor) a).resetProblems();
+ }
+ }
- monitor.done();
+ monitor.done();
}
private void handleI18NAuditorMarkers(I18nResourceAuditor ra) {
- try {
- for (ILocation problem : ra.getConstantStringLiterals()) {
- EditorUtils
- .reportToMarker(
- org.eclipse.babel.tapiji.tools.core.util.EditorUtils
- .getFormattedMessage(
- org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_NON_LOCALIZED_LITERAL,
- new String[] { problem
- .getLiteral() }),
- problem,
- IMarkerConstants.CAUSE_CONSTANT_LITERAL, "",
- (ILocation) problem.getData(), ra
- .getContextId());
- }
+ try {
+ for (ILocation problem : ra.getConstantStringLiterals()) {
+ EditorUtils
+ .reportToMarker(
+ org.eclipse.babel.tapiji.tools.core.util.EditorUtils
+ .getFormattedMessage(
+ org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_NON_LOCALIZED_LITERAL,
+ new String[] { problem
+ .getLiteral() }),
+ problem,
+ IMarkerConstants.CAUSE_CONSTANT_LITERAL, "",
+ (ILocation) problem.getData(), ra
+ .getContextId());
+ }
- // Report all broken Resource-Bundle references
- for (ILocation brokenLiteral : ra.getBrokenResourceReferences()) {
- EditorUtils
- .reportToMarker(
- org.eclipse.babel.tapiji.tools.core.util.EditorUtils
- .getFormattedMessage(
- org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_BROKEN_RESOURCE_REFERENCE,
- new String[] {
- brokenLiteral
- .getLiteral(),
- ((ILocation) brokenLiteral
- .getData())
- .getLiteral() }),
- brokenLiteral,
- IMarkerConstants.CAUSE_BROKEN_REFERENCE,
- brokenLiteral.getLiteral(),
- (ILocation) brokenLiteral.getData(), ra
- .getContextId());
- }
+ // Report all broken Resource-Bundle references
+ for (ILocation brokenLiteral : ra.getBrokenResourceReferences()) {
+ EditorUtils
+ .reportToMarker(
+ org.eclipse.babel.tapiji.tools.core.util.EditorUtils
+ .getFormattedMessage(
+ org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_BROKEN_RESOURCE_REFERENCE,
+ new String[] {
+ brokenLiteral
+ .getLiteral(),
+ ((ILocation) brokenLiteral
+ .getData())
+ .getLiteral() }),
+ brokenLiteral,
+ IMarkerConstants.CAUSE_BROKEN_REFERENCE,
+ brokenLiteral.getLiteral(),
+ (ILocation) brokenLiteral.getData(), ra
+ .getContextId());
+ }
- // Report all broken definitions to Resource-Bundle
- // references
- for (ILocation brokenLiteral : ra.getBrokenBundleReferences()) {
- EditorUtils
- .reportToMarker(
- org.eclipse.babel.tapiji.tools.core.util.EditorUtils
- .getFormattedMessage(
- org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE,
- new String[] { brokenLiteral
- .getLiteral() }),
- brokenLiteral,
- IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE,
- brokenLiteral.getLiteral(),
- (ILocation) brokenLiteral.getData(), ra
- .getContextId());
- }
- } catch (Exception e) {
- Logger.logError(
- "Exception during reporting of Internationalization errors",
- e);
- }
+ // Report all broken definitions to Resource-Bundle
+ // references
+ for (ILocation brokenLiteral : ra.getBrokenBundleReferences()) {
+ EditorUtils
+ .reportToMarker(
+ org.eclipse.babel.tapiji.tools.core.util.EditorUtils
+ .getFormattedMessage(
+ org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE,
+ new String[] { brokenLiteral
+ .getLiteral() }),
+ brokenLiteral,
+ IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE,
+ brokenLiteral.getLiteral(),
+ (ILocation) brokenLiteral.getData(), ra
+ .getContextId());
+ }
+ } catch (Exception e) {
+ Logger.logError(
+ "Exception during reporting of Internationalization errors",
+ e);
+ }
}
private void handleI18NAuditorMarkers(I18nRBAuditor ra) {
- IConfiguration configuration = ConfigurationManager.getInstance()
- .getConfiguration();
- try {
- // Report all unspecified keys
- if (configuration.getAuditMissingValue()) {
- for (ILocation problem : ra.getUnspecifiedKeyReferences()) {
- EditorUtils
- .reportToRBMarker(
- org.eclipse.babel.tapiji.tools.core.util.EditorUtils
- .getFormattedMessage(
- org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_UNSPECIFIED_KEYS,
- new String[] {
- problem.getLiteral(),
- problem.getFile()
- .getName() }),
- problem,
- IMarkerConstants.CAUSE_UNSPEZIFIED_KEY,
- problem.getLiteral(), "",
- (ILocation) problem.getData(), ra
- .getContextId());
- }
- }
+ IConfiguration configuration = ConfigurationManager.getInstance()
+ .getConfiguration();
+ try {
+ // Report all unspecified keys
+ if (configuration.getAuditMissingValue()) {
+ for (ILocation problem : ra.getUnspecifiedKeyReferences()) {
+ EditorUtils
+ .reportToRBMarker(
+ org.eclipse.babel.tapiji.tools.core.util.EditorUtils
+ .getFormattedMessage(
+ org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_UNSPECIFIED_KEYS,
+ new String[] {
+ problem.getLiteral(),
+ problem.getFile()
+ .getName() }),
+ problem,
+ IMarkerConstants.CAUSE_UNSPEZIFIED_KEY,
+ problem.getLiteral(), "",
+ (ILocation) problem.getData(), ra
+ .getContextId());
+ }
+ }
- // Report all same values
- if (configuration.getAuditSameValue()) {
- Map<ILocation, ILocation> sameValues = ra
- .getSameValuesReferences();
- for (ILocation problem : sameValues.keySet()) {
- EditorUtils
- .reportToRBMarker(
- org.eclipse.babel.tapiji.tools.core.util.EditorUtils
- .getFormattedMessage(
- org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_SAME_VALUE,
- new String[] {
- problem.getFile()
- .getName(),
- sameValues
- .get(problem)
- .getFile()
- .getName(),
- problem.getLiteral() }),
- problem,
- IMarkerConstants.CAUSE_SAME_VALUE,
- problem.getLiteral(),
- sameValues.get(problem).getFile().getName(),
- (ILocation) problem.getData(), ra
- .getContextId());
- }
- }
- // Report all missing languages
- if (configuration.getAuditMissingLanguage()) {
- for (ILocation problem : ra.getMissingLanguageReferences()) {
- EditorUtils
- .reportToRBMarker(
- org.eclipse.babel.tapiji.tools.core.util.EditorUtils
- .getFormattedMessage(
- org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_MISSING_LANGUAGE,
- new String[] {
- RBFileUtils
- .getCorrespondingResourceBundleId(problem
- .getFile()),
- problem.getLiteral() }),
- problem,
- IMarkerConstants.CAUSE_MISSING_LANGUAGE,
- problem.getLiteral(), "",
- (ILocation) problem.getData(), ra
- .getContextId());
- }
- }
- } catch (Exception e) {
- Logger.logError(
- "Exception during reporting of Internationalization errors",
- e);
- }
+ // Report all same values
+ if (configuration.getAuditSameValue()) {
+ Map<ILocation, ILocation> sameValues = ra
+ .getSameValuesReferences();
+ for (ILocation problem : sameValues.keySet()) {
+ EditorUtils
+ .reportToRBMarker(
+ org.eclipse.babel.tapiji.tools.core.util.EditorUtils
+ .getFormattedMessage(
+ org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_SAME_VALUE,
+ new String[] {
+ problem.getFile()
+ .getName(),
+ sameValues
+ .get(problem)
+ .getFile()
+ .getName(),
+ problem.getLiteral() }),
+ problem,
+ IMarkerConstants.CAUSE_SAME_VALUE,
+ problem.getLiteral(),
+ sameValues.get(problem).getFile().getName(),
+ (ILocation) problem.getData(), ra
+ .getContextId());
+ }
+ }
+ // Report all missing languages
+ if (configuration.getAuditMissingLanguage()) {
+ for (ILocation problem : ra.getMissingLanguageReferences()) {
+ EditorUtils
+ .reportToRBMarker(
+ org.eclipse.babel.tapiji.tools.core.util.EditorUtils
+ .getFormattedMessage(
+ org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_MISSING_LANGUAGE,
+ new String[] {
+ RBFileUtils
+ .getCorrespondingResourceBundleId(problem
+ .getFile()),
+ problem.getLiteral() }),
+ problem,
+ IMarkerConstants.CAUSE_MISSING_LANGUAGE,
+ problem.getLiteral(), "",
+ (ILocation) problem.getData(), ra
+ .getContextId());
+ }
+ }
+ } catch (Exception e) {
+ Logger.logError(
+ "Exception during reporting of Internationalization errors",
+ e);
+ }
}
@SuppressWarnings("unused")
private void setProgress(IProgressMonitor monitor, int progress)
- throws InterruptedException {
- monitor.worked(progress);
+ throws InterruptedException {
+ monitor.worked(progress);
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
+ if (monitor.isCanceled()) {
+ throw new OperationCanceledException();
+ }
- if (isInterrupted()) {
- throw new InterruptedException();
- }
+ if (isInterrupted()) {
+ throw new InterruptedException();
+ }
}
@Override
protected void clean(IProgressMonitor monitor) throws CoreException {
- // TODO Auto-generated method stub
- super.clean(monitor);
+ // TODO Auto-generated method stub
+ super.clean(monitor);
}
public static void addBuilderToProject(IProject project) {
- Logger.logInfo("Internationalization-Builder registered for '"
- + project.getName() + "'");
+ Logger.logInfo("Internationalization-Builder registered for '"
+ + project.getName() + "'");
- // Only for open projects
- if (!project.isOpen()) {
- return;
- }
+ // Only for open projects
+ if (!project.isOpen()) {
+ return;
+ }
- IProjectDescription description = null;
- try {
- description = project.getDescription();
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
+ IProjectDescription description = null;
+ try {
+ description = project.getDescription();
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
- // Check if the builder is already associated to the specified project
- ICommand[] commands = description.getBuildSpec();
- for (ICommand command : commands) {
- if (command.getBuilderName().equals(BUILDER_ID)) {
- return;
- }
- }
+ // Check if the builder is already associated to the specified project
+ ICommand[] commands = description.getBuildSpec();
+ for (ICommand command : commands) {
+ if (command.getBuilderName().equals(BUILDER_ID)) {
+ return;
+ }
+ }
- // Associate the builder with the project
- ICommand builderCmd = description.newCommand();
- builderCmd.setBuilderName(BUILDER_ID);
- List<ICommand> newCommands = new ArrayList<ICommand>();
- newCommands.addAll(Arrays.asList(commands));
- newCommands.add(builderCmd);
- description.setBuildSpec(newCommands.toArray(new ICommand[newCommands
- .size()]));
+ // Associate the builder with the project
+ ICommand builderCmd = description.newCommand();
+ builderCmd.setBuilderName(BUILDER_ID);
+ List<ICommand> newCommands = new ArrayList<ICommand>();
+ newCommands.addAll(Arrays.asList(commands));
+ newCommands.add(builderCmd);
+ description.setBuildSpec(newCommands.toArray(new ICommand[newCommands
+ .size()]));
- try {
- project.setDescription(description, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
+ try {
+ project.setDescription(description, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
}
public static void removeBuilderFromProject(IProject project) {
- // Only for open projects
- if (!project.isOpen()) {
- return;
- }
+ // Only for open projects
+ if (!project.isOpen()) {
+ return;
+ }
- try {
- project.deleteMarkers(EditorUtils.MARKER_ID, false,
- IResource.DEPTH_INFINITE);
- project.deleteMarkers(EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
- } catch (CoreException e1) {
- Logger.logError(e1);
- }
+ try {
+ project.deleteMarkers(EditorUtils.MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ project.deleteMarkers(EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ } catch (CoreException e1) {
+ Logger.logError(e1);
+ }
- IProjectDescription description = null;
- try {
- description = project.getDescription();
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
+ IProjectDescription description = null;
+ try {
+ description = project.getDescription();
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
- // remove builder from project
- int idx = -1;
- ICommand[] commands = description.getBuildSpec();
- for (int i = 0; i < commands.length; i++) {
- if (commands[i].getBuilderName().equals(BUILDER_ID)) {
- idx = i;
- break;
- }
- }
- if (idx == -1) {
- return;
- }
+ // remove builder from project
+ int idx = -1;
+ ICommand[] commands = description.getBuildSpec();
+ for (int i = 0; i < commands.length; i++) {
+ if (commands[i].getBuilderName().equals(BUILDER_ID)) {
+ idx = i;
+ break;
+ }
+ }
+ if (idx == -1) {
+ return;
+ }
- List<ICommand> newCommands = new ArrayList<ICommand>();
- newCommands.addAll(Arrays.asList(commands));
- newCommands.remove(idx);
- description.setBuildSpec(newCommands.toArray(new ICommand[newCommands
- .size()]));
+ List<ICommand> newCommands = new ArrayList<ICommand>();
+ newCommands.addAll(Arrays.asList(commands));
+ newCommands.remove(idx);
+ description.setBuildSpec(newCommands.toArray(new ICommand[newCommands
+ .size()]));
- try {
- project.setDescription(description, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
+ try {
+ project.setDescription(description, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/InternationalizationNature.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/InternationalizationNature.java
index 21f7841..7e9fbea 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/InternationalizationNature.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/InternationalizationNature.java
@@ -33,110 +33,110 @@
@Override
public void configure() throws CoreException {
- I18nBuilder.addBuilderToProject(project);
- new Job("Audit source files") {
+ I18nBuilder.addBuilderToProject(project);
+ new Job("Audit source files") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- project.build(I18nBuilder.FULL_BUILD,
- I18nBuilder.BUILDER_ID, null, monitor);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- return Status.OK_STATUS;
- }
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ try {
+ project.build(I18nBuilder.FULL_BUILD,
+ I18nBuilder.BUILDER_ID, null, monitor);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ return Status.OK_STATUS;
+ }
- }.schedule();
+ }.schedule();
}
@Override
public void deconfigure() throws CoreException {
- I18nBuilder.removeBuilderFromProject(project);
+ I18nBuilder.removeBuilderFromProject(project);
}
@Override
public IProject getProject() {
- return project;
+ return project;
}
@Override
public void setProject(IProject project) {
- this.project = project;
+ this.project = project;
}
public static void addNature(IProject project) {
- if (!project.isOpen())
- return;
+ if (!project.isOpen())
+ return;
- IProjectDescription description = null;
+ IProjectDescription description = null;
- try {
- description = project.getDescription();
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
+ try {
+ description = project.getDescription();
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
- // Check if the project has already this nature
- List<String> newIds = new ArrayList<String>();
- newIds.addAll(Arrays.asList(description.getNatureIds()));
- int index = newIds.indexOf(NATURE_ID);
- if (index != -1)
- return;
+ // Check if the project has already this nature
+ List<String> newIds = new ArrayList<String>();
+ newIds.addAll(Arrays.asList(description.getNatureIds()));
+ int index = newIds.indexOf(NATURE_ID);
+ if (index != -1)
+ return;
- // Add the nature
- newIds.add(NATURE_ID);
- description.setNatureIds(newIds.toArray(new String[newIds.size()]));
+ // Add the nature
+ newIds.add(NATURE_ID);
+ description.setNatureIds(newIds.toArray(new String[newIds.size()]));
- try {
- project.setDescription(description, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
+ try {
+ project.setDescription(description, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
}
public static boolean supportsNature(IProject project) {
- return project.isOpen();
+ return project.isOpen();
}
public static boolean hasNature(IProject project) {
- try {
- return project.isOpen() && project.hasNature(NATURE_ID);
- } catch (CoreException e) {
- Logger.logError(e);
- return false;
- }
+ try {
+ return project.isOpen() && project.hasNature(NATURE_ID);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return false;
+ }
}
public static void removeNature(IProject project) {
- if (!project.isOpen())
- return;
+ if (!project.isOpen())
+ return;
- IProjectDescription description = null;
+ IProjectDescription description = null;
- try {
- description = project.getDescription();
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
+ try {
+ description = project.getDescription();
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
- // Check if the project has already this nature
- List<String> newIds = new ArrayList<String>();
- newIds.addAll(Arrays.asList(description.getNatureIds()));
- int index = newIds.indexOf(NATURE_ID);
- if (index == -1)
- return;
+ // Check if the project has already this nature
+ List<String> newIds = new ArrayList<String>();
+ newIds.addAll(Arrays.asList(description.getNatureIds()));
+ int index = newIds.indexOf(NATURE_ID);
+ if (index == -1)
+ return;
- // remove the nature
- newIds.remove(NATURE_ID);
- description.setNatureIds(newIds.toArray(new String[newIds.size()]));
+ // remove the nature
+ newIds.remove(NATURE_ID);
+ description.setNatureIds(newIds.toArray(new String[newIds.size()]));
- try {
- project.setDescription(description, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
+ try {
+ project.setDescription(description, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ViolationResolutionGenerator.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ViolationResolutionGenerator.java
index da1fad4..11f84bf 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ViolationResolutionGenerator.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ViolationResolutionGenerator.java
@@ -20,32 +20,32 @@
import org.eclipse.ui.IMarkerResolutionGenerator2;
public class ViolationResolutionGenerator implements
- IMarkerResolutionGenerator2 {
+ IMarkerResolutionGenerator2 {
@Override
public boolean hasResolutions(IMarker marker) {
- return true;
+ return true;
}
@Override
public IMarkerResolution[] getResolutions(IMarker marker) {
- EditorUtils.updateMarker(marker);
+ EditorUtils.updateMarker(marker);
- String contextId = marker.getAttribute("context", "");
+ String contextId = marker.getAttribute("context", "");
- // find resolution generator for the given context
- try {
- I18nAuditor auditor = I18nBuilder
- .getI18nAuditorByContext(contextId);
- List<IMarkerResolution> resolutions = auditor
- .getMarkerResolutions(marker);
- return resolutions
- .toArray(new IMarkerResolution[resolutions.size()]);
- } catch (NoSuchResourceAuditorException e) {
- }
+ // find resolution generator for the given context
+ try {
+ I18nAuditor auditor = I18nBuilder
+ .getI18nAuditorByContext(contextId);
+ List<IMarkerResolution> resolutions = auditor
+ .getMarkerResolutions(marker);
+ return resolutions
+ .toArray(new IMarkerResolution[resolutions.size()]);
+ } catch (NoSuchResourceAuditorException e) {
+ }
- return new IMarkerResolution[0];
+ return new IMarkerResolution[0];
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java
index bf11968..5697477 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java
@@ -31,85 +31,85 @@
import org.eclipse.swt.graphics.Image;
public class ExcludedResource implements ILabelDecorator,
- IResourceExclusionListener {
+ IResourceExclusionListener {
private static final String ENTRY_SUFFIX = "[no i18n]";
private static final Image OVERLAY_IMAGE_ON = ImageUtils
- .getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_ON);
+ .getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_ON);
private static final Image OVERLAY_IMAGE_OFF = ImageUtils
- .getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF);
+ .getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF);
private final List<ILabelProviderListener> label_provider_listener = new ArrayList<ILabelProviderListener>();
public boolean decorate(Object element) {
- boolean needsDecoration = false;
- if (element instanceof IFolder || element instanceof IFile) {
- IResource resource = (IResource) element;
- if (!InternationalizationNature.hasNature(resource.getProject()))
- return false;
- try {
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(resource.getProject());
- if (!manager.isResourceExclusionListenerRegistered(this))
- manager.registerResourceExclusionListener(this);
- if (ResourceBundleManager.isResourceExcluded(resource)) {
- needsDecoration = true;
- }
- } catch (Exception e) {
- Logger.logError(e);
- }
- }
- return needsDecoration;
+ boolean needsDecoration = false;
+ if (element instanceof IFolder || element instanceof IFile) {
+ IResource resource = (IResource) element;
+ if (!InternationalizationNature.hasNature(resource.getProject()))
+ return false;
+ try {
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(resource.getProject());
+ if (!manager.isResourceExclusionListenerRegistered(this))
+ manager.registerResourceExclusionListener(this);
+ if (ResourceBundleManager.isResourceExcluded(resource)) {
+ needsDecoration = true;
+ }
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+ }
+ return needsDecoration;
}
@Override
public void addListener(ILabelProviderListener listener) {
- label_provider_listener.add(listener);
+ label_provider_listener.add(listener);
}
@Override
public void dispose() {
- ResourceBundleManager
- .unregisterResourceExclusionListenerFromAllManagers(this);
+ ResourceBundleManager
+ .unregisterResourceExclusionListenerFromAllManagers(this);
}
@Override
public boolean isLabelProperty(Object element, String property) {
- return false;
+ return false;
}
@Override
public void removeListener(ILabelProviderListener listener) {
- label_provider_listener.remove(listener);
+ label_provider_listener.remove(listener);
}
@Override
public void exclusionChanged(ResourceExclusionEvent event) {
- LabelProviderChangedEvent labelEvent = new LabelProviderChangedEvent(
- this, event.getChangedResources().toArray());
- for (ILabelProviderListener l : label_provider_listener)
- l.labelProviderChanged(labelEvent);
+ LabelProviderChangedEvent labelEvent = new LabelProviderChangedEvent(
+ this, event.getChangedResources().toArray());
+ for (ILabelProviderListener l : label_provider_listener)
+ l.labelProviderChanged(labelEvent);
}
@Override
public Image decorateImage(Image image, Object element) {
- if (decorate(element)) {
- DecorationOverlayIcon overlayIcon = new DecorationOverlayIcon(
- image,
- Activator
- .getImageDescriptor(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF),
- IDecoration.TOP_RIGHT);
- return overlayIcon.createImage();
- } else {
- return image;
- }
+ if (decorate(element)) {
+ DecorationOverlayIcon overlayIcon = new DecorationOverlayIcon(
+ image,
+ Activator
+ .getImageDescriptor(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF),
+ IDecoration.TOP_RIGHT);
+ return overlayIcon.createImage();
+ } else {
+ return image;
+ }
}
@Override
public String decorateText(String text, Object element) {
- if (decorate(element)) {
- return text + " " + ENTRY_SUFFIX;
- } else
- return text;
+ if (decorate(element)) {
+ return text + " " + ENTRY_SUFFIX;
+ } else
+ return text;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java
index c592586..1cf552c 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java
@@ -47,122 +47,122 @@
private Text variant;
public AddLanguageDialoge(Shell parentShell) {
- super(parentShell);
- shell = parentShell;
+ super(parentShell);
+ shell = parentShell;
}
@Override
protected Control createDialogArea(Composite parent) {
- Composite titelArea = new Composite(parent, SWT.NO_BACKGROUND);
- Composite dialogArea = (Composite) super.createDialogArea(parent);
- GridLayout layout = new GridLayout(1, true);
- dialogArea.setLayout(layout);
+ Composite titelArea = new Composite(parent, SWT.NO_BACKGROUND);
+ Composite dialogArea = (Composite) super.createDialogArea(parent);
+ GridLayout layout = new GridLayout(1, true);
+ dialogArea.setLayout(layout);
- initDescription(titelArea);
- initCombo(dialogArea);
- initTextArea(dialogArea);
+ initDescription(titelArea);
+ initCombo(dialogArea);
+ initTextArea(dialogArea);
- titelArea.pack();
- dialogArea.pack();
- parent.pack();
+ titelArea.pack();
+ dialogArea.pack();
+ parent.pack();
- return dialogArea;
+ return dialogArea;
}
private void initDescription(Composite titelArea) {
- titelArea.setEnabled(false);
- titelArea.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, true,
- 1, 1));
- titelArea.setLayout(new GridLayout(1, true));
- titelArea.setBackground(new Color(shell.getDisplay(), 255, 255, 255));
+ titelArea.setEnabled(false);
+ titelArea.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, true,
+ 1, 1));
+ titelArea.setLayout(new GridLayout(1, true));
+ titelArea.setBackground(new Color(shell.getDisplay(), 255, 255, 255));
- titelText = new Text(titelArea, SWT.LEFT);
- titelText.setFont(new Font(shell.getDisplay(), shell.getFont()
- .getFontData()[0].getName(), 11, SWT.BOLD));
- titelText.setText("Please, specify the desired language");
+ titelText = new Text(titelArea, SWT.LEFT);
+ titelText.setFont(new Font(shell.getDisplay(), shell.getFont()
+ .getFontData()[0].getName(), 11, SWT.BOLD));
+ titelText.setText("Please, specify the desired language");
- descriptionText = new Text(titelArea, SWT.WRAP);
- descriptionText.setLayoutData(new GridData(450, 60)); // TODO improve
- descriptionText
- .setText("Note: "
- + "In all ResourceBundles of the project/plug-in will be created a new properties-file with the basename of the ResourceBundle and the corresponding locale-extension. "
- + "If the locale is just provided of a ResourceBundle, no new file will be created.");
+ descriptionText = new Text(titelArea, SWT.WRAP);
+ descriptionText.setLayoutData(new GridData(450, 60)); // TODO improve
+ descriptionText
+ .setText("Note: "
+ + "In all ResourceBundles of the project/plug-in will be created a new properties-file with the basename of the ResourceBundle and the corresponding locale-extension. "
+ + "If the locale is just provided of a ResourceBundle, no new file will be created.");
}
private void initCombo(Composite dialogArea) {
- cmbLanguage = new Combo(dialogArea, SWT.DROP_DOWN);
- cmbLanguage.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true,
- true, 1, 1));
+ cmbLanguage = new Combo(dialogArea, SWT.DROP_DOWN);
+ cmbLanguage.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true,
+ true, 1, 1));
- final Locale[] locales = Locale.getAvailableLocales();
- final Set<Locale> localeSet = new HashSet<Locale>();
- List<String> localeNames = new LinkedList<String>();
+ final Locale[] locales = Locale.getAvailableLocales();
+ final Set<Locale> localeSet = new HashSet<Locale>();
+ List<String> localeNames = new LinkedList<String>();
- for (Locale l : locales) {
- localeNames.add(l.getDisplayName());
- localeSet.add(l);
- }
+ for (Locale l : locales) {
+ localeNames.add(l.getDisplayName());
+ localeSet.add(l);
+ }
- Collections.sort(localeNames);
+ Collections.sort(localeNames);
- String[] s = new String[localeNames.size()];
- cmbLanguage.setItems(localeNames.toArray(s));
- cmbLanguage.add(ResourceBundleManager.defaultLocaleTag, 0);
+ String[] s = new String[localeNames.size()];
+ cmbLanguage.setItems(localeNames.toArray(s));
+ cmbLanguage.add(ResourceBundleManager.defaultLocaleTag, 0);
- cmbLanguage.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- int selectIndex = ((Combo) e.getSource()).getSelectionIndex();
- if (!cmbLanguage.getItem(selectIndex).equals(
- ResourceBundleManager.defaultLocaleTag)) {
- Locale l = LocaleUtils.getLocaleByDisplayName(localeSet,
- cmbLanguage.getItem(selectIndex));
+ cmbLanguage.addSelectionListener(new SelectionListener() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ int selectIndex = ((Combo) e.getSource()).getSelectionIndex();
+ if (!cmbLanguage.getItem(selectIndex).equals(
+ ResourceBundleManager.defaultLocaleTag)) {
+ Locale l = LocaleUtils.getLocaleByDisplayName(localeSet,
+ cmbLanguage.getItem(selectIndex));
- language.setText(l.getLanguage());
- country.setText(l.getCountry());
- variant.setText(l.getVariant());
- } else {
- language.setText("");
- country.setText("");
- variant.setText("");
- }
- }
+ language.setText(l.getLanguage());
+ country.setText(l.getCountry());
+ variant.setText(l.getVariant());
+ } else {
+ language.setText("");
+ country.setText("");
+ variant.setText("");
+ }
+ }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- // TODO Auto-generated method stub
- }
- });
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ // TODO Auto-generated method stub
+ }
+ });
}
private void initTextArea(Composite dialogArea) {
- final Group group = new Group(dialogArea, SWT.SHADOW_ETCHED_IN);
- group.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1,
- 1));
- group.setLayout(new GridLayout(3, true));
- group.setText("Locale");
+ final Group group = new Group(dialogArea, SWT.SHADOW_ETCHED_IN);
+ group.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1,
+ 1));
+ group.setLayout(new GridLayout(3, true));
+ group.setText("Locale");
- Label languageLabel = new Label(group, SWT.SINGLE);
- languageLabel.setText("Language");
- Label countryLabel = new Label(group, SWT.SINGLE);
- countryLabel.setText("Country");
- Label variantLabel = new Label(group, SWT.SINGLE);
- variantLabel.setText("Variant");
+ Label languageLabel = new Label(group, SWT.SINGLE);
+ languageLabel.setText("Language");
+ Label countryLabel = new Label(group, SWT.SINGLE);
+ countryLabel.setText("Country");
+ Label variantLabel = new Label(group, SWT.SINGLE);
+ variantLabel.setText("Variant");
- language = new Text(group, SWT.SINGLE);
- country = new Text(group, SWT.SINGLE);
- variant = new Text(group, SWT.SINGLE);
+ language = new Text(group, SWT.SINGLE);
+ country = new Text(group, SWT.SINGLE);
+ variant = new Text(group, SWT.SINGLE);
}
@Override
protected void okPressed() {
- locale = new Locale(language.getText(), country.getText(),
- variant.getText());
+ locale = new Locale(language.getText(), country.getText(),
+ variant.getText());
- super.okPressed();
+ super.okPressed();
}
public Locale getSelectedLanguage() {
- return locale;
+ return locale;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java
index cda61c0..17f050a 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java
@@ -25,43 +25,43 @@
private Text patternText;
public CreatePatternDialoge(Shell shell) {
- this(shell, "");
+ this(shell, "");
}
public CreatePatternDialoge(Shell shell, String pattern) {
- super(shell);
- this.pattern = pattern;
- // setShellStyle(SWT.RESIZE);
+ super(shell);
+ this.pattern = pattern;
+ // setShellStyle(SWT.RESIZE);
}
@Override
protected Control createDialogArea(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(1, true));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
+ Composite composite = new Composite(parent, SWT.NONE);
+ composite.setLayout(new GridLayout(1, true));
+ composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
- Label descriptionLabel = new Label(composite, SWT.NONE);
- descriptionLabel.setText("Enter a regular expression:");
+ Label descriptionLabel = new Label(composite, SWT.NONE);
+ descriptionLabel.setText("Enter a regular expression:");
- patternText = new Text(composite, SWT.WRAP | SWT.MULTI);
- GridData gData = new GridData(SWT.FILL, SWT.FILL, true, false);
- gData.widthHint = 400;
- gData.heightHint = 60;
- patternText.setLayoutData(gData);
- patternText.setText(pattern);
+ patternText = new Text(composite, SWT.WRAP | SWT.MULTI);
+ GridData gData = new GridData(SWT.FILL, SWT.FILL, true, false);
+ gData.widthHint = 400;
+ gData.heightHint = 60;
+ patternText.setLayoutData(gData);
+ patternText.setText(pattern);
- return composite;
+ return composite;
}
@Override
protected void okPressed() {
- pattern = patternText.getText();
+ pattern = patternText.getText();
- super.okPressed();
+ super.okPressed();
}
public String getPattern() {
- return pattern;
+ return pattern;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java
index fa66c12..30d4f3f 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java
@@ -66,416 +66,416 @@
public class DialogConfiguration {
- String projectName;
+ String projectName;
- String preselectedKey;
- String preselectedMessage;
- String preselectedBundle;
- String preselectedLocale;
+ String preselectedKey;
+ String preselectedMessage;
+ String preselectedBundle;
+ String preselectedLocale;
- public String getProjectName() {
- return projectName;
- }
+ public String getProjectName() {
+ return projectName;
+ }
- public void setProjectName(String projectName) {
- this.projectName = projectName;
- }
+ public void setProjectName(String projectName) {
+ this.projectName = projectName;
+ }
- public String getPreselectedKey() {
- return preselectedKey;
- }
+ public String getPreselectedKey() {
+ return preselectedKey;
+ }
- public void setPreselectedKey(String preselectedKey) {
- this.preselectedKey = preselectedKey;
- }
+ public void setPreselectedKey(String preselectedKey) {
+ this.preselectedKey = preselectedKey;
+ }
- public String getPreselectedMessage() {
- return preselectedMessage;
- }
+ public String getPreselectedMessage() {
+ return preselectedMessage;
+ }
- public void setPreselectedMessage(String preselectedMessage) {
- this.preselectedMessage = preselectedMessage;
- }
+ public void setPreselectedMessage(String preselectedMessage) {
+ this.preselectedMessage = preselectedMessage;
+ }
- public String getPreselectedBundle() {
- return preselectedBundle;
- }
+ public String getPreselectedBundle() {
+ return preselectedBundle;
+ }
- public void setPreselectedBundle(String preselectedBundle) {
- this.preselectedBundle = preselectedBundle;
- }
+ public void setPreselectedBundle(String preselectedBundle) {
+ this.preselectedBundle = preselectedBundle;
+ }
- public String getPreselectedLocale() {
- return preselectedLocale;
- }
+ public String getPreselectedLocale() {
+ return preselectedLocale;
+ }
- public void setPreselectedLocale(String preselectedLocale) {
- this.preselectedLocale = preselectedLocale;
- }
+ public void setPreselectedLocale(String preselectedLocale) {
+ this.preselectedLocale = preselectedLocale;
+ }
}
public CreateResourceBundleEntryDialog(Shell parentShell) {
- super(parentShell);
+ super(parentShell);
}
public void setDialogConfiguration(DialogConfiguration config) {
- String preselectedKey = config.getPreselectedKey();
- this.selectedKey = preselectedKey != null ? preselectedKey.trim()
- : preselectedKey;
- if ("".equals(this.selectedKey)) {
- this.selectedKey = DEFAULT_KEY;
- }
+ String preselectedKey = config.getPreselectedKey();
+ this.selectedKey = preselectedKey != null ? preselectedKey.trim()
+ : preselectedKey;
+ if ("".equals(this.selectedKey)) {
+ this.selectedKey = DEFAULT_KEY;
+ }
- this.selectedDefaultText = config.getPreselectedMessage();
- this.selectedRB = config.getPreselectedBundle();
- this.selectedLocale = config.getPreselectedLocale();
- this.projectName = config.getProjectName();
+ this.selectedDefaultText = config.getPreselectedMessage();
+ this.selectedRB = config.getPreselectedBundle();
+ this.selectedLocale = config.getPreselectedLocale();
+ this.projectName = config.getProjectName();
}
public String getSelectedResourceBundle() {
- return selectedRB;
+ return selectedRB;
}
public String getSelectedKey() {
- return selectedKey;
+ return selectedKey;
}
@Override
protected Control createDialogArea(Composite parent) {
- Composite dialogArea = (Composite) super.createDialogArea(parent);
- initLayout(dialogArea);
- constructRBSection(dialogArea);
- constructDefaultSection(dialogArea);
- initContent();
- return dialogArea;
+ Composite dialogArea = (Composite) super.createDialogArea(parent);
+ initLayout(dialogArea);
+ constructRBSection(dialogArea);
+ constructDefaultSection(dialogArea);
+ initContent();
+ return dialogArea;
}
protected void initContent() {
- cmbRB.removeAll();
- int iSel = -1;
- int index = 0;
+ cmbRB.removeAll();
+ int iSel = -1;
+ int index = 0;
- Collection<String> availableBundles = ResourceBundleManager.getManager(
- projectName).getResourceBundleNames();
+ Collection<String> availableBundles = ResourceBundleManager.getManager(
+ projectName).getResourceBundleNames();
- for (String bundle : availableBundles) {
- cmbRB.add(bundle);
- if (bundle.equals(selectedRB)) {
- cmbRB.select(index);
- iSel = index;
- cmbRB.setEnabled(false);
- }
- index++;
- }
+ for (String bundle : availableBundles) {
+ cmbRB.add(bundle);
+ if (bundle.equals(selectedRB)) {
+ cmbRB.select(index);
+ iSel = index;
+ cmbRB.setEnabled(false);
+ }
+ index++;
+ }
- if (availableBundles.size() > 0 && iSel < 0) {
- cmbRB.select(0);
- selectedRB = cmbRB.getText();
- cmbRB.setEnabled(true);
- }
+ if (availableBundles.size() > 0 && iSel < 0) {
+ cmbRB.select(0);
+ selectedRB = cmbRB.getText();
+ cmbRB.setEnabled(true);
+ }
- rbModifyListener = new ModifyListener() {
+ rbModifyListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- selectedRB = cmbRB.getText();
- validate();
- }
- };
- cmbRB.removeModifyListener(rbModifyListener);
- cmbRB.addModifyListener(rbModifyListener);
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedRB = cmbRB.getText();
+ validate();
+ }
+ };
+ cmbRB.removeModifyListener(rbModifyListener);
+ cmbRB.addModifyListener(rbModifyListener);
- cmbRB.addSelectionListener(new SelectionListener() {
+ cmbRB.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- selectedLocale = "";
- updateAvailableLanguages();
- }
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ selectedLocale = "";
+ updateAvailableLanguages();
+ }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
- selectedLocale = "";
- updateAvailableLanguages();
- }
- });
- updateAvailableLanguages();
- validate();
+ selectedLocale = "";
+ updateAvailableLanguages();
+ }
+ });
+ updateAvailableLanguages();
+ validate();
}
protected void updateAvailableLanguages() {
- cmbLanguage.removeAll();
- String selectedBundle = cmbRB.getText();
+ cmbLanguage.removeAll();
+ String selectedBundle = cmbRB.getText();
- if ("".equals(selectedBundle.trim())) {
- return;
- }
+ if ("".equals(selectedBundle.trim())) {
+ return;
+ }
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(projectName);
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
- // Retrieve available locales for the selected resource-bundle
- Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
- int index = 0;
- int iSel = -1;
- for (Locale l : manager.getProvidedLocales(selectedBundle)) {
- String displayName = l == null ? ResourceBundleManager.defaultLocaleTag
- : l.getDisplayName();
- if (displayName.equals(selectedLocale))
- iSel = index;
- if (displayName.equals(""))
- displayName = ResourceBundleManager.defaultLocaleTag;
- cmbLanguage.add(displayName);
- if (index == iSel)
- cmbLanguage.select(iSel);
- index++;
- }
+ // Retrieve available locales for the selected resource-bundle
+ Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
+ int index = 0;
+ int iSel = -1;
+ for (Locale l : manager.getProvidedLocales(selectedBundle)) {
+ String displayName = l == null ? ResourceBundleManager.defaultLocaleTag
+ : l.getDisplayName();
+ if (displayName.equals(selectedLocale))
+ iSel = index;
+ if (displayName.equals(""))
+ displayName = ResourceBundleManager.defaultLocaleTag;
+ cmbLanguage.add(displayName);
+ if (index == iSel)
+ cmbLanguage.select(iSel);
+ index++;
+ }
- if (locales.size() > 0) {
- cmbLanguage.select(0);
- selectedLocale = cmbLanguage.getText();
- }
+ if (locales.size() > 0) {
+ cmbLanguage.select(0);
+ selectedLocale = cmbLanguage.getText();
+ }
- cmbLanguage.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- selectedLocale = cmbLanguage.getText();
- validate();
- }
- });
+ cmbLanguage.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedLocale = cmbLanguage.getText();
+ validate();
+ }
+ });
}
protected void initLayout(Composite parent) {
- final GridLayout layout = new GridLayout(1, true);
- parent.setLayout(layout);
+ final GridLayout layout = new GridLayout(1, true);
+ parent.setLayout(layout);
}
protected void constructRBSection(Composite parent) {
- final Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
- group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
- false, 1, 1));
- group.setText("Resource Bundle");
+ final Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
+ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
+ group.setText("Resource Bundle");
- // define grid data for this group
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = true;
- group.setLayoutData(gridData);
- group.setLayout(new GridLayout(2, false));
+ // define grid data for this group
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ group.setLayoutData(gridData);
+ group.setLayout(new GridLayout(2, false));
- final Label spacer = new Label(group, SWT.NONE | SWT.LEFT);
- spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
- false, false, 1, 1));
+ final Label spacer = new Label(group, SWT.NONE | SWT.LEFT);
+ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
+ false, false, 1, 1));
- final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT);
- infoLabel.setLayoutData(new GridData(GridData.BEGINNING,
- GridData.CENTER, false, false, 1, 1));
- infoLabel
- .setText("Specify the key of the new resource as well as the Resource-Bundle in\n"
- + "which the resource" + "should be added.\n");
+ final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT);
+ infoLabel.setLayoutData(new GridData(GridData.BEGINNING,
+ GridData.CENTER, false, false, 1, 1));
+ infoLabel
+ .setText("Specify the key of the new resource as well as the Resource-Bundle in\n"
+ + "which the resource" + "should be added.\n");
- // Schl�ssel
- final Label lblKey = new Label(group, SWT.NONE | SWT.RIGHT);
- GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER,
- false, false, 1, 1);
- lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN;
- lblKey.setLayoutData(lblKeyGrid);
- lblKey.setText("Key:");
- txtKey = new Text(group, SWT.BORDER);
- txtKey.setText(selectedKey);
- // grey ouut textfield if there already is a preset key
- txtKey.setEditable(selectedKey.trim().length() == 0
- || selectedKey.indexOf("[Platzhalter]") >= 0
- || selectedKey.equals(DEFAULT_KEY));
- txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
- false, 1, 1));
- txtKey.addModifyListener(new ModifyListener() {
+ // Schl�ssel
+ final Label lblKey = new Label(group, SWT.NONE | SWT.RIGHT);
+ GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER,
+ false, false, 1, 1);
+ lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN;
+ lblKey.setLayoutData(lblKeyGrid);
+ lblKey.setText("Key:");
+ txtKey = new Text(group, SWT.BORDER);
+ txtKey.setText(selectedKey);
+ // grey ouut textfield if there already is a preset key
+ txtKey.setEditable(selectedKey.trim().length() == 0
+ || selectedKey.indexOf("[Platzhalter]") >= 0
+ || selectedKey.equals(DEFAULT_KEY));
+ txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
+ txtKey.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- selectedKey = txtKey.getText();
- validate();
- }
- });
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedKey = txtKey.getText();
+ validate();
+ }
+ });
- // Resource-Bundle
- final Label lblRB = new Label(group, SWT.NONE);
- lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false,
- false, 1, 1));
- lblRB.setText("Resource-Bundle:");
+ // Resource-Bundle
+ final Label lblRB = new Label(group, SWT.NONE);
+ lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false,
+ false, 1, 1));
+ lblRB.setText("Resource-Bundle:");
- cmbRB = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE);
- cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
- false, 1, 1));
+ cmbRB = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE);
+ cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
}
protected void constructDefaultSection(Composite parent) {
- final Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
- group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
- true, 1, 1));
- group.setText("Default-Text");
+ final Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
+ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ true, 1, 1));
+ group.setText("Default-Text");
- // define grid data for this group
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = true;
- group.setLayoutData(gridData);
- group.setLayout(new GridLayout(2, false));
+ // define grid data for this group
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ group.setLayoutData(gridData);
+ group.setLayout(new GridLayout(2, false));
- final Label spacer = new Label(group, SWT.NONE | SWT.LEFT);
- spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
- false, false, 1, 1));
+ final Label spacer = new Label(group, SWT.NONE | SWT.LEFT);
+ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
+ false, false, 1, 1));
- final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT);
- infoLabel.setLayoutData(new GridData(GridData.BEGINNING,
- GridData.CENTER, false, false, 1, 1));
- infoLabel
- .setText("Define a default text for the specified resource. Moreover, you need to\n"
- + "select the locale for which the default text should be defined.");
+ final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT);
+ infoLabel.setLayoutData(new GridData(GridData.BEGINNING,
+ GridData.CENTER, false, false, 1, 1));
+ infoLabel
+ .setText("Define a default text for the specified resource. Moreover, you need to\n"
+ + "select the locale for which the default text should be defined.");
- // Text
- final Label lblText = new Label(group, SWT.NONE | SWT.RIGHT);
- GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER,
- false, false, 1, 1);
- lblTextGrid.heightHint = 80;
- lblTextGrid.widthHint = 100;
- lblText.setLayoutData(lblTextGrid);
- lblText.setText("Text:");
+ // Text
+ final Label lblText = new Label(group, SWT.NONE | SWT.RIGHT);
+ GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER,
+ false, false, 1, 1);
+ lblTextGrid.heightHint = 80;
+ lblTextGrid.widthHint = 100;
+ lblText.setLayoutData(lblTextGrid);
+ lblText.setText("Text:");
- txtDefaultText = new Text(group, SWT.MULTI | SWT.BORDER);
- txtDefaultText.setText(selectedDefaultText);
- txtDefaultText.setLayoutData(new GridData(GridData.FILL, GridData.FILL,
- true, true, 1, 1));
- txtDefaultText.addModifyListener(new ModifyListener() {
+ txtDefaultText = new Text(group, SWT.MULTI | SWT.BORDER);
+ txtDefaultText.setText(selectedDefaultText);
+ txtDefaultText.setLayoutData(new GridData(GridData.FILL, GridData.FILL,
+ true, true, 1, 1));
+ txtDefaultText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- selectedDefaultText = txtDefaultText.getText();
- validate();
- }
- });
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedDefaultText = txtDefaultText.getText();
+ validate();
+ }
+ });
- // Sprache
- final Label lblLanguage = new Label(group, SWT.NONE);
- lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER,
- false, false, 1, 1));
- lblLanguage.setText("Language (Country):");
+ // Sprache
+ final Label lblLanguage = new Label(group, SWT.NONE);
+ lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER,
+ false, false, 1, 1));
+ lblLanguage.setText("Language (Country):");
- cmbLanguage = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE);
- cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER,
- true, false, 1, 1));
+ cmbLanguage = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE);
+ cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER,
+ true, false, 1, 1));
}
@Override
protected void okPressed() {
- super.okPressed();
- // TODO debug
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(projectName);
- // Insert new Resource-Bundle reference
- Locale locale = LocaleUtils.getLocaleByDisplayName(
- manager.getProvidedLocales(selectedRB), selectedLocale); // new
- // Locale("");
- // //
- // retrieve
- // locale
+ super.okPressed();
+ // TODO debug
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ // Insert new Resource-Bundle reference
+ Locale locale = LocaleUtils.getLocaleByDisplayName(
+ manager.getProvidedLocales(selectedRB), selectedLocale); // new
+ // Locale("");
+ // //
+ // retrieve
+ // locale
- try {
- manager.addResourceBundleEntry(selectedRB, selectedKey, locale,
- selectedDefaultText);
- } catch (ResourceBundleException e) {
- Logger.logError(e);
- }
+ try {
+ manager.addResourceBundleEntry(selectedRB, selectedKey, locale,
+ selectedDefaultText);
+ } catch (ResourceBundleException e) {
+ Logger.logError(e);
+ }
}
@Override
protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Create Resource-Bundle entry");
+ super.configureShell(newShell);
+ newShell.setText("Create Resource-Bundle entry");
}
@Override
public void create() {
- // TODO Auto-generated method stub
- super.create();
- this.setTitle("New Resource-Bundle entry");
- this.setMessage("Please, specify details about the new Resource-Bundle entry");
+ // TODO Auto-generated method stub
+ super.create();
+ this.setTitle("New Resource-Bundle entry");
+ this.setMessage("Please, specify details about the new Resource-Bundle entry");
}
/**
* Validates all inputs of the CreateResourceBundleEntryDialog
*/
protected void validate() {
- // Check Resource-Bundle ids
- boolean keyValid = false;
- boolean keyValidChar = ResourceUtils.isValidResourceKey(selectedKey);
- boolean rbValid = false;
- boolean textValid = false;
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(projectName);
- boolean localeValid = LocaleUtils.containsLocaleByDisplayName(
- manager.getProvidedLocales(selectedRB), selectedLocale);
+ // Check Resource-Bundle ids
+ boolean keyValid = false;
+ boolean keyValidChar = ResourceUtils.isValidResourceKey(selectedKey);
+ boolean rbValid = false;
+ boolean textValid = false;
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ boolean localeValid = LocaleUtils.containsLocaleByDisplayName(
+ manager.getProvidedLocales(selectedRB), selectedLocale);
- for (String rbId : manager.getResourceBundleNames()) {
- if (rbId.equals(selectedRB)) {
- rbValid = true;
- break;
- }
- }
+ for (String rbId : manager.getResourceBundleNames()) {
+ if (rbId.equals(selectedRB)) {
+ rbValid = true;
+ break;
+ }
+ }
- if (!manager.isResourceExisting(selectedRB, selectedKey))
- keyValid = true;
+ if (!manager.isResourceExisting(selectedRB, selectedKey))
+ keyValid = true;
- if (selectedDefaultText.trim().length() > 0)
- textValid = true;
+ if (selectedDefaultText.trim().length() > 0)
+ textValid = true;
- // print Validation summary
- String errorMessage = null;
- if (selectedKey.trim().length() == 0)
- errorMessage = "No resource key specified.";
- else if (!keyValidChar)
- errorMessage = "The specified resource key contains invalid characters.";
- else if (!keyValid)
- errorMessage = "The specified resource key is already existing.";
- else if (!rbValid)
- errorMessage = "The specified Resource-Bundle does not exist.";
- else if (!localeValid)
- errorMessage = "The specified Locale does not exist for the selected Resource-Bundle.";
- else if (!textValid)
- errorMessage = "No default translation specified.";
- else {
- if (okButton != null)
- okButton.setEnabled(true);
- }
+ // print Validation summary
+ String errorMessage = null;
+ if (selectedKey.trim().length() == 0)
+ errorMessage = "No resource key specified.";
+ else if (!keyValidChar)
+ errorMessage = "The specified resource key contains invalid characters.";
+ else if (!keyValid)
+ errorMessage = "The specified resource key is already existing.";
+ else if (!rbValid)
+ errorMessage = "The specified Resource-Bundle does not exist.";
+ else if (!localeValid)
+ errorMessage = "The specified Locale does not exist for the selected Resource-Bundle.";
+ else if (!textValid)
+ errorMessage = "No default translation specified.";
+ else {
+ if (okButton != null)
+ okButton.setEnabled(true);
+ }
- setErrorMessage(errorMessage);
- if (okButton != null && errorMessage != null)
- okButton.setEnabled(false);
+ setErrorMessage(errorMessage);
+ if (okButton != null && errorMessage != null)
+ okButton.setEnabled(false);
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
- okButton = createButton(parent, OK, "Ok", true);
- okButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- // Set return code
- setReturnCode(OK);
- close();
- }
- });
+ okButton = createButton(parent, OK, "Ok", true);
+ okButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ // Set return code
+ setReturnCode(OK);
+ close();
+ }
+ });
- cancelButton = createButton(parent, CANCEL, "Cancel", false);
- cancelButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- setReturnCode(CANCEL);
- close();
- }
- });
+ cancelButton = createButton(parent, CANCEL, "Cancel", false);
+ cancelButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ setReturnCode(CANCEL);
+ close();
+ }
+ });
- okButton.setEnabled(this.getErrorMessage() == null);
- cancelButton.setEnabled(true);
+ okButton.setEnabled(this.getErrorMessage() == null);
+ cancelButton.setEnabled(true);
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java
index 14b637d..c868bc0 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java
@@ -29,96 +29,96 @@
private List<IProject> allProjects;
public FragmentProjectSelectionDialog(Shell parent, IProject hostproject,
- List<IProject> fragmentprojects) {
- super(parent);
- this.hostproject = hostproject;
- this.allProjects = new ArrayList<IProject>(fragmentprojects);
- allProjects.add(0, hostproject);
+ List<IProject> fragmentprojects) {
+ super(parent);
+ this.hostproject = hostproject;
+ this.allProjects = new ArrayList<IProject>(fragmentprojects);
+ allProjects.add(0, hostproject);
- init();
+ init();
}
private void init() {
- this.setAddCancelButton(true);
- this.setMessage("Select one of the following plug-ins:");
- this.setTitle("Project Selector");
- this.setContentProvider(new IProjectContentProvider());
- this.setLabelProvider(new IProjectLabelProvider());
+ this.setAddCancelButton(true);
+ this.setMessage("Select one of the following plug-ins:");
+ this.setTitle("Project Selector");
+ this.setContentProvider(new IProjectContentProvider());
+ this.setLabelProvider(new IProjectLabelProvider());
- this.setInput(allProjects);
+ this.setInput(allProjects);
}
public IProject getSelectedProject() {
- Object[] selection = this.getResult();
- if (selection != null && selection.length > 0)
- return (IProject) selection[0];
- return null;
+ Object[] selection = this.getResult();
+ if (selection != null && selection.length > 0)
+ return (IProject) selection[0];
+ return null;
}
// private classes--------------------------------------------------------
class IProjectContentProvider implements IStructuredContentProvider {
- @Override
- public Object[] getElements(Object inputElement) {
- List<IProject> resources = (List<IProject>) inputElement;
- return resources.toArray();
- }
+ @Override
+ public Object[] getElements(Object inputElement) {
+ List<IProject> resources = (List<IProject>) inputElement;
+ return resources.toArray();
+ }
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
- }
+ }
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // TODO Auto-generated method stub
- }
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ // TODO Auto-generated method stub
+ }
}
class IProjectLabelProvider implements ILabelProvider {
- @Override
- public Image getImage(Object element) {
- return PlatformUI.getWorkbench().getSharedImages()
- .getImage(ISharedImages.IMG_OBJ_PROJECT);
- }
+ @Override
+ public Image getImage(Object element) {
+ return PlatformUI.getWorkbench().getSharedImages()
+ .getImage(ISharedImages.IMG_OBJ_PROJECT);
+ }
- @Override
- public String getText(Object element) {
- IProject p = ((IProject) element);
- String text = p.getName();
- if (p.equals(hostproject))
- text += " [host project]";
- else
- text += " [fragment project]";
- return text;
- }
+ @Override
+ public String getText(Object element) {
+ IProject p = ((IProject) element);
+ String text = p.getName();
+ if (p.equals(hostproject))
+ text += " [host project]";
+ else
+ text += " [fragment project]";
+ return text;
+ }
- @Override
- public void addListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
+ @Override
+ public void addListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
- }
+ }
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
- }
+ }
- @Override
- public boolean isLabelProperty(Object element, String property) {
- // TODO Auto-generated method stub
- return false;
- }
+ @Override
+ public boolean isLabelProperty(Object element, String property) {
+ // TODO Auto-generated method stub
+ return false;
+ }
- @Override
- public void removeListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
+ @Override
+ public void removeListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
- }
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java
index ac9fce7..ae46d9b 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java
@@ -29,73 +29,73 @@
private Text packageName;
public GenerateBundleAccessorDialog(Shell parentShell) {
- super(parentShell);
+ super(parentShell);
}
@Override
protected Control createDialogArea(Composite parent) {
- Composite dialogArea = (Composite) super.createDialogArea(parent);
- initLayout(dialogArea);
- constructBASection(dialogArea);
- // constructDefaultSection (dialogArea);
- initContent();
- return dialogArea;
+ Composite dialogArea = (Composite) super.createDialogArea(parent);
+ initLayout(dialogArea);
+ constructBASection(dialogArea);
+ // constructDefaultSection (dialogArea);
+ initContent();
+ return dialogArea;
}
protected void initLayout(Composite parent) {
- final GridLayout layout = new GridLayout(1, true);
- parent.setLayout(layout);
+ final GridLayout layout = new GridLayout(1, true);
+ parent.setLayout(layout);
}
protected void constructBASection(Composite parent) {
- final Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
- group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
- false, 1, 1));
- group.setText("Resource Bundle");
+ final Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
+ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
+ group.setText("Resource Bundle");
- // define grid data for this group
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = true;
- group.setLayoutData(gridData);
- group.setLayout(new GridLayout(2, false));
+ // define grid data for this group
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ group.setLayoutData(gridData);
+ group.setLayout(new GridLayout(2, false));
- final Label spacer = new Label(group, SWT.NONE | SWT.LEFT);
- spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
- false, false, 1, 1));
+ final Label spacer = new Label(group, SWT.NONE | SWT.LEFT);
+ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
+ false, false, 1, 1));
- final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT);
- infoLabel.setLayoutData(new GridData(GridData.BEGINNING,
- GridData.CENTER, false, false, 1, 1));
- infoLabel
- .setText("Diese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.\nDiese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.");
+ final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT);
+ infoLabel.setLayoutData(new GridData(GridData.BEGINNING,
+ GridData.CENTER, false, false, 1, 1));
+ infoLabel
+ .setText("Diese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.\nDiese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.");
- // Schl�ssel
- final Label lblBA = new Label(group, SWT.NONE | SWT.RIGHT);
- GridData lblBAGrid = new GridData(GridData.END, GridData.CENTER, false,
- false, 1, 1);
- lblBAGrid.widthHint = WIDTH_LEFT_COLUMN;
- lblBA.setLayoutData(lblBAGrid);
- lblBA.setText("Class-Name:");
+ // Schl�ssel
+ final Label lblBA = new Label(group, SWT.NONE | SWT.RIGHT);
+ GridData lblBAGrid = new GridData(GridData.END, GridData.CENTER, false,
+ false, 1, 1);
+ lblBAGrid.widthHint = WIDTH_LEFT_COLUMN;
+ lblBA.setLayoutData(lblBAGrid);
+ lblBA.setText("Class-Name:");
- bundleAccessor = new Text(group, SWT.BORDER);
- bundleAccessor.setLayoutData(new GridData(GridData.FILL,
- GridData.CENTER, true, false, 1, 1));
+ bundleAccessor = new Text(group, SWT.BORDER);
+ bundleAccessor.setLayoutData(new GridData(GridData.FILL,
+ GridData.CENTER, true, false, 1, 1));
- // Resource-Bundle
- final Label lblPkg = new Label(group, SWT.NONE);
- lblPkg.setLayoutData(new GridData(GridData.END, GridData.CENTER, false,
- false, 1, 1));
- lblPkg.setText("Package:");
+ // Resource-Bundle
+ final Label lblPkg = new Label(group, SWT.NONE);
+ lblPkg.setLayoutData(new GridData(GridData.END, GridData.CENTER, false,
+ false, 1, 1));
+ lblPkg.setText("Package:");
- packageName = new Text(group, SWT.BORDER);
- packageName.setLayoutData(new GridData(GridData.FILL, GridData.CENTER,
- true, false, 1, 1));
+ packageName = new Text(group, SWT.BORDER);
+ packageName.setLayoutData(new GridData(GridData.FILL, GridData.CENTER,
+ true, false, 1, 1));
}
protected void initContent() {
- bundleAccessor.setText("BundleAccessor");
- packageName.setText("a.b");
+ bundleAccessor.setText("BundleAccessor");
+ packageName.setText("a.b");
}
/*
@@ -139,8 +139,8 @@
@Override
protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Create Resource-Bundle Accessor");
+ super.configureShell(newShell);
+ newShell.setText("Create Resource-Bundle Accessor");
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java
index 2106194..baca62a 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java
@@ -67,396 +67,396 @@
private String selectedKey = "";
public QueryResourceBundleEntryDialog(Shell parentShell,
- ResourceBundleManager manager, String bundleName) {
- super(parentShell);
- this.manager = manager;
- // init available resource bundles
- this.availableBundles = manager.getResourceBundleNames();
- this.preselectedRB = bundleName;
+ ResourceBundleManager manager, String bundleName) {
+ super(parentShell);
+ this.manager = manager;
+ // init available resource bundles
+ this.availableBundles = manager.getResourceBundleNames();
+ this.preselectedRB = bundleName;
}
@Override
protected Control createDialogArea(Composite parent) {
- Composite dialogArea = (Composite) super.createDialogArea(parent);
- initLayout(dialogArea);
- constructSearchSection(dialogArea);
- initContent();
- return dialogArea;
+ Composite dialogArea = (Composite) super.createDialogArea(parent);
+ initLayout(dialogArea);
+ constructSearchSection(dialogArea);
+ initContent();
+ return dialogArea;
}
protected void initContent() {
- // init available resource bundles
- cmbRB.removeAll();
- int i = 0;
- for (String bundle : availableBundles) {
- cmbRB.add(bundle);
- if (bundle.equals(preselectedRB)) {
- cmbRB.select(i);
- cmbRB.setEnabled(false);
- }
- i++;
- }
+ // init available resource bundles
+ cmbRB.removeAll();
+ int i = 0;
+ for (String bundle : availableBundles) {
+ cmbRB.add(bundle);
+ if (bundle.equals(preselectedRB)) {
+ cmbRB.select(i);
+ cmbRB.setEnabled(false);
+ }
+ i++;
+ }
- if (availableBundles.size() > 0) {
- if (preselectedRB.trim().length() == 0) {
- cmbRB.select(0);
- cmbRB.setEnabled(true);
- }
- }
+ if (availableBundles.size() > 0) {
+ if (preselectedRB.trim().length() == 0) {
+ cmbRB.select(0);
+ cmbRB.setEnabled(true);
+ }
+ }
- cmbRB.addSelectionListener(new SelectionListener() {
+ cmbRB.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- // updateAvailableLanguages();
- updateResourceSelector();
- }
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ // updateAvailableLanguages();
+ updateResourceSelector();
+ }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- // updateAvailableLanguages();
- updateResourceSelector();
- }
- });
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ // updateAvailableLanguages();
+ updateResourceSelector();
+ }
+ });
- // init available translations
- // updateAvailableLanguages();
+ // init available translations
+ // updateAvailableLanguages();
- // init resource selector
- updateResourceSelector();
+ // init resource selector
+ updateResourceSelector();
- // update search options
- updateSearchOptions();
+ // update search options
+ updateSearchOptions();
}
protected void updateResourceSelector() {
- resourceBundle = cmbRB.getText();
- resourceSelector.setResourceBundle(resourceBundle);
+ resourceBundle = cmbRB.getText();
+ resourceSelector.setResourceBundle(resourceBundle);
}
protected void updateSearchOptions() {
- searchOption = (btSearchKey.getSelection() ? SEARCH_KEY
- : SEARCH_FULLTEXT);
- // cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT);
- // lblLanguage.setEnabled(cmbLanguage.getEnabled());
+ searchOption = (btSearchKey.getSelection() ? SEARCH_KEY
+ : SEARCH_FULLTEXT);
+ // cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT);
+ // lblLanguage.setEnabled(cmbLanguage.getEnabled());
- // update ResourceSelector
- resourceSelector
- .setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT
- : ResourceSelector.DISPLAY_KEYS);
+ // update ResourceSelector
+ resourceSelector
+ .setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT
+ : ResourceSelector.DISPLAY_KEYS);
}
protected void updateAvailableLanguages() {
- cmbLanguage.removeAll();
- String selectedBundle = cmbRB.getText();
+ cmbLanguage.removeAll();
+ String selectedBundle = cmbRB.getText();
- if (selectedBundle.trim().equals(""))
- return;
+ if (selectedBundle.trim().equals(""))
+ return;
- // Retrieve available locales for the selected resource-bundle
- Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
- for (Locale l : locales) {
- String displayName = l.getDisplayName();
- if (displayName.equals(""))
- displayName = ResourceBundleManager.defaultLocaleTag;
- cmbLanguage.add(displayName);
- }
+ // Retrieve available locales for the selected resource-bundle
+ Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
+ for (Locale l : locales) {
+ String displayName = l.getDisplayName();
+ if (displayName.equals(""))
+ displayName = ResourceBundleManager.defaultLocaleTag;
+ cmbLanguage.add(displayName);
+ }
- // if (locales.size() > 0) {
- // cmbLanguage.select(0);
- updateSelectedLocale();
- // }
+ // if (locales.size() > 0) {
+ // cmbLanguage.select(0);
+ updateSelectedLocale();
+ // }
}
protected void updateSelectedLocale() {
- String selectedBundle = cmbRB.getText();
+ String selectedBundle = cmbRB.getText();
- if (selectedBundle.trim().equals(""))
- return;
+ if (selectedBundle.trim().equals(""))
+ return;
- Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
- Iterator<Locale> it = locales.iterator();
- String selectedLocale = cmbLanguage.getText();
- while (it.hasNext()) {
- Locale l = it.next();
- if (l.getDisplayName().equals(selectedLocale)) {
- resourceSelector.setDisplayLocale(l);
- break;
- }
- }
+ Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
+ Iterator<Locale> it = locales.iterator();
+ String selectedLocale = cmbLanguage.getText();
+ while (it.hasNext()) {
+ Locale l = it.next();
+ if (l.getDisplayName().equals(selectedLocale)) {
+ resourceSelector.setDisplayLocale(l);
+ break;
+ }
+ }
}
protected void initLayout(Composite parent) {
- final GridLayout layout = new GridLayout(1, true);
- parent.setLayout(layout);
+ final GridLayout layout = new GridLayout(1, true);
+ parent.setLayout(layout);
}
protected void constructSearchSection(Composite parent) {
- final Group group = new Group(parent, SWT.NONE);
- group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
- false, 1, 1));
- group.setText("Resource selection");
+ final Group group = new Group(parent, SWT.NONE);
+ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
+ group.setText("Resource selection");
- // define grid data for this group
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = true;
- group.setLayoutData(gridData);
- group.setLayout(new GridLayout(2, false));
- // TODO export as help text
+ // define grid data for this group
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ group.setLayoutData(gridData);
+ group.setLayout(new GridLayout(2, false));
+ // TODO export as help text
- final Label spacer = new Label(group, SWT.NONE | SWT.LEFT);
- spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
- false, false, 1, 1));
+ final Label spacer = new Label(group, SWT.NONE | SWT.LEFT);
+ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
+ false, false, 1, 1));
- final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT);
- GridData infoGrid = new GridData(GridData.BEGINNING,
- GridData.BEGINNING, false, false, 1, 1);
- infoGrid.heightHint = 70;
- infoLabel.setLayoutData(infoGrid);
- infoLabel
- .setText("Select the resource that needs to be refrenced. This is achieved in two\n"
- + "steps. First select the Resource-Bundle in which the resource is located. \n"
- + "In a last step you need to choose the required resource.");
+ final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT);
+ GridData infoGrid = new GridData(GridData.BEGINNING,
+ GridData.BEGINNING, false, false, 1, 1);
+ infoGrid.heightHint = 70;
+ infoLabel.setLayoutData(infoGrid);
+ infoLabel
+ .setText("Select the resource that needs to be refrenced. This is achieved in two\n"
+ + "steps. First select the Resource-Bundle in which the resource is located. \n"
+ + "In a last step you need to choose the required resource.");
- // Resource-Bundle
- final Label lblRB = new Label(group, SWT.NONE);
- lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false,
- false, 1, 1));
- lblRB.setText("Resource-Bundle:");
+ // Resource-Bundle
+ final Label lblRB = new Label(group, SWT.NONE);
+ lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false,
+ false, 1, 1));
+ lblRB.setText("Resource-Bundle:");
- cmbRB = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE);
- cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
- false, 1, 1));
- cmbRB.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- selectedRB = cmbRB.getText();
- validate();
- }
- });
+ cmbRB = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE);
+ cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
+ cmbRB.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedRB = cmbRB.getText();
+ validate();
+ }
+ });
- // Search-Options
- final Label spacer2 = new Label(group, SWT.NONE | SWT.LEFT);
- spacer2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
- false, false, 1, 1));
+ // Search-Options
+ final Label spacer2 = new Label(group, SWT.NONE | SWT.LEFT);
+ spacer2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
+ false, false, 1, 1));
- Composite searchOptions = new Composite(group, SWT.NONE);
- searchOptions.setLayout(new GridLayout(2, true));
+ Composite searchOptions = new Composite(group, SWT.NONE);
+ searchOptions.setLayout(new GridLayout(2, true));
- btSearchText = new Button(searchOptions, SWT.RADIO);
- btSearchText.setText("Full-text");
- btSearchText.setSelection(searchOption == SEARCH_FULLTEXT);
- btSearchText.addSelectionListener(new SelectionListener() {
+ btSearchText = new Button(searchOptions, SWT.RADIO);
+ btSearchText.setText("Full-text");
+ btSearchText.setSelection(searchOption == SEARCH_FULLTEXT);
+ btSearchText.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSearchOptions();
- }
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSearchOptions();
- }
- });
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+ });
- btSearchKey = new Button(searchOptions, SWT.RADIO);
- btSearchKey.setText("Key");
- btSearchKey.setSelection(searchOption == SEARCH_KEY);
- btSearchKey.addSelectionListener(new SelectionListener() {
+ btSearchKey = new Button(searchOptions, SWT.RADIO);
+ btSearchKey.setText("Key");
+ btSearchKey.setSelection(searchOption == SEARCH_KEY);
+ btSearchKey.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSearchOptions();
- }
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSearchOptions();
- }
- });
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+ });
- // Sprache
- // lblLanguage = new Label (group, SWT.NONE);
- // lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER,
- // false, false, 1, 1));
- // lblLanguage.setText("Language (Country):");
- //
- // cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
- // cmbLanguage.setLayoutData(new GridData(GridData.FILL,
- // GridData.CENTER, true, false, 1, 1));
- // cmbLanguage.addSelectionListener(new SelectionListener () {
- //
- // @Override
- // public void widgetDefaultSelected(SelectionEvent e) {
- // updateSelectedLocale();
- // }
- //
- // @Override
- // public void widgetSelected(SelectionEvent e) {
- // updateSelectedLocale();
- // }
- //
- // });
- // cmbLanguage.addModifyListener(new ModifyListener() {
- // @Override
- // public void modifyText(ModifyEvent e) {
- // selectedLocale =
- // LocaleUtils.getLocaleByDisplayName(manager.getProvidedLocales(selectedRB),
- // cmbLanguage.getText());
- // validate();
- // }
- // });
+ // Sprache
+ // lblLanguage = new Label (group, SWT.NONE);
+ // lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER,
+ // false, false, 1, 1));
+ // lblLanguage.setText("Language (Country):");
+ //
+ // cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
+ // cmbLanguage.setLayoutData(new GridData(GridData.FILL,
+ // GridData.CENTER, true, false, 1, 1));
+ // cmbLanguage.addSelectionListener(new SelectionListener () {
+ //
+ // @Override
+ // public void widgetDefaultSelected(SelectionEvent e) {
+ // updateSelectedLocale();
+ // }
+ //
+ // @Override
+ // public void widgetSelected(SelectionEvent e) {
+ // updateSelectedLocale();
+ // }
+ //
+ // });
+ // cmbLanguage.addModifyListener(new ModifyListener() {
+ // @Override
+ // public void modifyText(ModifyEvent e) {
+ // selectedLocale =
+ // LocaleUtils.getLocaleByDisplayName(manager.getProvidedLocales(selectedRB),
+ // cmbLanguage.getText());
+ // validate();
+ // }
+ // });
- // Filter
- final Label lblKey = new Label(group, SWT.NONE | SWT.RIGHT);
- GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER,
- false, false, 1, 1);
- lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN;
- lblKey.setLayoutData(lblKeyGrid);
- lblKey.setText("Filter:");
+ // Filter
+ final Label lblKey = new Label(group, SWT.NONE | SWT.RIGHT);
+ GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER,
+ false, false, 1, 1);
+ lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN;
+ lblKey.setLayoutData(lblKeyGrid);
+ lblKey.setText("Filter:");
- txtKey = new Text(group, SWT.BORDER);
- txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
- false, 1, 1));
+ txtKey = new Text(group, SWT.BORDER);
+ txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
- // Add selector for property keys
- final Label lblKeys = new Label(group, SWT.NONE);
- lblKeys.setLayoutData(new GridData(GridData.END, GridData.BEGINNING,
- false, false, 1, 1));
- lblKeys.setText("Resource:");
+ // Add selector for property keys
+ final Label lblKeys = new Label(group, SWT.NONE);
+ lblKeys.setLayoutData(new GridData(GridData.END, GridData.BEGINNING,
+ false, false, 1, 1));
+ lblKeys.setText("Resource:");
- resourceSelector = new ResourceSelector(group, SWT.NONE);
+ resourceSelector = new ResourceSelector(group, SWT.NONE);
- resourceSelector.setProjectName(manager.getProject().getName());
- resourceSelector.setResourceBundle(cmbRB.getText());
- resourceSelector.setDisplayMode(searchOption);
+ resourceSelector.setProjectName(manager.getProject().getName());
+ resourceSelector.setResourceBundle(cmbRB.getText());
+ resourceSelector.setDisplayMode(searchOption);
- GridData resourceSelectionData = new GridData(GridData.FILL,
- GridData.CENTER, true, false, 1, 1);
- resourceSelectionData.heightHint = 150;
- resourceSelectionData.widthHint = 400;
- resourceSelector.setLayoutData(resourceSelectionData);
- resourceSelector
- .addSelectionChangedListener(new IResourceSelectionListener() {
+ GridData resourceSelectionData = new GridData(GridData.FILL,
+ GridData.CENTER, true, false, 1, 1);
+ resourceSelectionData.heightHint = 150;
+ resourceSelectionData.widthHint = 400;
+ resourceSelector.setLayoutData(resourceSelectionData);
+ resourceSelector
+ .addSelectionChangedListener(new IResourceSelectionListener() {
- @Override
- public void selectionChanged(ResourceSelectionEvent e) {
- selectedKey = e.getSelectedKey();
- updatePreviewLabel(e.getSelectionSummary());
- validate();
- }
- });
+ @Override
+ public void selectionChanged(ResourceSelectionEvent e) {
+ selectedKey = e.getSelectedKey();
+ updatePreviewLabel(e.getSelectionSummary());
+ validate();
+ }
+ });
- // final Label spacer = new Label (group, SWT.SEPARATOR |
- // SWT.HORIZONTAL);
- // spacer.setLayoutData(new GridData(GridData.BEGINNING,
- // GridData.CENTER, true, false, 2, 1));
+ // final Label spacer = new Label (group, SWT.SEPARATOR |
+ // SWT.HORIZONTAL);
+ // spacer.setLayoutData(new GridData(GridData.BEGINNING,
+ // GridData.CENTER, true, false, 2, 1));
- // Preview
- final Label lblText = new Label(group, SWT.NONE | SWT.RIGHT);
- GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER,
- false, false, 1, 1);
- lblTextGrid.heightHint = 120;
- lblTextGrid.widthHint = 100;
- lblText.setLayoutData(lblTextGrid);
- lblText.setText("Preview:");
+ // Preview
+ final Label lblText = new Label(group, SWT.NONE | SWT.RIGHT);
+ GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER,
+ false, false, 1, 1);
+ lblTextGrid.heightHint = 120;
+ lblTextGrid.widthHint = 100;
+ lblText.setLayoutData(lblTextGrid);
+ lblText.setText("Preview:");
- txtPreviewText = new Text(group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
- txtPreviewText.setEditable(false);
- GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL,
- true, true, 1, 1);
- txtPreviewText.setLayoutData(lblTextGrid2);
+ txtPreviewText = new Text(group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
+ txtPreviewText.setEditable(false);
+ GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL,
+ true, true, 1, 1);
+ txtPreviewText.setLayoutData(lblTextGrid2);
}
@Override
protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Insert Resource-Bundle-Reference");
+ super.configureShell(newShell);
+ newShell.setText("Insert Resource-Bundle-Reference");
}
@Override
public void create() {
- // TODO Auto-generated method stub
- super.create();
- this.setTitle("Reference a Resource");
- this.setMessage("Please, specify details about the required Resource-Bundle reference");
+ // TODO Auto-generated method stub
+ super.create();
+ this.setTitle("Reference a Resource");
+ this.setMessage("Please, specify details about the required Resource-Bundle reference");
}
protected void updatePreviewLabel(String previewText) {
- txtPreviewText.setText(previewText);
+ txtPreviewText.setText(previewText);
}
protected void validate() {
- // Check Resource-Bundle ids
- boolean rbValid = false;
- boolean localeValid = false;
- boolean keyValid = false;
+ // Check Resource-Bundle ids
+ boolean rbValid = false;
+ boolean localeValid = false;
+ boolean keyValid = false;
- for (String rbId : this.availableBundles) {
- if (rbId.equals(selectedRB)) {
- rbValid = true;
- break;
- }
- }
+ for (String rbId : this.availableBundles) {
+ if (rbId.equals(selectedRB)) {
+ rbValid = true;
+ break;
+ }
+ }
- if (selectedLocale != null)
- localeValid = true;
+ if (selectedLocale != null)
+ localeValid = true;
- if (manager.isResourceExisting(selectedRB, selectedKey))
- keyValid = true;
+ if (manager.isResourceExisting(selectedRB, selectedKey))
+ keyValid = true;
- // print Validation summary
- String errorMessage = null;
- if (!rbValid)
- errorMessage = "The specified Resource-Bundle does not exist";
- // else if (! localeValid)
- // errorMessage =
- // "The specified Locale does not exist for the selecte Resource-Bundle";
- else if (!keyValid)
- errorMessage = "No resource selected";
- else {
- if (okButton != null)
- okButton.setEnabled(true);
- }
+ // print Validation summary
+ String errorMessage = null;
+ if (!rbValid)
+ errorMessage = "The specified Resource-Bundle does not exist";
+ // else if (! localeValid)
+ // errorMessage =
+ // "The specified Locale does not exist for the selecte Resource-Bundle";
+ else if (!keyValid)
+ errorMessage = "No resource selected";
+ else {
+ if (okButton != null)
+ okButton.setEnabled(true);
+ }
- setErrorMessage(errorMessage);
- if (okButton != null && errorMessage != null)
- okButton.setEnabled(false);
+ setErrorMessage(errorMessage);
+ if (okButton != null && errorMessage != null)
+ okButton.setEnabled(false);
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
- okButton = createButton(parent, OK, "Ok", true);
- okButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- // Set return code
- setReturnCode(OK);
- close();
- }
- });
+ okButton = createButton(parent, OK, "Ok", true);
+ okButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ // Set return code
+ setReturnCode(OK);
+ close();
+ }
+ });
- cancelButton = createButton(parent, CANCEL, "Cancel", false);
- cancelButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- setReturnCode(CANCEL);
- close();
- }
- });
+ cancelButton = createButton(parent, CANCEL, "Cancel", false);
+ cancelButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ setReturnCode(CANCEL);
+ close();
+ }
+ });
- okButton.setEnabled(false);
- cancelButton.setEnabled(true);
+ okButton.setEnabled(false);
+ cancelButton.setEnabled(true);
}
public String getSelectedResourceBundle() {
- return selectedRB;
+ return selectedRB;
}
public String getSelectedResource() {
- return selectedKey;
+ return selectedKey;
}
public Locale getSelectedLocale() {
- return selectedLocale;
+ return selectedLocale;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java
index b9a8d81..1f260a3 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java
@@ -28,96 +28,96 @@
private IProject project;
public RemoveLanguageDialoge(IProject project, Shell shell) {
- super(shell);
- this.project = project;
+ super(shell);
+ this.project = project;
- initDialog();
+ initDialog();
}
protected void initDialog() {
- this.setAddCancelButton(true);
- this.setMessage("Select one of the following languages to delete:");
- this.setTitle("Language Selector");
- this.setContentProvider(new RBContentProvider());
- this.setLabelProvider(new RBLabelProvider());
+ this.setAddCancelButton(true);
+ this.setMessage("Select one of the following languages to delete:");
+ this.setTitle("Language Selector");
+ this.setContentProvider(new RBContentProvider());
+ this.setLabelProvider(new RBLabelProvider());
- this.setInput(ResourceBundleManager.getManager(project)
- .getProjectProvidedLocales());
+ this.setInput(ResourceBundleManager.getManager(project)
+ .getProjectProvidedLocales());
}
public Locale getSelectedLanguage() {
- Object[] selection = this.getResult();
- if (selection != null && selection.length > 0)
- return (Locale) selection[0];
- return null;
+ Object[] selection = this.getResult();
+ if (selection != null && selection.length > 0)
+ return (Locale) selection[0];
+ return null;
}
// private
// classes-------------------------------------------------------------------------------------
class RBContentProvider implements IStructuredContentProvider {
- @Override
- public Object[] getElements(Object inputElement) {
- Set<Locale> resources = (Set<Locale>) inputElement;
- return resources.toArray();
- }
+ @Override
+ public Object[] getElements(Object inputElement) {
+ Set<Locale> resources = (Set<Locale>) inputElement;
+ return resources.toArray();
+ }
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
- }
+ }
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // TODO Auto-generated method stub
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ // TODO Auto-generated method stub
- }
+ }
}
class RBLabelProvider implements ILabelProvider {
- @Override
- public Image getImage(Object element) {
- return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
- }
+ @Override
+ public Image getImage(Object element) {
+ return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
+ }
- @Override
- public String getText(Object element) {
- Locale l = ((Locale) element);
- String text = l.getDisplayName();
- if (text == null || text.equals(""))
- text = "default";
- else
- text += " - " + l.getLanguage() + " " + l.getCountry() + " "
- + l.getVariant();
- return text;
- }
+ @Override
+ public String getText(Object element) {
+ Locale l = ((Locale) element);
+ String text = l.getDisplayName();
+ if (text == null || text.equals(""))
+ text = "default";
+ else
+ text += " - " + l.getLanguage() + " " + l.getCountry() + " "
+ + l.getVariant();
+ return text;
+ }
- @Override
- public void addListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
+ @Override
+ public void addListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
- }
+ }
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
- }
+ }
- @Override
- public boolean isLabelProperty(Object element, String property) {
- // TODO Auto-generated method stub
- return false;
- }
+ @Override
+ public boolean isLabelProperty(Object element, String property) {
+ // TODO Auto-generated method stub
+ return false;
+ }
- @Override
- public void removeListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
+ @Override
+ public void removeListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
- }
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java
index 9d2895a..3879c11 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java
@@ -66,409 +66,409 @@
private String selectedKey = "";
public ResourceBundleEntrySelectionDialog(Shell parentShell) {
- super(parentShell);
+ super(parentShell);
}
@Override
protected Control createDialogArea(Composite parent) {
- Composite dialogArea = (Composite) super.createDialogArea(parent);
- initLayout(dialogArea);
- constructSearchSection(dialogArea);
- initContent();
- return dialogArea;
+ Composite dialogArea = (Composite) super.createDialogArea(parent);
+ initLayout(dialogArea);
+ constructSearchSection(dialogArea);
+ initContent();
+ return dialogArea;
}
protected void initContent() {
- // init available resource bundles
- cmbRB.removeAll();
- int i = 0;
- for (String bundle : ResourceBundleManager.getManager(projectName)
- .getResourceBundleNames()) {
- cmbRB.add(bundle);
- if (bundle.equals(preselectedRB)) {
- cmbRB.select(i);
- cmbRB.setEnabled(false);
- }
- i++;
- }
+ // init available resource bundles
+ cmbRB.removeAll();
+ int i = 0;
+ for (String bundle : ResourceBundleManager.getManager(projectName)
+ .getResourceBundleNames()) {
+ cmbRB.add(bundle);
+ if (bundle.equals(preselectedRB)) {
+ cmbRB.select(i);
+ cmbRB.setEnabled(false);
+ }
+ i++;
+ }
- if (ResourceBundleManager.getManager(projectName)
- .getResourceBundleNames().size() > 0) {
- if (preselectedRB.trim().length() == 0) {
- cmbRB.select(0);
- cmbRB.setEnabled(true);
- }
- }
+ if (ResourceBundleManager.getManager(projectName)
+ .getResourceBundleNames().size() > 0) {
+ if (preselectedRB.trim().length() == 0) {
+ cmbRB.select(0);
+ cmbRB.setEnabled(true);
+ }
+ }
- cmbRB.addSelectionListener(new SelectionListener() {
+ cmbRB.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- // updateAvailableLanguages();
- updateResourceSelector();
- }
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ // updateAvailableLanguages();
+ updateResourceSelector();
+ }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- // updateAvailableLanguages();
- updateResourceSelector();
- }
- });
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ // updateAvailableLanguages();
+ updateResourceSelector();
+ }
+ });
- // init available translations
- // updateAvailableLanguages();
+ // init available translations
+ // updateAvailableLanguages();
- // init resource selector
- updateResourceSelector();
+ // init resource selector
+ updateResourceSelector();
- // update search options
- updateSearchOptions();
+ // update search options
+ updateSearchOptions();
}
protected void updateResourceSelector() {
- resourceBundle = cmbRB.getText();
- resourceSelector.setResourceBundle(resourceBundle);
+ resourceBundle = cmbRB.getText();
+ resourceSelector.setResourceBundle(resourceBundle);
}
protected void updateSearchOptions() {
- searchOption = (btSearchKey.getSelection() ? SEARCH_KEY
- : SEARCH_FULLTEXT);
- // cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT);
- // lblLanguage.setEnabled(cmbLanguage.getEnabled());
+ searchOption = (btSearchKey.getSelection() ? SEARCH_KEY
+ : SEARCH_FULLTEXT);
+ // cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT);
+ // lblLanguage.setEnabled(cmbLanguage.getEnabled());
- // update ResourceSelector
- resourceSelector
- .setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT
- : ResourceSelector.DISPLAY_KEYS);
+ // update ResourceSelector
+ resourceSelector
+ .setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT
+ : ResourceSelector.DISPLAY_KEYS);
}
protected void updateAvailableLanguages() {
- cmbLanguage.removeAll();
- String selectedBundle = cmbRB.getText();
+ cmbLanguage.removeAll();
+ String selectedBundle = cmbRB.getText();
- if (selectedBundle.trim().equals(""))
- return;
+ if (selectedBundle.trim().equals(""))
+ return;
- // Retrieve available locales for the selected resource-bundle
- Set<Locale> locales = ResourceBundleManager.getManager(projectName)
- .getProvidedLocales(selectedBundle);
- for (Locale l : locales) {
- String displayName = l.getDisplayName();
- if (displayName.equals(""))
- displayName = ResourceBundleManager.defaultLocaleTag;
- cmbLanguage.add(displayName);
- }
+ // Retrieve available locales for the selected resource-bundle
+ Set<Locale> locales = ResourceBundleManager.getManager(projectName)
+ .getProvidedLocales(selectedBundle);
+ for (Locale l : locales) {
+ String displayName = l.getDisplayName();
+ if (displayName.equals(""))
+ displayName = ResourceBundleManager.defaultLocaleTag;
+ cmbLanguage.add(displayName);
+ }
- // if (locales.size() > 0) {
- // cmbLanguage.select(0);
- updateSelectedLocale();
- // }
+ // if (locales.size() > 0) {
+ // cmbLanguage.select(0);
+ updateSelectedLocale();
+ // }
}
protected void updateSelectedLocale() {
- String selectedBundle = cmbRB.getText();
+ String selectedBundle = cmbRB.getText();
- if (selectedBundle.trim().equals(""))
- return;
+ if (selectedBundle.trim().equals(""))
+ return;
- Set<Locale> locales = ResourceBundleManager.getManager(projectName)
- .getProvidedLocales(selectedBundle);
- Iterator<Locale> it = locales.iterator();
- String selectedLocale = cmbLanguage.getText();
- while (it.hasNext()) {
- Locale l = it.next();
- if (l.getDisplayName().equals(selectedLocale)) {
- resourceSelector.setDisplayLocale(l);
- break;
- }
- }
+ Set<Locale> locales = ResourceBundleManager.getManager(projectName)
+ .getProvidedLocales(selectedBundle);
+ Iterator<Locale> it = locales.iterator();
+ String selectedLocale = cmbLanguage.getText();
+ while (it.hasNext()) {
+ Locale l = it.next();
+ if (l.getDisplayName().equals(selectedLocale)) {
+ resourceSelector.setDisplayLocale(l);
+ break;
+ }
+ }
}
protected void initLayout(Composite parent) {
- final GridLayout layout = new GridLayout(1, true);
- parent.setLayout(layout);
+ final GridLayout layout = new GridLayout(1, true);
+ parent.setLayout(layout);
}
protected void constructSearchSection(Composite parent) {
- final Group group = new Group(parent, SWT.NONE);
- group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
- false, 1, 1));
- group.setText("Resource selection");
+ final Group group = new Group(parent, SWT.NONE);
+ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
+ group.setText("Resource selection");
- // define grid data for this group
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = true;
- group.setLayoutData(gridData);
- group.setLayout(new GridLayout(2, false));
- // TODO export as help text
+ // define grid data for this group
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ group.setLayoutData(gridData);
+ group.setLayout(new GridLayout(2, false));
+ // TODO export as help text
- final Label spacer = new Label(group, SWT.NONE | SWT.LEFT);
- spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
- false, false, 1, 1));
+ final Label spacer = new Label(group, SWT.NONE | SWT.LEFT);
+ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
+ false, false, 1, 1));
- final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT);
- GridData infoGrid = new GridData(GridData.BEGINNING,
- GridData.BEGINNING, false, false, 1, 1);
- infoGrid.heightHint = 70;
- infoLabel.setLayoutData(infoGrid);
- infoLabel
- .setText("Select the resource that needs to be refrenced. This is accomplished in two\n"
- + "steps. First select the Resource-Bundle in which the resource is located. \n"
- + "In a last step you need to choose a particular resource.");
+ final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT);
+ GridData infoGrid = new GridData(GridData.BEGINNING,
+ GridData.BEGINNING, false, false, 1, 1);
+ infoGrid.heightHint = 70;
+ infoLabel.setLayoutData(infoGrid);
+ infoLabel
+ .setText("Select the resource that needs to be refrenced. This is accomplished in two\n"
+ + "steps. First select the Resource-Bundle in which the resource is located. \n"
+ + "In a last step you need to choose a particular resource.");
- // Resource-Bundle
- final Label lblRB = new Label(group, SWT.NONE);
- lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false,
- false, 1, 1));
- lblRB.setText("Resource-Bundle:");
+ // Resource-Bundle
+ final Label lblRB = new Label(group, SWT.NONE);
+ lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false,
+ false, 1, 1));
+ lblRB.setText("Resource-Bundle:");
- cmbRB = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE);
- cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
- false, 1, 1));
- cmbRB.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- selectedRB = cmbRB.getText();
- validate();
- }
- });
+ cmbRB = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE);
+ cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
+ cmbRB.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedRB = cmbRB.getText();
+ validate();
+ }
+ });
- // Search-Options
- final Label spacer2 = new Label(group, SWT.NONE | SWT.LEFT);
- spacer2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
- false, false, 1, 1));
+ // Search-Options
+ final Label spacer2 = new Label(group, SWT.NONE | SWT.LEFT);
+ spacer2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
+ false, false, 1, 1));
- Composite searchOptions = new Composite(group, SWT.NONE);
- searchOptions.setLayout(new GridLayout(2, true));
+ Composite searchOptions = new Composite(group, SWT.NONE);
+ searchOptions.setLayout(new GridLayout(2, true));
- btSearchText = new Button(searchOptions, SWT.RADIO);
- btSearchText.setText("Flat");
- btSearchText.setSelection(searchOption == SEARCH_FULLTEXT);
- btSearchText.addSelectionListener(new SelectionListener() {
+ btSearchText = new Button(searchOptions, SWT.RADIO);
+ btSearchText.setText("Flat");
+ btSearchText.setSelection(searchOption == SEARCH_FULLTEXT);
+ btSearchText.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSearchOptions();
- }
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSearchOptions();
- }
- });
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+ });
- btSearchKey = new Button(searchOptions, SWT.RADIO);
- btSearchKey.setText("Hierarchical");
- btSearchKey.setSelection(searchOption == SEARCH_KEY);
- btSearchKey.addSelectionListener(new SelectionListener() {
+ btSearchKey = new Button(searchOptions, SWT.RADIO);
+ btSearchKey.setText("Hierarchical");
+ btSearchKey.setSelection(searchOption == SEARCH_KEY);
+ btSearchKey.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSearchOptions();
- }
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSearchOptions();
- }
- });
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+ });
- // Sprache
- // lblLanguage = new Label (group, SWT.NONE);
- // lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER,
- // false, false, 1, 1));
- // lblLanguage.setText("Language (Country):");
- //
- // cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
- // cmbLanguage.setLayoutData(new GridData(GridData.FILL,
- // GridData.CENTER, true, false, 1, 1));
- // cmbLanguage.addSelectionListener(new SelectionListener () {
- //
- // @Override
- // public void widgetDefaultSelected(SelectionEvent e) {
- // updateSelectedLocale();
- // }
- //
- // @Override
- // public void widgetSelected(SelectionEvent e) {
- // updateSelectedLocale();
- // }
- //
- // });
- // cmbLanguage.addModifyListener(new ModifyListener() {
- // @Override
- // public void modifyText(ModifyEvent e) {
- // selectedLocale =
- // LocaleUtils.getLocaleByDisplayName(manager.getProvidedLocales(selectedRB),
- // cmbLanguage.getText());
- // validate();
- // }
- // });
+ // Sprache
+ // lblLanguage = new Label (group, SWT.NONE);
+ // lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER,
+ // false, false, 1, 1));
+ // lblLanguage.setText("Language (Country):");
+ //
+ // cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
+ // cmbLanguage.setLayoutData(new GridData(GridData.FILL,
+ // GridData.CENTER, true, false, 1, 1));
+ // cmbLanguage.addSelectionListener(new SelectionListener () {
+ //
+ // @Override
+ // public void widgetDefaultSelected(SelectionEvent e) {
+ // updateSelectedLocale();
+ // }
+ //
+ // @Override
+ // public void widgetSelected(SelectionEvent e) {
+ // updateSelectedLocale();
+ // }
+ //
+ // });
+ // cmbLanguage.addModifyListener(new ModifyListener() {
+ // @Override
+ // public void modifyText(ModifyEvent e) {
+ // selectedLocale =
+ // LocaleUtils.getLocaleByDisplayName(manager.getProvidedLocales(selectedRB),
+ // cmbLanguage.getText());
+ // validate();
+ // }
+ // });
- // Filter
- // final Label lblKey = new Label (group, SWT.NONE | SWT.RIGHT);
- // GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER,
- // false, false, 1, 1);
- // lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN;
- // lblKey.setLayoutData(lblKeyGrid);
- // lblKey.setText("Filter:");
- //
- // txtKey = new Text (group, SWT.BORDER);
- // txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER,
- // true, false, 1, 1));
+ // Filter
+ // final Label lblKey = new Label (group, SWT.NONE | SWT.RIGHT);
+ // GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER,
+ // false, false, 1, 1);
+ // lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN;
+ // lblKey.setLayoutData(lblKeyGrid);
+ // lblKey.setText("Filter:");
+ //
+ // txtKey = new Text (group, SWT.BORDER);
+ // txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER,
+ // true, false, 1, 1));
- // Add selector for property keys
- final Label lblKeys = new Label(group, SWT.NONE);
- lblKeys.setLayoutData(new GridData(GridData.END, GridData.BEGINNING,
- false, false, 1, 1));
- lblKeys.setText("Resource:");
+ // Add selector for property keys
+ final Label lblKeys = new Label(group, SWT.NONE);
+ lblKeys.setLayoutData(new GridData(GridData.END, GridData.BEGINNING,
+ false, false, 1, 1));
+ lblKeys.setText("Resource:");
- resourceSelector = new ResourceSelector(group, SWT.NONE);
+ resourceSelector = new ResourceSelector(group, SWT.NONE);
- resourceSelector.setProjectName(projectName);
- resourceSelector.setResourceBundle(cmbRB.getText());
- resourceSelector.setDisplayMode(searchOption);
+ resourceSelector.setProjectName(projectName);
+ resourceSelector.setResourceBundle(cmbRB.getText());
+ resourceSelector.setDisplayMode(searchOption);
- GridData resourceSelectionData = new GridData(GridData.FILL,
- GridData.CENTER, true, false, 1, 1);
- resourceSelectionData.heightHint = 150;
- resourceSelectionData.widthHint = 400;
- resourceSelector.setLayoutData(resourceSelectionData);
- resourceSelector
- .addSelectionChangedListener(new IResourceSelectionListener() {
+ GridData resourceSelectionData = new GridData(GridData.FILL,
+ GridData.CENTER, true, false, 1, 1);
+ resourceSelectionData.heightHint = 150;
+ resourceSelectionData.widthHint = 400;
+ resourceSelector.setLayoutData(resourceSelectionData);
+ resourceSelector
+ .addSelectionChangedListener(new IResourceSelectionListener() {
- @Override
- public void selectionChanged(ResourceSelectionEvent e) {
- selectedKey = e.getSelectedKey();
- updatePreviewLabel(e.getSelectionSummary());
- validate();
- }
- });
+ @Override
+ public void selectionChanged(ResourceSelectionEvent e) {
+ selectedKey = e.getSelectedKey();
+ updatePreviewLabel(e.getSelectionSummary());
+ validate();
+ }
+ });
- // final Label spacer = new Label (group, SWT.SEPARATOR |
- // SWT.HORIZONTAL);
- // spacer.setLayoutData(new GridData(GridData.BEGINNING,
- // GridData.CENTER, true, false, 2, 1));
+ // final Label spacer = new Label (group, SWT.SEPARATOR |
+ // SWT.HORIZONTAL);
+ // spacer.setLayoutData(new GridData(GridData.BEGINNING,
+ // GridData.CENTER, true, false, 2, 1));
- // Preview
- final Label lblText = new Label(group, SWT.NONE | SWT.RIGHT);
- GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER,
- false, false, 1, 1);
- lblTextGrid.heightHint = 120;
- lblTextGrid.widthHint = 100;
- lblText.setLayoutData(lblTextGrid);
- lblText.setText("Preview:");
+ // Preview
+ final Label lblText = new Label(group, SWT.NONE | SWT.RIGHT);
+ GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER,
+ false, false, 1, 1);
+ lblTextGrid.heightHint = 120;
+ lblTextGrid.widthHint = 100;
+ lblText.setLayoutData(lblTextGrid);
+ lblText.setText("Preview:");
- txtPreviewText = new Text(group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
- txtPreviewText.setEditable(false);
- GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL,
- true, true, 1, 1);
- txtPreviewText.setLayoutData(lblTextGrid2);
+ txtPreviewText = new Text(group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
+ txtPreviewText.setEditable(false);
+ GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL,
+ true, true, 1, 1);
+ txtPreviewText.setLayoutData(lblTextGrid2);
}
@Override
protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Select Resource-Bundle entry");
+ super.configureShell(newShell);
+ newShell.setText("Select Resource-Bundle entry");
}
@Override
public void create() {
- // TODO Auto-generated method stub
- super.create();
- this.setTitle("Select a Resource-Bundle entry");
- this.setMessage("Please, select a resource of a particular Resource-Bundle");
+ // TODO Auto-generated method stub
+ super.create();
+ this.setTitle("Select a Resource-Bundle entry");
+ this.setMessage("Please, select a resource of a particular Resource-Bundle");
}
protected void updatePreviewLabel(String previewText) {
- txtPreviewText.setText(previewText);
+ txtPreviewText.setText(previewText);
}
protected void validate() {
- // Check Resource-Bundle ids
- boolean rbValid = false;
- boolean localeValid = false;
- boolean keyValid = false;
+ // Check Resource-Bundle ids
+ boolean rbValid = false;
+ boolean localeValid = false;
+ boolean keyValid = false;
- for (String rbId : ResourceBundleManager.getManager(projectName)
- .getResourceBundleNames()) {
- if (rbId.equals(selectedRB)) {
- rbValid = true;
- break;
- }
- }
+ for (String rbId : ResourceBundleManager.getManager(projectName)
+ .getResourceBundleNames()) {
+ if (rbId.equals(selectedRB)) {
+ rbValid = true;
+ break;
+ }
+ }
- if (selectedLocale != null)
- localeValid = true;
+ if (selectedLocale != null)
+ localeValid = true;
- if (ResourceBundleManager.getManager(projectName).isResourceExisting(
- selectedRB, selectedKey))
- keyValid = true;
+ if (ResourceBundleManager.getManager(projectName).isResourceExisting(
+ selectedRB, selectedKey))
+ keyValid = true;
- // print Validation summary
- String errorMessage = null;
- if (!rbValid)
- errorMessage = "The specified Resource-Bundle does not exist";
- // else if (! localeValid)
- // errorMessage =
- // "The specified Locale does not exist for the selecte Resource-Bundle";
- else if (!keyValid)
- errorMessage = "No resource selected";
- else {
- if (okButton != null)
- okButton.setEnabled(true);
- }
+ // print Validation summary
+ String errorMessage = null;
+ if (!rbValid)
+ errorMessage = "The specified Resource-Bundle does not exist";
+ // else if (! localeValid)
+ // errorMessage =
+ // "The specified Locale does not exist for the selecte Resource-Bundle";
+ else if (!keyValid)
+ errorMessage = "No resource selected";
+ else {
+ if (okButton != null)
+ okButton.setEnabled(true);
+ }
- setErrorMessage(errorMessage);
- if (okButton != null && errorMessage != null)
- okButton.setEnabled(false);
+ setErrorMessage(errorMessage);
+ if (okButton != null && errorMessage != null)
+ okButton.setEnabled(false);
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
- okButton = createButton(parent, OK, "Ok", true);
- okButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- // Set return code
- setReturnCode(OK);
- close();
- }
- });
+ okButton = createButton(parent, OK, "Ok", true);
+ okButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ // Set return code
+ setReturnCode(OK);
+ close();
+ }
+ });
- cancelButton = createButton(parent, CANCEL, "Cancel", false);
- cancelButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- setReturnCode(CANCEL);
- close();
- }
- });
+ cancelButton = createButton(parent, CANCEL, "Cancel", false);
+ cancelButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ setReturnCode(CANCEL);
+ close();
+ }
+ });
- okButton.setEnabled(false);
- cancelButton.setEnabled(true);
+ okButton.setEnabled(false);
+ cancelButton.setEnabled(true);
}
public String getSelectedResourceBundle() {
- return selectedRB;
+ return selectedRB;
}
public String getSelectedResource() {
- return selectedKey;
+ return selectedKey;
}
public Locale getSelectedLocale() {
- return selectedLocale;
+ return selectedLocale;
}
public void setProjectName(String projectName) {
- this.projectName = projectName;
+ this.projectName = projectName;
}
public void setBundleName(String bundleName) {
- this.bundleName = bundleName;
+ this.bundleName = bundleName;
- if (preselectedRB.isEmpty()) {
- preselectedRB = this.bundleName;
- }
+ if (preselectedRB.isEmpty()) {
+ preselectedRB = this.bundleName;
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java
index de01395..1e27d91 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java
@@ -29,93 +29,93 @@
private IProject project;
public ResourceBundleSelectionDialog(Shell parent, IProject project) {
- super(parent);
- this.project = project;
+ super(parent);
+ this.project = project;
- initDialog();
+ initDialog();
}
protected void initDialog() {
- this.setAddCancelButton(true);
- this.setMessage("Select one of the following Resource-Bundle to open:");
- this.setTitle("Resource-Bundle Selector");
- this.setContentProvider(new RBContentProvider());
- this.setLabelProvider(new RBLabelProvider());
- this.setBlockOnOpen(true);
+ this.setAddCancelButton(true);
+ this.setMessage("Select one of the following Resource-Bundle to open:");
+ this.setTitle("Resource-Bundle Selector");
+ this.setContentProvider(new RBContentProvider());
+ this.setLabelProvider(new RBLabelProvider());
+ this.setBlockOnOpen(true);
- if (project != null)
- this.setInput(RBManager.getInstance(project)
- .getMessagesBundleGroupNames());
- else
- this.setInput(RBManager.getAllMessagesBundleGroupNames());
+ if (project != null)
+ this.setInput(RBManager.getInstance(project)
+ .getMessagesBundleGroupNames());
+ else
+ this.setInput(RBManager.getAllMessagesBundleGroupNames());
}
public String getSelectedBundleId() {
- Object[] selection = this.getResult();
- if (selection != null && selection.length > 0)
- return (String) selection[0];
- return null;
+ Object[] selection = this.getResult();
+ if (selection != null && selection.length > 0)
+ return (String) selection[0];
+ return null;
}
class RBContentProvider implements IStructuredContentProvider {
- @Override
- public Object[] getElements(Object inputElement) {
- List<String> resources = (List<String>) inputElement;
- return resources.toArray();
- }
+ @Override
+ public Object[] getElements(Object inputElement) {
+ List<String> resources = (List<String>) inputElement;
+ return resources.toArray();
+ }
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
- }
+ }
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // TODO Auto-generated method stub
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ // TODO Auto-generated method stub
- }
+ }
}
class RBLabelProvider implements ILabelProvider {
- @Override
- public Image getImage(Object element) {
- // TODO Auto-generated method stub
- return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
- }
+ @Override
+ public Image getImage(Object element) {
+ // TODO Auto-generated method stub
+ return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
+ }
- @Override
- public String getText(Object element) {
- // TODO Auto-generated method stub
- return ((String) element);
- }
+ @Override
+ public String getText(Object element) {
+ // TODO Auto-generated method stub
+ return ((String) element);
+ }
- @Override
- public void addListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
+ @Override
+ public void addListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
- }
+ }
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
- }
+ }
- @Override
- public boolean isLabelProperty(Object element, String property) {
- // TODO Auto-generated method stub
- return false;
- }
+ @Override
+ public boolean isLabelProperty(Object element, String property) {
+ // TODO Auto-generated method stub
+ return false;
+ }
- @Override
- public void removeListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
+ @Override
+ public void removeListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
- }
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nAuditor.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nAuditor.java
index 61b9615..afa72c9 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nAuditor.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nAuditor.java
@@ -64,10 +64,10 @@
* resource
*/
public boolean isResourceOfType(IResource resource) {
- for (String ending : getFileEndings()) {
- if (resource.getFileExtension().equalsIgnoreCase(ending))
- return true;
- }
- return false;
+ for (String ending : getFileEndings()) {
+ if (resource.getFileExtension().equalsIgnoreCase(ending))
+ return true;
+ }
+ return false;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nResourceAuditor.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nResourceAuditor.java
index ac69fc0..04bb77a 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nResourceAuditor.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nResourceAuditor.java
@@ -98,10 +98,10 @@
* resource
*/
public boolean isResourceOfType(IResource resource) {
- for (String ending : getFileEndings()) {
- if (resource.getFileExtension().equalsIgnoreCase(ending))
- return true;
- }
- return false;
+ for (String ending : getFileEndings()) {
+ if (resource.getFileExtension().equalsIgnoreCase(ending))
+ return true;
+ }
+ return false;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java
index d79d4be..c9b8729 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java
@@ -24,18 +24,18 @@
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (debugEnabled)
- return true;
+ if (debugEnabled)
+ return true;
- if (element.getClass().getSimpleName().equals("CompilationUnit"))
- return false;
+ if (element.getClass().getSimpleName().equals("CompilationUnit"))
+ return false;
- if (!(element instanceof IFile))
- return true;
+ if (!(element instanceof IFile))
+ return true;
- IFile file = (IFile) element;
+ IFile file = (IFile) element;
- return file.getFileExtension().equalsIgnoreCase("properties");
+ return file.getFileExtension().equalsIgnoreCase("properties");
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java
index 6c6ec3f..22a9f00 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java
@@ -21,27 +21,27 @@
@Override
public String getMarkerType() {
- return "org.eclipse.core.resources.problemmarker";
+ return "org.eclipse.core.resources.problemmarker";
}
@Override
public String[] getAttribute() {
- // TODO Auto-generated method stub
- return null;
+ // TODO Auto-generated method stub
+ return null;
}
@Override
public boolean updateMarker(IMarker marker, IDocument document,
- Position position) {
- try {
- int start = position.getOffset();
- int end = position.getOffset() + position.getLength();
- marker.setAttribute(IMarker.CHAR_START, start);
- marker.setAttribute(IMarker.CHAR_END, end);
- return true;
- } catch (CoreException e) {
- Logger.logError(e);
- return false;
- }
+ Position position) {
+ try {
+ int start = position.getOffset();
+ int end = position.getOffset() + position.getLength();
+ marker.setAttribute(IMarker.CHAR_START, start);
+ marker.setAttribute(IMarker.CHAR_END, end);
+ return true;
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return false;
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java
index 65b9211..a5353e0 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java
@@ -49,26 +49,26 @@
@Override
public void loadState() {
- excludedResources = new HashSet<IResourceDescriptor>();
- FileReader reader = null;
- try {
- reader = new FileReader(FileUtils.getRBManagerStateFile());
- loadManagerState(XMLMemento.createReadRoot(reader));
- } catch (Exception e) {
- Logger.logError(e);
- }
+ excludedResources = new HashSet<IResourceDescriptor>();
+ FileReader reader = null;
+ try {
+ reader = new FileReader(FileUtils.getRBManagerStateFile());
+ loadManagerState(XMLMemento.createReadRoot(reader));
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
}
private void loadManagerState(XMLMemento memento) {
- IMemento excludedChild = memento.getChild(TAG_EXCLUDED);
- for (IMemento excluded : excludedChild.getChildren(TAG_RES_DESC)) {
- IResourceDescriptor descriptor = new ResourceDescriptor();
- descriptor.setAbsolutePath(excluded.getString(TAG_RES_DESC_ABS));
- descriptor.setRelativePath(excluded.getString(TAG_RES_DESC_REL));
- descriptor.setProjectName(excluded.getString(TAB_RES_DESC_PRO));
- descriptor.setBundleId(excluded.getString(TAB_RES_DESC_BID));
- excludedResources.add(descriptor);
- }
+ IMemento excludedChild = memento.getChild(TAG_EXCLUDED);
+ for (IMemento excluded : excludedChild.getChildren(TAG_RES_DESC)) {
+ IResourceDescriptor descriptor = new ResourceDescriptor();
+ descriptor.setAbsolutePath(excluded.getString(TAG_RES_DESC_ABS));
+ descriptor.setRelativePath(excluded.getString(TAG_RES_DESC_REL));
+ descriptor.setProjectName(excluded.getString(TAB_RES_DESC_PRO));
+ descriptor.setBundleId(excluded.getString(TAB_RES_DESC_BID));
+ excludedResources.add(descriptor);
+ }
}
/**
@@ -76,7 +76,7 @@
*/
@Override
public Set<IResourceDescriptor> getExcludedResources() {
- return excludedResources;
+ return excludedResources;
}
/**
@@ -84,37 +84,37 @@
*/
@Override
public void saveState() {
- if (excludedResources == null) {
- return;
- }
- XMLMemento memento = XMLMemento
- .createWriteRoot(TAG_INTERNATIONALIZATION);
- IMemento exclChild = memento.createChild(TAG_EXCLUDED);
+ if (excludedResources == null) {
+ return;
+ }
+ XMLMemento memento = XMLMemento
+ .createWriteRoot(TAG_INTERNATIONALIZATION);
+ IMemento exclChild = memento.createChild(TAG_EXCLUDED);
- Iterator<IResourceDescriptor> itExcl = excludedResources.iterator();
- while (itExcl.hasNext()) {
- IResourceDescriptor desc = itExcl.next();
- IMemento resDesc = exclChild.createChild(TAG_RES_DESC);
- resDesc.putString(TAB_RES_DESC_PRO, desc.getProjectName());
- resDesc.putString(TAG_RES_DESC_ABS, desc.getAbsolutePath());
- resDesc.putString(TAG_RES_DESC_REL, desc.getRelativePath());
- resDesc.putString(TAB_RES_DESC_BID, desc.getBundleId());
- }
- FileWriter writer = null;
- try {
- writer = new FileWriter(FileUtils.getRBManagerStateFile());
- memento.save(writer);
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- try {
- if (writer != null) {
- writer.close();
- }
- } catch (Exception e) {
- Logger.logError(e);
- }
- }
+ Iterator<IResourceDescriptor> itExcl = excludedResources.iterator();
+ while (itExcl.hasNext()) {
+ IResourceDescriptor desc = itExcl.next();
+ IMemento resDesc = exclChild.createChild(TAG_RES_DESC);
+ resDesc.putString(TAB_RES_DESC_PRO, desc.getProjectName());
+ resDesc.putString(TAG_RES_DESC_ABS, desc.getAbsolutePath());
+ resDesc.putString(TAG_RES_DESC_REL, desc.getRelativePath());
+ resDesc.putString(TAB_RES_DESC_BID, desc.getBundleId());
+ }
+ FileWriter writer = null;
+ try {
+ writer = new FileWriter(FileUtils.getRBManagerStateFile());
+ memento.save(writer);
+ } catch (Exception e) {
+ Logger.logError(e);
+ } finally {
+ try {
+ if (writer != null) {
+ writer.close();
+ }
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/menus/InternationalizationMenu.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/menus/InternationalizationMenu.java
index 64053b4..34149f0 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/menus/InternationalizationMenu.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/menus/InternationalizationMenu.java
@@ -65,369 +65,369 @@
}
public InternationalizationMenu(String id) {
- super(id);
+ super(id);
}
@Override
public void fill(Menu menu, int index) {
- if (getSelectedProjects().size() == 0 || !projectsSupported()) {
- return;
- }
+ if (getSelectedProjects().size() == 0 || !projectsSupported()) {
+ return;
+ }
- // Toggle Internatinalization
- mnuToggleInt = new MenuItem(menu, SWT.PUSH);
- mnuToggleInt.addSelectionListener(new SelectionAdapter() {
+ // Toggle Internatinalization
+ mnuToggleInt = new MenuItem(menu, SWT.PUSH);
+ mnuToggleInt.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- runToggleInt();
- }
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ runToggleInt();
+ }
- });
+ });
- // Exclude Resource
- excludeResource = new MenuItem(menu, SWT.PUSH);
- excludeResource.addSelectionListener(new SelectionAdapter() {
+ // Exclude Resource
+ excludeResource = new MenuItem(menu, SWT.PUSH);
+ excludeResource.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- runExclude();
- }
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ runExclude();
+ }
- });
+ });
- new MenuItem(menu, SWT.SEPARATOR);
+ new MenuItem(menu, SWT.SEPARATOR);
- // Add Language
- addLanguage = new MenuItem(menu, SWT.PUSH);
- addLanguage.addSelectionListener(new SelectionAdapter() {
+ // Add Language
+ addLanguage = new MenuItem(menu, SWT.PUSH);
+ addLanguage.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- runAddLanguage();
- }
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ runAddLanguage();
+ }
- });
+ });
- // Remove Language
- removeLanguage = new MenuItem(menu, SWT.PUSH);
- removeLanguage.addSelectionListener(new SelectionAdapter() {
+ // Remove Language
+ removeLanguage = new MenuItem(menu, SWT.PUSH);
+ removeLanguage.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- runRemoveLanguage();
- }
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ runRemoveLanguage();
+ }
- });
+ });
- menu.addMenuListener(new MenuAdapter() {
- @Override
- public void menuShown(MenuEvent e) {
- updateStateToggleInt(mnuToggleInt);
- // updateStateGenRBAccessor (generateAccessor);
- updateStateExclude(excludeResource);
- updateStateAddLanguage(addLanguage);
- updateStateRemoveLanguage(removeLanguage);
- }
- });
+ menu.addMenuListener(new MenuAdapter() {
+ @Override
+ public void menuShown(MenuEvent e) {
+ updateStateToggleInt(mnuToggleInt);
+ // updateStateGenRBAccessor (generateAccessor);
+ updateStateExclude(excludeResource);
+ updateStateAddLanguage(addLanguage);
+ updateStateRemoveLanguage(removeLanguage);
+ }
+ });
}
protected void runGenRBAccessor() {
- GenerateBundleAccessorDialog dlg = new GenerateBundleAccessorDialog(
- Display.getDefault().getActiveShell());
- if (dlg.open() != InputDialog.OK) {
- return;
- }
+ GenerateBundleAccessorDialog dlg = new GenerateBundleAccessorDialog(
+ Display.getDefault().getActiveShell());
+ if (dlg.open() != InputDialog.OK) {
+ return;
+ }
}
protected void updateStateGenRBAccessor(MenuItem menuItem) {
- Collection<IPackageFragment> frags = getSelectedPackageFragments();
- menuItem.setEnabled(frags.size() > 0);
+ Collection<IPackageFragment> frags = getSelectedPackageFragments();
+ menuItem.setEnabled(frags.size() > 0);
}
protected void updateStateToggleInt(MenuItem menuItem) {
- Collection<IProject> projects = getSelectedProjects();
- boolean enabled = projects.size() > 0;
- menuItem.setEnabled(enabled);
- setVisible(enabled);
- internationalizationEnabled = InternationalizationNature
- .hasNature(projects.iterator().next());
- // menuItem.setSelection(enabled && internationalizationEnabled);
+ Collection<IProject> projects = getSelectedProjects();
+ boolean enabled = projects.size() > 0;
+ menuItem.setEnabled(enabled);
+ setVisible(enabled);
+ internationalizationEnabled = InternationalizationNature
+ .hasNature(projects.iterator().next());
+ // menuItem.setSelection(enabled && internationalizationEnabled);
- if (internationalizationEnabled) {
- menuItem.setText("Disable Internationalization");
- } else {
- menuItem.setText("Enable Internationalization");
- }
+ if (internationalizationEnabled) {
+ menuItem.setText("Disable Internationalization");
+ } else {
+ menuItem.setText("Enable Internationalization");
+ }
}
private Collection<IPackageFragment> getSelectedPackageFragments() {
- Collection<IPackageFragment> frags = new HashSet<IPackageFragment>();
- IWorkbenchWindow window = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow();
- ISelection selection = window.getActivePage().getSelection();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection) selection)
- .iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof IPackageFragment) {
- IPackageFragment frag = (IPackageFragment) elem;
- if (!frag.isReadOnly()) {
- frags.add(frag);
- }
- }
- }
- }
- return frags;
+ Collection<IPackageFragment> frags = new HashSet<IPackageFragment>();
+ IWorkbenchWindow window = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow();
+ ISelection selection = window.getActivePage().getSelection();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection)
+ .iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof IPackageFragment) {
+ IPackageFragment frag = (IPackageFragment) elem;
+ if (!frag.isReadOnly()) {
+ frags.add(frag);
+ }
+ }
+ }
+ }
+ return frags;
}
private Collection<IProject> getSelectedProjects() {
- Collection<IProject> projects = new HashSet<IProject>();
- IWorkbenchWindow window = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow();
- ISelection selection = window.getActivePage().getSelection();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection) selection)
- .iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (!(elem instanceof IResource)) {
- if (!(elem instanceof IAdaptable)) {
- continue;
- }
- elem = ((IAdaptable) elem).getAdapter(IResource.class);
- if (!(elem instanceof IResource)) {
- continue;
- }
- }
- if (!(elem instanceof IProject)) {
- elem = ((IResource) elem).getProject();
- if (!(elem instanceof IProject)) {
- continue;
- }
- }
- if (((IProject) elem).isAccessible()) {
- projects.add((IProject) elem);
- }
+ Collection<IProject> projects = new HashSet<IProject>();
+ IWorkbenchWindow window = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow();
+ ISelection selection = window.getActivePage().getSelection();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection)
+ .iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (!(elem instanceof IResource)) {
+ if (!(elem instanceof IAdaptable)) {
+ continue;
+ }
+ elem = ((IAdaptable) elem).getAdapter(IResource.class);
+ if (!(elem instanceof IResource)) {
+ continue;
+ }
+ }
+ if (!(elem instanceof IProject)) {
+ elem = ((IResource) elem).getProject();
+ if (!(elem instanceof IProject)) {
+ continue;
+ }
+ }
+ if (((IProject) elem).isAccessible()) {
+ projects.add((IProject) elem);
+ }
- }
- }
- return projects;
+ }
+ }
+ return projects;
}
protected boolean projectsSupported() {
- Collection<IProject> projects = getSelectedProjects();
- for (IProject project : projects) {
- if (!InternationalizationNature.supportsNature(project)) {
- return false;
- }
- }
+ Collection<IProject> projects = getSelectedProjects();
+ for (IProject project : projects) {
+ if (!InternationalizationNature.supportsNature(project)) {
+ return false;
+ }
+ }
- return true;
+ return true;
}
protected void runToggleInt() {
- Collection<IProject> projects = getSelectedProjects();
- for (IProject project : projects) {
- toggleNature(project);
- }
+ Collection<IProject> projects = getSelectedProjects();
+ for (IProject project : projects) {
+ toggleNature(project);
+ }
}
private void toggleNature(IProject project) {
- if (InternationalizationNature.hasNature(project)) {
- InternationalizationNature.removeNature(project);
- } else {
- InternationalizationNature.addNature(project);
- }
+ if (InternationalizationNature.hasNature(project)) {
+ InternationalizationNature.removeNature(project);
+ } else {
+ InternationalizationNature.addNature(project);
+ }
}
protected void updateStateExclude(MenuItem menuItem) {
- Collection<IResource> resources = getSelectedResources();
- menuItem.setEnabled(resources.size() > 0 && internationalizationEnabled);
- ResourceBundleManager manager = null;
- excludeMode = false;
+ Collection<IResource> resources = getSelectedResources();
+ menuItem.setEnabled(resources.size() > 0 && internationalizationEnabled);
+ ResourceBundleManager manager = null;
+ excludeMode = false;
- for (IResource res : resources) {
- if (manager == null || (manager.getProject() != res.getProject())) {
- manager = ResourceBundleManager.getManager(res.getProject());
- }
- try {
- if (!ResourceBundleManager.isResourceExcluded(res)) {
- excludeMode = true;
- }
- } catch (Exception e) {
- }
- }
+ for (IResource res : resources) {
+ if (manager == null || (manager.getProject() != res.getProject())) {
+ manager = ResourceBundleManager.getManager(res.getProject());
+ }
+ try {
+ if (!ResourceBundleManager.isResourceExcluded(res)) {
+ excludeMode = true;
+ }
+ } catch (Exception e) {
+ }
+ }
- if (!excludeMode) {
- menuItem.setText("Include Resource");
- } else {
- menuItem.setText("Exclude Resource");
- }
+ if (!excludeMode) {
+ menuItem.setText("Include Resource");
+ } else {
+ menuItem.setText("Exclude Resource");
+ }
}
private Collection<IResource> getSelectedResources() {
- Collection<IResource> resources = new HashSet<IResource>();
- IWorkbenchWindow window = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow();
- ISelection selection = window.getActivePage().getSelection();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection) selection)
- .iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof IProject) {
- continue;
- }
+ Collection<IResource> resources = new HashSet<IResource>();
+ IWorkbenchWindow window = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow();
+ ISelection selection = window.getActivePage().getSelection();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection)
+ .iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof IProject) {
+ continue;
+ }
- if (elem instanceof IResource) {
- resources.add((IResource) elem);
- } else if (elem instanceof IJavaElement) {
- resources.add(((IJavaElement) elem).getResource());
- }
- }
- }
- return resources;
+ if (elem instanceof IResource) {
+ resources.add((IResource) elem);
+ } else if (elem instanceof IJavaElement) {
+ resources.add(((IJavaElement) elem).getResource());
+ }
+ }
+ }
+ return resources;
}
protected void runExclude() {
- final Collection<IResource> selectedResources = getSelectedResources();
+ final Collection<IResource> selectedResources = getSelectedResources();
- IWorkbench wb = PlatformUI.getWorkbench();
- IProgressService ps = wb.getProgressService();
- try {
- ps.busyCursorWhile(new IRunnableWithProgress() {
- @Override
- public void run(IProgressMonitor pm) {
+ IWorkbench wb = PlatformUI.getWorkbench();
+ IProgressService ps = wb.getProgressService();
+ try {
+ ps.busyCursorWhile(new IRunnableWithProgress() {
+ @Override
+ public void run(IProgressMonitor pm) {
- ResourceBundleManager manager = null;
- pm.beginTask("Including resources to Internationalization",
- selectedResources.size());
+ ResourceBundleManager manager = null;
+ pm.beginTask("Including resources to Internationalization",
+ selectedResources.size());
- for (IResource res : selectedResources) {
- if (manager == null
- || (manager.getProject() != res.getProject())) {
- manager = ResourceBundleManager.getManager(res
- .getProject());
- }
- if (excludeMode) {
- manager.excludeResource(res, pm);
- } else {
- manager.includeResource(res, pm);
- }
- pm.worked(1);
- }
- pm.done();
- }
- });
- } catch (Exception e) {
- }
+ for (IResource res : selectedResources) {
+ if (manager == null
+ || (manager.getProject() != res.getProject())) {
+ manager = ResourceBundleManager.getManager(res
+ .getProject());
+ }
+ if (excludeMode) {
+ manager.excludeResource(res, pm);
+ } else {
+ manager.includeResource(res, pm);
+ }
+ pm.worked(1);
+ }
+ pm.done();
+ }
+ });
+ } catch (Exception e) {
+ }
}
protected void updateStateAddLanguage(MenuItem menuItem) {
- Collection<IProject> projects = getSelectedProjects();
- boolean hasResourceBundles = false;
- for (IProject p : projects) {
- ResourceBundleManager rbmanager = ResourceBundleManager
- .getManager(p);
- hasResourceBundles = rbmanager.getResourceBundleIdentifiers()
- .size() > 0 ? true : false;
- }
+ Collection<IProject> projects = getSelectedProjects();
+ boolean hasResourceBundles = false;
+ for (IProject p : projects) {
+ ResourceBundleManager rbmanager = ResourceBundleManager
+ .getManager(p);
+ hasResourceBundles = rbmanager.getResourceBundleIdentifiers()
+ .size() > 0 ? true : false;
+ }
- menuItem.setText("Add Language To Project");
- menuItem.setEnabled(projects.size() > 0 && hasResourceBundles);
+ menuItem.setText("Add Language To Project");
+ menuItem.setEnabled(projects.size() > 0 && hasResourceBundles);
}
protected void runAddLanguage() {
- AddLanguageDialoge dialog = new AddLanguageDialoge(new Shell(
- Display.getCurrent()));
- if (dialog.open() == InputDialog.OK) {
- final Locale locale = dialog.getSelectedLanguage();
+ AddLanguageDialoge dialog = new AddLanguageDialoge(new Shell(
+ Display.getCurrent()));
+ if (dialog.open() == InputDialog.OK) {
+ final Locale locale = dialog.getSelectedLanguage();
- Collection<IProject> selectedProjects = getSelectedProjects();
- for (IProject project : selectedProjects) {
- // check if project is fragmentproject and continue working with
- // the hostproject, if host not member of selectedProjects
- if (FragmentProjectUtils.isFragment(project)) {
- IProject host = FragmentProjectUtils
- .getFragmentHost(project);
- if (!selectedProjects.contains(host)) {
- project = host;
- } else {
- continue;
- }
- }
+ Collection<IProject> selectedProjects = getSelectedProjects();
+ for (IProject project : selectedProjects) {
+ // check if project is fragmentproject and continue working with
+ // the hostproject, if host not member of selectedProjects
+ if (FragmentProjectUtils.isFragment(project)) {
+ IProject host = FragmentProjectUtils
+ .getFragmentHost(project);
+ if (!selectedProjects.contains(host)) {
+ project = host;
+ } else {
+ continue;
+ }
+ }
- List<IProject> fragments = FragmentProjectUtils
- .getFragments(project);
+ List<IProject> fragments = FragmentProjectUtils
+ .getFragments(project);
- if (!fragments.isEmpty()) {
- FragmentProjectSelectionDialog fragmentDialog = new FragmentProjectSelectionDialog(
- Display.getCurrent().getActiveShell(), project,
- fragments);
+ if (!fragments.isEmpty()) {
+ FragmentProjectSelectionDialog fragmentDialog = new FragmentProjectSelectionDialog(
+ Display.getCurrent().getActiveShell(), project,
+ fragments);
- if (fragmentDialog.open() == InputDialog.OK) {
- project = fragmentDialog.getSelectedProject();
- }
- }
+ if (fragmentDialog.open() == InputDialog.OK) {
+ project = fragmentDialog.getSelectedProject();
+ }
+ }
- final IProject selectedProject = project;
- BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
- @Override
- public void run() {
- LanguageUtils.addLanguageToProject(selectedProject,
- locale);
- }
+ final IProject selectedProject = project;
+ BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
+ @Override
+ public void run() {
+ LanguageUtils.addLanguageToProject(selectedProject,
+ locale);
+ }
- });
+ });
- }
- }
+ }
+ }
}
protected void updateStateRemoveLanguage(MenuItem menuItem) {
- Collection<IProject> projects = getSelectedProjects();
- boolean hasResourceBundles = false;
- if (projects.size() == 1) {
- IProject project = projects.iterator().next();
- ResourceBundleManager rbmanager = ResourceBundleManager
- .getManager(project);
- hasResourceBundles = rbmanager.getResourceBundleIdentifiers()
- .size() > 0 ? true : false;
- }
- menuItem.setText("Remove Language From Project");
- menuItem.setEnabled(projects.size() == 1 && hasResourceBundles/*
- * && more
- * than
- * one
- * common
- * languages
- * contained
- */);
+ Collection<IProject> projects = getSelectedProjects();
+ boolean hasResourceBundles = false;
+ if (projects.size() == 1) {
+ IProject project = projects.iterator().next();
+ ResourceBundleManager rbmanager = ResourceBundleManager
+ .getManager(project);
+ hasResourceBundles = rbmanager.getResourceBundleIdentifiers()
+ .size() > 0 ? true : false;
+ }
+ menuItem.setText("Remove Language From Project");
+ menuItem.setEnabled(projects.size() == 1 && hasResourceBundles/*
+ * && more
+ * than
+ * one
+ * common
+ * languages
+ * contained
+ */);
}
protected void runRemoveLanguage() {
- final IProject project = getSelectedProjects().iterator().next();
- RemoveLanguageDialoge dialog = new RemoveLanguageDialoge(project,
- new Shell(Display.getCurrent()));
+ final IProject project = getSelectedProjects().iterator().next();
+ RemoveLanguageDialoge dialog = new RemoveLanguageDialoge(project,
+ new Shell(Display.getCurrent()));
- if (dialog.open() == InputDialog.OK) {
- final Locale locale = dialog.getSelectedLanguage();
- if (locale != null) {
- if (MessageDialog.openConfirm(Display.getCurrent()
- .getActiveShell(), "Confirm",
- "Do you really want remove all properties-files for "
- + locale.getDisplayName() + "?")) {
- BusyIndicator.showWhile(Display.getCurrent(),
- new Runnable() {
- @Override
- public void run() {
- RBFileUtils.removeLanguageFromProject(
- project, locale);
- }
- });
- }
+ if (dialog.open() == InputDialog.OK) {
+ final Locale locale = dialog.getSelectedLanguage();
+ if (locale != null) {
+ if (MessageDialog.openConfirm(Display.getCurrent()
+ .getActiveShell(), "Confirm",
+ "Do you really want remove all properties-files for "
+ + locale.getDisplayName() + "?")) {
+ BusyIndicator.showWhile(Display.getCurrent(),
+ new Runnable() {
+ @Override
+ public void run() {
+ RBFileUtils.removeLanguageFromProject(
+ project, locale);
+ }
+ });
+ }
- }
- }
+ }
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/BuilderPreferencePage.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/BuilderPreferencePage.java
index d749330..c972b12 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/BuilderPreferencePage.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/BuilderPreferencePage.java
@@ -26,7 +26,7 @@
import org.eclipse.ui.IWorkbenchPreferencePage;
public class BuilderPreferencePage extends PreferencePage implements
- IWorkbenchPreferencePage {
+ IWorkbenchPreferencePage {
private static final int INDENT = 20;
private Button checkSameValueButton;
@@ -39,118 +39,118 @@
@Override
public void init(IWorkbench workbench) {
- setPreferenceStore(Activator.getDefault().getPreferenceStore());
+ setPreferenceStore(Activator.getDefault().getPreferenceStore());
}
@Override
protected Control createContents(Composite parent) {
- IPreferenceStore prefs = getPreferenceStore();
- Composite composite = new Composite(parent, SWT.SHADOW_OUT);
+ IPreferenceStore prefs = getPreferenceStore();
+ Composite composite = new Composite(parent, SWT.SHADOW_OUT);
- composite.setLayout(new GridLayout(1, false));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
+ composite.setLayout(new GridLayout(1, false));
+ composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
- Composite field = createComposite(parent, 0, 10);
- Label descriptionLabel = new Label(composite, SWT.NONE);
- descriptionLabel.setText("Select types of reported problems:");
+ Composite field = createComposite(parent, 0, 10);
+ Label descriptionLabel = new Label(composite, SWT.NONE);
+ descriptionLabel.setText("Select types of reported problems:");
- field = createComposite(composite, 0, 0);
- sourceAuditButton = new Button(field, SWT.CHECK);
- sourceAuditButton.setSelection(prefs
- .getBoolean(TapiJIPreferences.AUDIT_RESOURCE));
- sourceAuditButton
- .setText("Check source code for non externalizated Strings");
+ field = createComposite(composite, 0, 0);
+ sourceAuditButton = new Button(field, SWT.CHECK);
+ sourceAuditButton.setSelection(prefs
+ .getBoolean(TapiJIPreferences.AUDIT_RESOURCE));
+ sourceAuditButton
+ .setText("Check source code for non externalizated Strings");
- field = createComposite(composite, 0, 0);
- rbAuditButton = new Button(field, SWT.CHECK);
- rbAuditButton
- .setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_RB));
- rbAuditButton
- .setText("Check ResourceBundles on the following problems:");
- rbAuditButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent event) {
- setRBAudits();
- }
- });
+ field = createComposite(composite, 0, 0);
+ rbAuditButton = new Button(field, SWT.CHECK);
+ rbAuditButton
+ .setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_RB));
+ rbAuditButton
+ .setText("Check ResourceBundles on the following problems:");
+ rbAuditButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent event) {
+ setRBAudits();
+ }
+ });
- field = createComposite(composite, INDENT, 0);
- checkMissingValueButton = new Button(field, SWT.CHECK);
- checkMissingValueButton.setSelection(prefs
- .getBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY));
- checkMissingValueButton.setText("Missing translation for a key");
+ field = createComposite(composite, INDENT, 0);
+ checkMissingValueButton = new Button(field, SWT.CHECK);
+ checkMissingValueButton.setSelection(prefs
+ .getBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY));
+ checkMissingValueButton.setText("Missing translation for a key");
- field = createComposite(composite, INDENT, 0);
- checkSameValueButton = new Button(field, SWT.CHECK);
- checkSameValueButton.setSelection(prefs
- .getBoolean(TapiJIPreferences.AUDIT_SAME_VALUE));
- checkSameValueButton
- .setText("Same translations for one key in diffrent languages");
+ field = createComposite(composite, INDENT, 0);
+ checkSameValueButton = new Button(field, SWT.CHECK);
+ checkSameValueButton.setSelection(prefs
+ .getBoolean(TapiJIPreferences.AUDIT_SAME_VALUE));
+ checkSameValueButton
+ .setText("Same translations for one key in diffrent languages");
- field = createComposite(composite, INDENT, 0);
- checkMissingLanguageButton = new Button(field, SWT.CHECK);
- checkMissingLanguageButton.setSelection(prefs
- .getBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE));
- checkMissingLanguageButton
- .setText("Missing languages in a ResourceBundle");
+ field = createComposite(composite, INDENT, 0);
+ checkMissingLanguageButton = new Button(field, SWT.CHECK);
+ checkMissingLanguageButton.setSelection(prefs
+ .getBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE));
+ checkMissingLanguageButton
+ .setText("Missing languages in a ResourceBundle");
- setRBAudits();
+ setRBAudits();
- composite.pack();
+ composite.pack();
- return composite;
+ return composite;
}
@Override
protected void performDefaults() {
- IPreferenceStore prefs = getPreferenceStore();
+ IPreferenceStore prefs = getPreferenceStore();
- sourceAuditButton.setSelection(prefs
- .getDefaultBoolean(TapiJIPreferences.AUDIT_RESOURCE));
- rbAuditButton.setSelection(prefs
- .getDefaultBoolean(TapiJIPreferences.AUDIT_RB));
- checkMissingValueButton.setSelection(prefs
- .getDefaultBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY));
- checkSameValueButton.setSelection(prefs
- .getDefaultBoolean(TapiJIPreferences.AUDIT_SAME_VALUE));
- checkMissingLanguageButton.setSelection(prefs
- .getDefaultBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE));
+ sourceAuditButton.setSelection(prefs
+ .getDefaultBoolean(TapiJIPreferences.AUDIT_RESOURCE));
+ rbAuditButton.setSelection(prefs
+ .getDefaultBoolean(TapiJIPreferences.AUDIT_RB));
+ checkMissingValueButton.setSelection(prefs
+ .getDefaultBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY));
+ checkSameValueButton.setSelection(prefs
+ .getDefaultBoolean(TapiJIPreferences.AUDIT_SAME_VALUE));
+ checkMissingLanguageButton.setSelection(prefs
+ .getDefaultBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE));
}
@Override
public boolean performOk() {
- IPreferenceStore prefs = getPreferenceStore();
+ IPreferenceStore prefs = getPreferenceStore();
- prefs.setValue(TapiJIPreferences.AUDIT_RESOURCE,
- sourceAuditButton.getSelection());
- prefs.setValue(TapiJIPreferences.AUDIT_RB, rbAuditButton.getSelection());
- prefs.setValue(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY,
- checkMissingValueButton.getSelection());
- prefs.setValue(TapiJIPreferences.AUDIT_SAME_VALUE,
- checkSameValueButton.getSelection());
- prefs.setValue(TapiJIPreferences.AUDIT_MISSING_LANGUAGE,
- checkMissingLanguageButton.getSelection());
+ prefs.setValue(TapiJIPreferences.AUDIT_RESOURCE,
+ sourceAuditButton.getSelection());
+ prefs.setValue(TapiJIPreferences.AUDIT_RB, rbAuditButton.getSelection());
+ prefs.setValue(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY,
+ checkMissingValueButton.getSelection());
+ prefs.setValue(TapiJIPreferences.AUDIT_SAME_VALUE,
+ checkSameValueButton.getSelection());
+ prefs.setValue(TapiJIPreferences.AUDIT_MISSING_LANGUAGE,
+ checkMissingLanguageButton.getSelection());
- return super.performOk();
+ return super.performOk();
}
private Composite createComposite(Composite parent, int marginWidth,
- int marginHeight) {
- Composite composite = new Composite(parent, SWT.NONE);
+ int marginHeight) {
+ Composite composite = new Composite(parent, SWT.NONE);
- GridLayout indentLayout = new GridLayout(1, false);
- indentLayout.marginWidth = marginWidth;
- indentLayout.marginHeight = marginHeight;
- indentLayout.verticalSpacing = 0;
- composite.setLayout(indentLayout);
+ GridLayout indentLayout = new GridLayout(1, false);
+ indentLayout.marginWidth = marginWidth;
+ indentLayout.marginHeight = marginHeight;
+ indentLayout.verticalSpacing = 0;
+ composite.setLayout(indentLayout);
- return composite;
+ return composite;
}
protected void setRBAudits() {
- boolean selected = rbAuditButton.getSelection();
- checkMissingValueButton.setEnabled(selected);
- checkSameValueButton.setEnabled(selected);
- checkMissingLanguageButton.setEnabled(selected);
+ boolean selected = rbAuditButton.getSelection();
+ checkMissingValueButton.setEnabled(selected);
+ checkSameValueButton.setEnabled(selected);
+ checkMissingLanguageButton.setEnabled(selected);
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/CheckItem.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/CheckItem.java
index 541f804..42a56c5 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/CheckItem.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/CheckItem.java
@@ -16,19 +16,19 @@
String name;
public CheckItem(String item, boolean checked) {
- this.name = item;
- this.checked = checked;
+ this.name = item;
+ this.checked = checked;
}
public String getName() {
- return name;
+ return name;
}
public boolean getChecked() {
- return checked;
+ return checked;
}
public boolean equals(CheckItem item) {
- return name.equals(item.getName());
+ return name.equals(item.getName());
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/FilePreferencePage.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/FilePreferencePage.java
index aa382f1..4f25e42 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/FilePreferencePage.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/FilePreferencePage.java
@@ -36,7 +36,7 @@
import org.eclipse.ui.IWorkbenchPreferencePage;
public class FilePreferencePage extends PreferencePage implements
- IWorkbenchPreferencePage {
+ IWorkbenchPreferencePage {
private Table table;
protected Object dialoge;
@@ -46,182 +46,182 @@
@Override
public void init(IWorkbench workbench) {
- setPreferenceStore(Activator.getDefault().getPreferenceStore());
+ setPreferenceStore(Activator.getDefault().getPreferenceStore());
}
@Override
protected Control createContents(Composite parent) {
- IPreferenceStore prefs = getPreferenceStore();
- Composite composite = new Composite(parent, SWT.SHADOW_OUT);
+ IPreferenceStore prefs = getPreferenceStore();
+ Composite composite = new Composite(parent, SWT.SHADOW_OUT);
- composite.setLayout(new GridLayout(2, false));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
+ composite.setLayout(new GridLayout(2, false));
+ composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
- Label descriptionLabel = new Label(composite, SWT.WRAP);
- GridData descriptionData = new GridData(SWT.FILL, SWT.TOP, false, false);
- descriptionData.horizontalSpan = 2;
- descriptionLabel.setLayoutData(descriptionData);
- descriptionLabel
- .setText("Properties-files which match the following pattern, will not be interpreted as ResourceBundle-files");
+ Label descriptionLabel = new Label(composite, SWT.WRAP);
+ GridData descriptionData = new GridData(SWT.FILL, SWT.TOP, false, false);
+ descriptionData.horizontalSpan = 2;
+ descriptionLabel.setLayoutData(descriptionData);
+ descriptionLabel
+ .setText("Properties-files which match the following pattern, will not be interpreted as ResourceBundle-files");
- table = new Table(composite, SWT.SINGLE | SWT.BORDER
- | SWT.FULL_SELECTION | SWT.CHECK);
- GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
- table.setLayoutData(data);
+ table = new Table(composite, SWT.SINGLE | SWT.BORDER
+ | SWT.FULL_SELECTION | SWT.CHECK);
+ GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
+ table.setLayoutData(data);
- table.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- TableItem[] selection = table.getSelection();
- if (selection.length > 0) {
- editPatternButton.setEnabled(true);
- removePatternButton.setEnabled(true);
- } else {
- editPatternButton.setEnabled(false);
- removePatternButton.setEnabled(false);
- }
- }
+ table.addSelectionListener(new SelectionListener() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ TableItem[] selection = table.getSelection();
+ if (selection.length > 0) {
+ editPatternButton.setEnabled(true);
+ removePatternButton.setEnabled(true);
+ } else {
+ editPatternButton.setEnabled(false);
+ removePatternButton.setEnabled(false);
+ }
+ }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- // TODO Auto-generated method stub
- }
- });
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ // TODO Auto-generated method stub
+ }
+ });
- List<CheckItem> patternItems = TapiJIPreferences
- .getNonRbPatternAsList();
- for (CheckItem s : patternItems) {
- toTableItem(table, s);
- }
+ List<CheckItem> patternItems = TapiJIPreferences
+ .getNonRbPatternAsList();
+ for (CheckItem s : patternItems) {
+ toTableItem(table, s);
+ }
- Composite sitebar = new Composite(composite, SWT.NONE);
- sitebar.setLayout(new GridLayout(1, false));
- sitebar.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, true));
+ Composite sitebar = new Composite(composite, SWT.NONE);
+ sitebar.setLayout(new GridLayout(1, false));
+ sitebar.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, true));
- Button addPatternButton = new Button(sitebar, SWT.NONE);
- addPatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true,
- true));
- addPatternButton.setText("Add Pattern");
- addPatternButton.addMouseListener(new MouseListener() {
- @Override
- public void mouseUp(MouseEvent e) {
- // TODO Auto-generated method stub
- }
+ Button addPatternButton = new Button(sitebar, SWT.NONE);
+ addPatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true,
+ true));
+ addPatternButton.setText("Add Pattern");
+ addPatternButton.addMouseListener(new MouseListener() {
+ @Override
+ public void mouseUp(MouseEvent e) {
+ // TODO Auto-generated method stub
+ }
- @Override
- public void mouseDown(MouseEvent e) {
- String pattern = "^.*/<BASENAME>"
- + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?"
- + "\\.properties$";
- CreatePatternDialoge dialog = new CreatePatternDialoge(Display
- .getDefault().getActiveShell(), pattern);
- if (dialog.open() == InputDialog.OK) {
- pattern = dialog.getPattern();
+ @Override
+ public void mouseDown(MouseEvent e) {
+ String pattern = "^.*/<BASENAME>"
+ + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?"
+ + "\\.properties$";
+ CreatePatternDialoge dialog = new CreatePatternDialoge(Display
+ .getDefault().getActiveShell(), pattern);
+ if (dialog.open() == InputDialog.OK) {
+ pattern = dialog.getPattern();
- TableItem item = new TableItem(table, SWT.NONE);
- item.setText(pattern);
- item.setChecked(true);
- }
- }
+ TableItem item = new TableItem(table, SWT.NONE);
+ item.setText(pattern);
+ item.setChecked(true);
+ }
+ }
- @Override
- public void mouseDoubleClick(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- });
+ @Override
+ public void mouseDoubleClick(MouseEvent e) {
+ // TODO Auto-generated method stub
+ }
+ });
- editPatternButton = new Button(sitebar, SWT.NONE);
- editPatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true,
- true));
- editPatternButton.setText("Edit");
- editPatternButton.addMouseListener(new MouseListener() {
- @Override
- public void mouseUp(MouseEvent e) {
- // TODO Auto-generated method stub
- }
+ editPatternButton = new Button(sitebar, SWT.NONE);
+ editPatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true,
+ true));
+ editPatternButton.setText("Edit");
+ editPatternButton.addMouseListener(new MouseListener() {
+ @Override
+ public void mouseUp(MouseEvent e) {
+ // TODO Auto-generated method stub
+ }
- @Override
- public void mouseDown(MouseEvent e) {
- TableItem[] selection = table.getSelection();
- if (selection.length > 0) {
- String pattern = selection[0].getText();
+ @Override
+ public void mouseDown(MouseEvent e) {
+ TableItem[] selection = table.getSelection();
+ if (selection.length > 0) {
+ String pattern = selection[0].getText();
- CreatePatternDialoge dialog = new CreatePatternDialoge(
- Display.getDefault().getActiveShell(), pattern);
- if (dialog.open() == InputDialog.OK) {
- pattern = dialog.getPattern();
- TableItem item = selection[0];
- item.setText(pattern);
- }
- }
- }
+ CreatePatternDialoge dialog = new CreatePatternDialoge(
+ Display.getDefault().getActiveShell(), pattern);
+ if (dialog.open() == InputDialog.OK) {
+ pattern = dialog.getPattern();
+ TableItem item = selection[0];
+ item.setText(pattern);
+ }
+ }
+ }
- @Override
- public void mouseDoubleClick(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- });
+ @Override
+ public void mouseDoubleClick(MouseEvent e) {
+ // TODO Auto-generated method stub
+ }
+ });
- removePatternButton = new Button(sitebar, SWT.NONE);
- removePatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true,
- true));
- removePatternButton.setText("Remove");
- removePatternButton.addMouseListener(new MouseListener() {
- @Override
- public void mouseUp(MouseEvent e) {
- // TODO Auto-generated method stub
- }
+ removePatternButton = new Button(sitebar, SWT.NONE);
+ removePatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true,
+ true));
+ removePatternButton.setText("Remove");
+ removePatternButton.addMouseListener(new MouseListener() {
+ @Override
+ public void mouseUp(MouseEvent e) {
+ // TODO Auto-generated method stub
+ }
- @Override
- public void mouseDown(MouseEvent e) {
- TableItem[] selection = table.getSelection();
- if (selection.length > 0) {
- table.remove(table.indexOf(selection[0]));
- }
- }
+ @Override
+ public void mouseDown(MouseEvent e) {
+ TableItem[] selection = table.getSelection();
+ if (selection.length > 0) {
+ table.remove(table.indexOf(selection[0]));
+ }
+ }
- @Override
- public void mouseDoubleClick(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- });
+ @Override
+ public void mouseDoubleClick(MouseEvent e) {
+ // TODO Auto-generated method stub
+ }
+ });
- composite.pack();
+ composite.pack();
- return composite;
+ return composite;
}
@Override
protected void performDefaults() {
- IPreferenceStore prefs = getPreferenceStore();
+ IPreferenceStore prefs = getPreferenceStore();
- table.removeAll();
+ table.removeAll();
- List<CheckItem> patterns = TapiJIPreferences.convertStringToList(prefs
- .getDefaultString(TapiJIPreferences.NON_RB_PATTERN));
- for (CheckItem s : patterns) {
- toTableItem(table, s);
- }
+ List<CheckItem> patterns = TapiJIPreferences.convertStringToList(prefs
+ .getDefaultString(TapiJIPreferences.NON_RB_PATTERN));
+ for (CheckItem s : patterns) {
+ toTableItem(table, s);
+ }
}
@Override
public boolean performOk() {
- IPreferenceStore prefs = getPreferenceStore();
- List<CheckItem> patterns = new LinkedList<CheckItem>();
- for (TableItem i : table.getItems()) {
- patterns.add(new CheckItem(i.getText(), i.getChecked()));
- }
+ IPreferenceStore prefs = getPreferenceStore();
+ List<CheckItem> patterns = new LinkedList<CheckItem>();
+ for (TableItem i : table.getItems()) {
+ patterns.add(new CheckItem(i.getText(), i.getChecked()));
+ }
- prefs.setValue(TapiJIPreferences.NON_RB_PATTERN,
- TapiJIPreferences.convertListToString(patterns));
+ prefs.setValue(TapiJIPreferences.NON_RB_PATTERN,
+ TapiJIPreferences.convertListToString(patterns));
- return super.performOk();
+ return super.performOk();
}
private TableItem toTableItem(Table table, CheckItem s) {
- TableItem item = new TableItem(table, SWT.NONE);
- item.setText(s.getName());
- item.setChecked(s.getChecked());
- return item;
+ TableItem item = new TableItem(table, SWT.NONE);
+ item.setText(s.getName());
+ item.setChecked(s.getChecked());
+ return item;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiHomePreferencePage.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiHomePreferencePage.java
index 107e777..ab346aa 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiHomePreferencePage.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiHomePreferencePage.java
@@ -21,24 +21,24 @@
import org.eclipse.ui.IWorkbenchPreferencePage;
public class TapiHomePreferencePage extends PreferencePage implements
- IWorkbenchPreferencePage {
+ IWorkbenchPreferencePage {
@Override
public void init(IWorkbench workbench) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
}
@Override
protected Control createContents(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(1, true));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ Composite composite = new Composite(parent, SWT.NONE);
+ composite.setLayout(new GridLayout(1, true));
+ composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- Label description = new Label(composite, SWT.WRAP);
- description.setText("See sub-pages for settings.");
+ Label description = new Label(composite, SWT.WRAP);
+ description.setText("See sub-pages for settings.");
- return parent;
+ return parent;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferenceInitializer.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferenceInitializer.java
index b22c86e..520e492 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferenceInitializer.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferenceInitializer.java
@@ -20,27 +20,27 @@
public class TapiJIPreferenceInitializer extends AbstractPreferenceInitializer {
public TapiJIPreferenceInitializer() {
- // TODO Auto-generated constructor stub
+ // TODO Auto-generated constructor stub
}
@Override
public void initializeDefaultPreferences() {
- IPreferenceStore prefs = Activator.getDefault().getPreferenceStore();
+ IPreferenceStore prefs = Activator.getDefault().getPreferenceStore();
- // ResourceBundle-Settings
- List<CheckItem> patterns = new LinkedList<CheckItem>();
- patterns.add(new CheckItem("^(.)*/build\\.properties", true));
- patterns.add(new CheckItem("^(.)*/config\\.properties", true));
- patterns.add(new CheckItem("^(.)*/targetplatform/(.)*", true));
- prefs.setDefault(TapiJIPreferences.NON_RB_PATTERN,
- TapiJIPreferences.convertListToString(patterns));
+ // ResourceBundle-Settings
+ List<CheckItem> patterns = new LinkedList<CheckItem>();
+ patterns.add(new CheckItem("^(.)*/build\\.properties", true));
+ patterns.add(new CheckItem("^(.)*/config\\.properties", true));
+ patterns.add(new CheckItem("^(.)*/targetplatform/(.)*", true));
+ prefs.setDefault(TapiJIPreferences.NON_RB_PATTERN,
+ TapiJIPreferences.convertListToString(patterns));
- // Builder
- prefs.setDefault(TapiJIPreferences.AUDIT_RESOURCE, true);
- prefs.setDefault(TapiJIPreferences.AUDIT_RB, true);
- prefs.setDefault(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY, true);
- prefs.setDefault(TapiJIPreferences.AUDIT_SAME_VALUE, false);
- prefs.setDefault(TapiJIPreferences.AUDIT_MISSING_LANGUAGE, true);
+ // Builder
+ prefs.setDefault(TapiJIPreferences.AUDIT_RESOURCE, true);
+ prefs.setDefault(TapiJIPreferences.AUDIT_RB, true);
+ prefs.setDefault(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY, true);
+ prefs.setDefault(TapiJIPreferences.AUDIT_SAME_VALUE, false);
+ prefs.setDefault(TapiJIPreferences.AUDIT_MISSING_LANGUAGE, true);
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferences.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferences.java
index e8035f1..47b8cc5 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferences.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferences.java
@@ -30,95 +30,95 @@
public static final String NON_RB_PATTERN = "NoRBPattern";
private static final IPreferenceStore PREF = Activator.getDefault()
- .getPreferenceStore();
+ .getPreferenceStore();
private static final String DELIMITER = ";";
private static final String ATTRIBUTE_DELIMITER = ":";
@Override
public boolean getAuditSameValue() {
- return PREF.getBoolean(AUDIT_SAME_VALUE);
+ return PREF.getBoolean(AUDIT_SAME_VALUE);
}
@Override
public boolean getAuditMissingValue() {
- return PREF.getBoolean(AUDIT_UNSPEZIFIED_KEY);
+ return PREF.getBoolean(AUDIT_UNSPEZIFIED_KEY);
}
@Override
public boolean getAuditMissingLanguage() {
- return PREF.getBoolean(AUDIT_MISSING_LANGUAGE);
+ return PREF.getBoolean(AUDIT_MISSING_LANGUAGE);
}
@Override
public boolean getAuditRb() {
- return PREF.getBoolean(AUDIT_RB);
+ return PREF.getBoolean(AUDIT_RB);
}
@Override
public boolean getAuditResource() {
- return PREF.getBoolean(AUDIT_RESOURCE);
+ return PREF.getBoolean(AUDIT_RESOURCE);
}
@Override
public String getNonRbPattern() {
- return PREF.getString(NON_RB_PATTERN);
+ return PREF.getString(NON_RB_PATTERN);
}
public static List<CheckItem> getNonRbPatternAsList() {
- return convertStringToList(PREF.getString(NON_RB_PATTERN));
+ return convertStringToList(PREF.getString(NON_RB_PATTERN));
}
public static List<CheckItem> convertStringToList(String string) {
- StringTokenizer tokenizer = new StringTokenizer(string, DELIMITER);
- int tokenCount = tokenizer.countTokens();
- List<CheckItem> elements = new LinkedList<CheckItem>();
+ StringTokenizer tokenizer = new StringTokenizer(string, DELIMITER);
+ int tokenCount = tokenizer.countTokens();
+ List<CheckItem> elements = new LinkedList<CheckItem>();
- for (int i = 0; i < tokenCount; i++) {
- StringTokenizer attribute = new StringTokenizer(
- tokenizer.nextToken(), ATTRIBUTE_DELIMITER);
- String name = attribute.nextToken();
- boolean checked;
- if (attribute.nextToken().equals("true")) {
- checked = true;
- } else {
- checked = false;
- }
+ for (int i = 0; i < tokenCount; i++) {
+ StringTokenizer attribute = new StringTokenizer(
+ tokenizer.nextToken(), ATTRIBUTE_DELIMITER);
+ String name = attribute.nextToken();
+ boolean checked;
+ if (attribute.nextToken().equals("true")) {
+ checked = true;
+ } else {
+ checked = false;
+ }
- elements.add(new CheckItem(name, checked));
- }
- return elements;
+ elements.add(new CheckItem(name, checked));
+ }
+ return elements;
}
public static String convertListToString(List<CheckItem> patterns) {
- StringBuilder sb = new StringBuilder();
- int tokenCount = 0;
+ StringBuilder sb = new StringBuilder();
+ int tokenCount = 0;
- for (CheckItem s : patterns) {
- sb.append(s.getName());
- sb.append(ATTRIBUTE_DELIMITER);
- if (s.checked) {
- sb.append("true");
- } else {
- sb.append("false");
- }
+ for (CheckItem s : patterns) {
+ sb.append(s.getName());
+ sb.append(ATTRIBUTE_DELIMITER);
+ if (s.checked) {
+ sb.append("true");
+ } else {
+ sb.append("false");
+ }
- if (++tokenCount != patterns.size()) {
- sb.append(DELIMITER);
- }
- }
- return sb.toString();
+ if (++tokenCount != patterns.size()) {
+ sb.append(DELIMITER);
+ }
+ }
+ return sb.toString();
}
public static void addPropertyChangeListener(
- IPropertyChangeListener listener) {
- Activator.getDefault().getPreferenceStore()
- .addPropertyChangeListener(listener);
+ IPropertyChangeListener listener) {
+ Activator.getDefault().getPreferenceStore()
+ .addPropertyChangeListener(listener);
}
public static void removePropertyChangeListener(
- IPropertyChangeListener listener) {
- Activator.getDefault().getPreferenceStore()
- .removePropertyChangeListener(listener);
+ IPropertyChangeListener listener) {
+ Activator.getDefault().getPreferenceStore()
+ .removePropertyChangeListener(listener);
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundle.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundle.java
index 2e8ee6e..ebef566 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundle.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundle.java
@@ -46,156 +46,156 @@
private final String newBunldeWizard = "org.eclipse.babel.editor.wizards.ResourceBundleWizard";
public CreateResourceBundle(String key, IResource resource, int start,
- int end) {
- this.key = ResourceUtils.deriveNonExistingRBName(key,
- ResourceBundleManager.getManager(resource.getProject()));
- this.resource = resource;
- this.start = start;
- this.end = end;
- this.jsfContext = jsfContext;
+ int end) {
+ this.key = ResourceUtils.deriveNonExistingRBName(key,
+ ResourceBundleManager.getManager(resource.getProject()));
+ this.resource = resource;
+ this.start = start;
+ this.end = end;
+ this.jsfContext = jsfContext;
}
@Override
public String getDescription() {
- return "Creates a new Resource-Bundle with the id '" + key + "'";
+ return "Creates a new Resource-Bundle with the id '" + key + "'";
}
@Override
public Image getImage() {
- // TODO Auto-generated method stub
- return null;
+ // TODO Auto-generated method stub
+ return null;
}
@Override
public String getLabel() {
- return "Create Resource-Bundle '" + key + "'";
+ return "Create Resource-Bundle '" + key + "'";
}
@Override
public void run(IMarker marker) {
- runAction();
+ runAction();
}
protected void runAction() {
- // First see if this is a "new wizard".
- IWizardDescriptor descriptor = PlatformUI.getWorkbench()
- .getNewWizardRegistry().findWizard(newBunldeWizard);
- // If not check if it is an "import wizard".
- if (descriptor == null) {
- descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
- .findWizard(newBunldeWizard);
- }
- // Or maybe an export wizard
- if (descriptor == null) {
- descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
- .findWizard(newBunldeWizard);
- }
- try {
- // Then if we have a wizard, open it.
- if (descriptor != null) {
- IWizard wizard = descriptor.createWizard();
- if (!(wizard instanceof IResourceBundleWizard)) {
- return;
- }
+ // First see if this is a "new wizard".
+ IWizardDescriptor descriptor = PlatformUI.getWorkbench()
+ .getNewWizardRegistry().findWizard(newBunldeWizard);
+ // If not check if it is an "import wizard".
+ if (descriptor == null) {
+ descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
+ .findWizard(newBunldeWizard);
+ }
+ // Or maybe an export wizard
+ if (descriptor == null) {
+ descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
+ .findWizard(newBunldeWizard);
+ }
+ try {
+ // Then if we have a wizard, open it.
+ if (descriptor != null) {
+ IWizard wizard = descriptor.createWizard();
+ if (!(wizard instanceof IResourceBundleWizard)) {
+ return;
+ }
- IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
- String[] keySilbings = key.split("\\.");
- String rbName = keySilbings[keySilbings.length - 1];
- String packageName = "";
+ IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
+ String[] keySilbings = key.split("\\.");
+ String rbName = keySilbings[keySilbings.length - 1];
+ String packageName = "";
- rbw.setBundleId(rbName);
+ rbw.setBundleId(rbName);
- // Set the default path according to the specified package name
- String pathName = "";
- if (keySilbings.length > 1) {
- try {
- IJavaProject jp = JavaCore
- .create(resource.getProject());
- packageName = key.substring(0, key.lastIndexOf("."));
+ // Set the default path according to the specified package name
+ String pathName = "";
+ if (keySilbings.length > 1) {
+ try {
+ IJavaProject jp = JavaCore
+ .create(resource.getProject());
+ packageName = key.substring(0, key.lastIndexOf("."));
- for (IPackageFragmentRoot fr : jp
- .getAllPackageFragmentRoots()) {
- IPackageFragment pf = fr
- .getPackageFragment(packageName);
- if (pf.exists()) {
- pathName = pf.getResource().getFullPath()
- .removeFirstSegments(0).toOSString();
- break;
- }
- }
- } catch (Exception e) {
- pathName = "";
- }
- }
+ for (IPackageFragmentRoot fr : jp
+ .getAllPackageFragmentRoots()) {
+ IPackageFragment pf = fr
+ .getPackageFragment(packageName);
+ if (pf.exists()) {
+ pathName = pf.getResource().getFullPath()
+ .removeFirstSegments(0).toOSString();
+ break;
+ }
+ }
+ } catch (Exception e) {
+ pathName = "";
+ }
+ }
- try {
- IJavaProject jp = JavaCore.create(resource.getProject());
- if (pathName.trim().equals("")) {
- for (IPackageFragmentRoot fr : jp
- .getAllPackageFragmentRoots()) {
- if (!fr.isReadOnly()) {
- pathName = fr.getResource().getFullPath()
- .removeFirstSegments(0).toOSString();
- break;
- }
- }
- }
- } catch (Exception e) {
- pathName = "";
- }
+ try {
+ IJavaProject jp = JavaCore.create(resource.getProject());
+ if (pathName.trim().equals("")) {
+ for (IPackageFragmentRoot fr : jp
+ .getAllPackageFragmentRoots()) {
+ if (!fr.isReadOnly()) {
+ pathName = fr.getResource().getFullPath()
+ .removeFirstSegments(0).toOSString();
+ break;
+ }
+ }
+ }
+ } catch (Exception e) {
+ pathName = "";
+ }
- rbw.setDefaultPath(pathName);
+ rbw.setDefaultPath(pathName);
- WizardDialog wd = new WizardDialog(Display.getDefault()
- .getActiveShell(), wizard);
- wd.setTitle(wizard.getWindowTitle());
- if (wd.open() == WizardDialog.OK) {
- try {
- resource.getProject().build(
- IncrementalProjectBuilder.FULL_BUILD,
- I18nBuilder.BUILDER_ID, null, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
+ WizardDialog wd = new WizardDialog(Display.getDefault()
+ .getActiveShell(), wizard);
+ wd.setTitle(wizard.getWindowTitle());
+ if (wd.open() == WizardDialog.OK) {
+ try {
+ resource.getProject().build(
+ IncrementalProjectBuilder.FULL_BUILD,
+ I18nBuilder.BUILDER_ID, null, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
- ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager
- .getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, null);
+ ITextFileBuffer textFileBuffer = bufferManager
+ .getTextFileBuffer(path);
+ IDocument document = textFileBuffer.getDocument();
- if (document.get().charAt(start - 1) == '"'
- && document.get().charAt(start) != '"') {
- start--;
- end++;
- }
- if (document.get().charAt(end + 1) == '"'
- && document.get().charAt(end) != '"') {
- end++;
- }
+ if (document.get().charAt(start - 1) == '"'
+ && document.get().charAt(start) != '"') {
+ start--;
+ end++;
+ }
+ if (document.get().charAt(end + 1) == '"'
+ && document.get().charAt(end) != '"') {
+ end++;
+ }
- document.replace(start, end - start, "\""
- + (packageName.equals("") ? "" : packageName
- + ".") + rbName + "\"");
+ document.replace(start, end - start, "\""
+ + (packageName.equals("") ? "" : packageName
+ + ".") + rbName + "\"");
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
- }
- }
- } catch (CoreException e) {
- Logger.logError(e);
- }
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ Logger.logError(e);
+ } finally {
+ try {
+ bufferManager.disconnect(path, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+ }
+ }
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java
index 14a3f30..2de8a6f 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java
@@ -35,68 +35,68 @@
private String bundleId;
public CreateResourceBundleEntry(String key, String bundleId) {
- this.key = key;
- this.bundleId = bundleId;
+ this.key = key;
+ this.bundleId = bundleId;
}
@Override
public String getDescription() {
- return "Creates a new Resource-Bundle entry for the property-key '"
- + key + "'";
+ return "Creates a new Resource-Bundle entry for the property-key '"
+ + key + "'";
}
@Override
public Image getImage() {
- // TODO Auto-generated method stub
- return null;
+ // TODO Auto-generated method stub
+ return null;
}
@Override
public String getLabel() {
- return "Create Resource-Bundle entry for '" + key + "'";
+ return "Create Resource-Bundle entry for '" + key + "'";
}
@Override
public void run(IMarker marker) {
- int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
- int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
- IResource resource = marker.getResource();
+ int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
+ int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
+ IResource resource = marker.getResource();
- ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager
- .getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, null);
+ ITextFileBuffer textFileBuffer = bufferManager
+ .getTextFileBuffer(path);
+ IDocument document = textFileBuffer.getDocument();
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell());
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
- DialogConfiguration config = dialog.new DialogConfiguration();
- config.setPreselectedKey(key != null ? key : "");
- config.setPreselectedMessage("");
- config.setPreselectedBundle(bundleId);
- config.setPreselectedLocale("");
- config.setProjectName(resource.getProject().getName());
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey(key != null ? key : "");
+ config.setPreselectedMessage("");
+ config.setPreselectedBundle(bundleId);
+ config.setPreselectedLocale("");
+ config.setProjectName(resource.getProject().getName());
- dialog.setDialogConfiguration(config);
+ dialog.setDialogConfiguration(config);
- if (dialog.open() != InputDialog.OK) {
- return;
- }
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- try {
- resource.getProject().build(
- IncrementalProjectBuilder.FULL_BUILD,
- I18nBuilder.BUILDER_ID, null, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
+ if (dialog.open() != InputDialog.OK) {
+ return;
+ }
+ } catch (Exception e) {
+ Logger.logError(e);
+ } finally {
+ try {
+ resource.getProject().build(
+ IncrementalProjectBuilder.FULL_BUILD,
+ I18nBuilder.BUILDER_ID, null, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/IncludeResource.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/IncludeResource.java
index d4d389c..e3751ca 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/IncludeResource.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/IncludeResource.java
@@ -29,51 +29,51 @@
private Set<IResource> bundleResources;
public IncludeResource(String bundleName, Set<IResource> bundleResources) {
- this.bundleResources = bundleResources;
- this.bundleName = bundleName;
+ this.bundleResources = bundleResources;
+ this.bundleName = bundleName;
}
@Override
public String getDescription() {
- return "The Resource-Bundle with id '"
- + bundleName
- + "' has been "
- + "excluded from Internationalization. Based on this fact, no internationalization "
- + "supoort is provided for this Resource-Bundle. Performing this action, internationalization "
- + "support for '" + bundleName + "' will be enabled";
+ return "The Resource-Bundle with id '"
+ + bundleName
+ + "' has been "
+ + "excluded from Internationalization. Based on this fact, no internationalization "
+ + "supoort is provided for this Resource-Bundle. Performing this action, internationalization "
+ + "support for '" + bundleName + "' will be enabled";
}
@Override
public Image getImage() {
- // TODO Auto-generated method stub
- return null;
+ // TODO Auto-generated method stub
+ return null;
}
@Override
public String getLabel() {
- return "Include excluded Resource-Bundle '" + bundleName + "'";
+ return "Include excluded Resource-Bundle '" + bundleName + "'";
}
@Override
public void run(final IMarker marker) {
- IWorkbench wb = PlatformUI.getWorkbench();
- IProgressService ps = wb.getProgressService();
- try {
- ps.busyCursorWhile(new IRunnableWithProgress() {
- public void run(IProgressMonitor pm) {
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(marker.getResource().getProject());
- pm.beginTask("Including resources to Internationalization",
- bundleResources.size());
- for (IResource resource : bundleResources) {
- manager.includeResource(resource, pm);
- pm.worked(1);
- }
- pm.done();
- }
- });
- } catch (Exception e) {
- }
+ IWorkbench wb = PlatformUI.getWorkbench();
+ IProgressService ps = wb.getProgressService();
+ try {
+ ps.busyCursorWhile(new IRunnableWithProgress() {
+ public void run(IProgressMonitor pm) {
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(marker.getResource().getProject());
+ pm.beginTask("Including resources to Internationalization",
+ bundleResources.size());
+ for (IResource resource : bundleResources) {
+ manager.includeResource(resource, pm);
+ pm.worked(1);
+ }
+ pm.done();
+ }
+ });
+ } catch (Exception e) {
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/EditorUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/EditorUtils.java
index 151a854..ae220db 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/EditorUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/EditorUtils.java
@@ -25,166 +25,166 @@
public class EditorUtils {
- /** Marker constants **/
- public static final String MARKER_ID = Activator.PLUGIN_ID
- + ".StringLiteralAuditMarker";
- public static final String RB_MARKER_ID = Activator.PLUGIN_ID
- + ".ResourceBundleAuditMarker";
+ /** Marker constants **/
+ public static final String MARKER_ID = Activator.PLUGIN_ID
+ + ".StringLiteralAuditMarker";
+ public static final String RB_MARKER_ID = Activator.PLUGIN_ID
+ + ".ResourceBundleAuditMarker";
- /** Editor ids **/
- public static final String RESOURCE_BUNDLE_EDITOR = "com.essiembre.rbe.eclipse.editor.ResourceBundleEditor";
+ /** Editor ids **/
+ public static final String RESOURCE_BUNDLE_EDITOR = "com.essiembre.rbe.eclipse.editor.ResourceBundleEditor";
- public static IEditorPart openEditor(IWorkbenchPage page, IFile file,
- String editor) {
- // open the rb-editor for this file type
- try {
- return IDE.openEditor(page, file, editor);
- } catch (PartInitException e) {
- Logger.logError(e);
- }
- return null;
- }
+ public static IEditorPart openEditor(IWorkbenchPage page, IFile file,
+ String editor) {
+ // open the rb-editor for this file type
+ try {
+ return IDE.openEditor(page, file, editor);
+ } catch (PartInitException e) {
+ Logger.logError(e);
+ }
+ return null;
+ }
- public static IEditorPart openEditor(IWorkbenchPage page, IFile file,
- String editor, String key) {
- // open the rb-editor for this file type and selects given msg key
- IEditorPart part = openEditor(page, file, editor);
- if (part instanceof IMessagesEditor) {
- IMessagesEditor msgEditor = (IMessagesEditor) part;
- msgEditor.setSelectedKey(key);
- }
- return part;
- }
+ public static IEditorPart openEditor(IWorkbenchPage page, IFile file,
+ String editor, String key) {
+ // open the rb-editor for this file type and selects given msg key
+ IEditorPart part = openEditor(page, file, editor);
+ if (part instanceof IMessagesEditor) {
+ IMessagesEditor msgEditor = (IMessagesEditor) part;
+ msgEditor.setSelectedKey(key);
+ }
+ return part;
+ }
- public static void updateMarker(IMarker marker) {
- FileEditorInput input = new FileEditorInput(
- (IFile) marker.getResource());
+ public static void updateMarker(IMarker marker) {
+ FileEditorInput input = new FileEditorInput(
+ (IFile) marker.getResource());
- AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) getAnnotationModel(marker);
- IDocument doc = JavaUI.getDocumentProvider().getDocument(input);
+ AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) getAnnotationModel(marker);
+ IDocument doc = JavaUI.getDocumentProvider().getDocument(input);
- try {
- model.updateMarker(doc, marker, getCurPosition(marker, model));
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
+ try {
+ model.updateMarker(doc, marker, getCurPosition(marker, model));
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
- public static IAnnotationModel getAnnotationModel(IMarker marker) {
- FileEditorInput input = new FileEditorInput(
- (IFile) marker.getResource());
+ public static IAnnotationModel getAnnotationModel(IMarker marker) {
+ FileEditorInput input = new FileEditorInput(
+ (IFile) marker.getResource());
- return JavaUI.getDocumentProvider().getAnnotationModel(input);
- }
+ return JavaUI.getDocumentProvider().getAnnotationModel(input);
+ }
- private static Position getCurPosition(IMarker marker,
- IAnnotationModel model) {
- Iterator iter = model.getAnnotationIterator();
- Logger.logInfo("Updates Position!");
- while (iter.hasNext()) {
- Object curr = iter.next();
- if (curr instanceof SimpleMarkerAnnotation) {
- SimpleMarkerAnnotation annot = (SimpleMarkerAnnotation) curr;
- if (marker.equals(annot.getMarker())) {
- return model.getPosition(annot);
- }
- }
- }
- return null;
- }
+ private static Position getCurPosition(IMarker marker,
+ IAnnotationModel model) {
+ Iterator iter = model.getAnnotationIterator();
+ Logger.logInfo("Updates Position!");
+ while (iter.hasNext()) {
+ Object curr = iter.next();
+ if (curr instanceof SimpleMarkerAnnotation) {
+ SimpleMarkerAnnotation annot = (SimpleMarkerAnnotation) curr;
+ if (marker.equals(annot.getMarker())) {
+ return model.getPosition(annot);
+ }
+ }
+ }
+ return null;
+ }
- public static boolean deleteAuditMarkersForResource(IResource resource) {
- try {
- if (resource != null && resource.exists()) {
- resource.deleteMarkers(MARKER_ID, false,
- IResource.DEPTH_INFINITE);
- deleteAllAuditRBMarkersFromRB(resource);
- }
- } catch (CoreException e) {
- Logger.logError(e);
- return false;
- }
- return true;
- }
+ public static boolean deleteAuditMarkersForResource(IResource resource) {
+ try {
+ if (resource != null && resource.exists()) {
+ resource.deleteMarkers(MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ deleteAllAuditRBMarkersFromRB(resource);
+ }
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return false;
+ }
+ return true;
+ }
- /*
- * Delete all RB_MARKER from the hole resourcebundle
- */
- private static boolean deleteAllAuditRBMarkersFromRB(IResource resource)
- throws CoreException {
- // if (resource.findMarkers(RB_MARKER_ID, false,
- // IResource.DEPTH_INFINITE).length > 0)
- if (RBFileUtils.isResourceBundleFile(resource)) {
- String rbId = RBFileUtils
- .getCorrespondingResourceBundleId((IFile) resource);
- if (rbId == null) {
- return true; // file in no resourcebundle
- }
+ /*
+ * Delete all RB_MARKER from the hole resourcebundle
+ */
+ private static boolean deleteAllAuditRBMarkersFromRB(IResource resource)
+ throws CoreException {
+ // if (resource.findMarkers(RB_MARKER_ID, false,
+ // IResource.DEPTH_INFINITE).length > 0)
+ if (RBFileUtils.isResourceBundleFile(resource)) {
+ String rbId = RBFileUtils
+ .getCorrespondingResourceBundleId((IFile) resource);
+ if (rbId == null) {
+ return true; // file in no resourcebundle
+ }
- ResourceBundleManager rbmanager = ResourceBundleManager
- .getManager(resource.getProject());
- for (IResource r : rbmanager.getResourceBundles(rbId)) {
- r.deleteMarkers(RB_MARKER_ID, false, IResource.DEPTH_INFINITE);
- }
- }
- return true;
- }
+ ResourceBundleManager rbmanager = ResourceBundleManager
+ .getManager(resource.getProject());
+ for (IResource r : rbmanager.getResourceBundles(rbId)) {
+ r.deleteMarkers(RB_MARKER_ID, false, IResource.DEPTH_INFINITE);
+ }
+ }
+ return true;
+ }
- public static void reportToMarker(String string, ILocation problem,
- int cause, String key, ILocation data, String context) {
- try {
- IMarker marker = problem.getFile().createMarker(MARKER_ID);
- marker.setAttribute(IMarker.MESSAGE, string);
- marker.setAttribute(IMarker.CHAR_START, problem.getStartPos());
- marker.setAttribute(IMarker.CHAR_END, problem.getEndPos());
- marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
- marker.setAttribute("cause", cause);
- marker.setAttribute("key", key);
- marker.setAttribute("context", context);
- if (data != null) {
- marker.setAttribute("bundleName", data.getLiteral());
- marker.setAttribute("bundleStart", data.getStartPos());
- marker.setAttribute("bundleEnd", data.getEndPos());
- }
+ public static void reportToMarker(String string, ILocation problem,
+ int cause, String key, ILocation data, String context) {
+ try {
+ IMarker marker = problem.getFile().createMarker(MARKER_ID);
+ marker.setAttribute(IMarker.MESSAGE, string);
+ marker.setAttribute(IMarker.CHAR_START, problem.getStartPos());
+ marker.setAttribute(IMarker.CHAR_END, problem.getEndPos());
+ marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
+ marker.setAttribute("cause", cause);
+ marker.setAttribute("key", key);
+ marker.setAttribute("context", context);
+ if (data != null) {
+ marker.setAttribute("bundleName", data.getLiteral());
+ marker.setAttribute("bundleStart", data.getStartPos());
+ marker.setAttribute("bundleEnd", data.getEndPos());
+ }
- // TODO: init attributes
- marker.setAttribute("stringLiteral", string);
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
+ // TODO: init attributes
+ marker.setAttribute("stringLiteral", string);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
- Logger.logInfo(string);
- }
+ Logger.logInfo(string);
+ }
- public static void reportToRBMarker(String string, ILocation problem,
- int cause, String key, String problemPartnerFile, ILocation data,
- String context) {
- try {
- if (!problem.getFile().exists()) {
- return;
- }
- IMarker marker = problem.getFile().createMarker(RB_MARKER_ID);
- marker.setAttribute(IMarker.MESSAGE, string);
- marker.setAttribute(IMarker.LINE_NUMBER, problem.getStartPos()); // TODO
- // better-dirty
- // implementation
- marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
- marker.setAttribute("cause", cause);
- marker.setAttribute("key", key);
- marker.setAttribute("context", context);
- if (data != null) {
- marker.setAttribute("language", data.getLiteral());
- marker.setAttribute("bundleLine", data.getStartPos());
- }
- marker.setAttribute("stringLiteral", string);
- marker.setAttribute("problemPartner", problemPartnerFile);
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
+ public static void reportToRBMarker(String string, ILocation problem,
+ int cause, String key, String problemPartnerFile, ILocation data,
+ String context) {
+ try {
+ if (!problem.getFile().exists()) {
+ return;
+ }
+ IMarker marker = problem.getFile().createMarker(RB_MARKER_ID);
+ marker.setAttribute(IMarker.MESSAGE, string);
+ marker.setAttribute(IMarker.LINE_NUMBER, problem.getStartPos()); // TODO
+ // better-dirty
+ // implementation
+ marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
+ marker.setAttribute("cause", cause);
+ marker.setAttribute("key", key);
+ marker.setAttribute("context", context);
+ if (data != null) {
+ marker.setAttribute("language", data.getLiteral());
+ marker.setAttribute("bundleLine", data.getStartPos());
+ }
+ marker.setAttribute("stringLiteral", string);
+ marker.setAttribute("problemPartner", problemPartnerFile);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
- Logger.logInfo(string);
- }
+ Logger.logInfo(string);
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/FontUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/FontUtils.java
index 858644a..e7b66d4 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/FontUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/FontUtils.java
@@ -27,8 +27,8 @@
* @return system color
*/
public static Color getSystemColor(int colorId) {
- return Activator.getDefault().getWorkbench().getDisplay()
- .getSystemColor(colorId);
+ return Activator.getDefault().getWorkbench().getDisplay()
+ .getSystemColor(colorId);
}
/**
@@ -42,8 +42,8 @@
* @return newly created font
*/
public static Font createFont(Control control, int style) {
- // TODO consider dropping in favor of control-less version?
- return createFont(control, style, 0);
+ // TODO consider dropping in favor of control-less version?
+ return createFont(control, style, 0);
}
/**
@@ -59,13 +59,13 @@
* @return newly created font
*/
public static Font createFont(Control control, int style, int relSize) {
- // TODO consider dropping in favor of control-less version?
- FontData[] fontData = control.getFont().getFontData();
- for (int i = 0; i < fontData.length; i++) {
- fontData[i].setHeight(fontData[i].getHeight() + relSize);
- fontData[i].setStyle(style);
- }
- return new Font(control.getDisplay(), fontData);
+ // TODO consider dropping in favor of control-less version?
+ FontData[] fontData = control.getFont().getFontData();
+ for (int i = 0; i < fontData.length; i++) {
+ fontData[i].setHeight(fontData[i].getHeight() + relSize);
+ fontData[i].setStyle(style);
+ }
+ return new Font(control.getDisplay(), fontData);
}
/**
@@ -77,7 +77,7 @@
* @return newly created font
*/
public static Font createFont(int style) {
- return createFont(style, 0);
+ return createFont(style, 0);
}
/**
@@ -91,12 +91,12 @@
* @return newly created font
*/
public static Font createFont(int style, int relSize) {
- Display display = Activator.getDefault().getWorkbench().getDisplay();
- FontData[] fontData = display.getSystemFont().getFontData();
- for (int i = 0; i < fontData.length; i++) {
- fontData[i].setHeight(fontData[i].getHeight() + relSize);
- fontData[i].setStyle(style);
- }
- return new Font(display, fontData);
+ Display display = Activator.getDefault().getWorkbench().getDisplay();
+ FontData[] fontData = display.getSystemFont().getFontData();
+ for (int i = 0; i < fontData.length; i++) {
+ fontData[i].setHeight(fontData[i].getHeight() + relSize);
+ fontData[i].setStyle(style);
+ }
+ return new Font(display, fontData);
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ImageUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ImageUtils.java
index 409e374..62e8ddf 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ImageUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ImageUtils.java
@@ -17,47 +17,47 @@
public final class ImageUtils {
- /** Name of resource bundle image. */
- public static final String IMAGE_RESOURCE_BUNDLE = "icons/resourcebundle.gif"; //$NON-NLS-1$
- /** Name of properties file image. */
- public static final String IMAGE_PROPERTIES_FILE = "icons/propertiesfile.gif"; //$NON-NLS-1$
- /** Name of properties file entry image */
- public static final String IMAGE_PROPERTIES_FILE_ENTRY = "icons/key.gif";
- /** Name of new properties file image. */
- public static final String IMAGE_NEW_PROPERTIES_FILE = "icons/newpropertiesfile.gif"; //$NON-NLS-1$
- /** Name of hierarchical layout image. */
- public static final String IMAGE_LAYOUT_HIERARCHICAL = "icons/hierarchicalLayout.gif"; //$NON-NLS-1$
- /** Name of flat layout image. */
- public static final String IMAGE_LAYOUT_FLAT = "icons/flatLayout.gif"; //$NON-NLS-1$
- public static final String IMAGE_INCOMPLETE_ENTRIES = "icons/incomplete.gif"; //$NON-NLS-1$
- public static final String IMAGE_EXCLUDED_RESOURCE_ON = "icons/int.gif"; //$NON-NLS-1$
- public static final String IMAGE_EXCLUDED_RESOURCE_OFF = "icons/exclude.png"; //$NON-NLS-1$
- public static final String ICON_RESOURCE = "icons/Resource16_small.png";
- public static final String ICON_RESOURCE_INCOMPLETE = "icons/Resource16_warning_small.png";
+ /** Name of resource bundle image. */
+ public static final String IMAGE_RESOURCE_BUNDLE = "icons/resourcebundle.gif"; //$NON-NLS-1$
+ /** Name of properties file image. */
+ public static final String IMAGE_PROPERTIES_FILE = "icons/propertiesfile.gif"; //$NON-NLS-1$
+ /** Name of properties file entry image */
+ public static final String IMAGE_PROPERTIES_FILE_ENTRY = "icons/key.gif";
+ /** Name of new properties file image. */
+ public static final String IMAGE_NEW_PROPERTIES_FILE = "icons/newpropertiesfile.gif"; //$NON-NLS-1$
+ /** Name of hierarchical layout image. */
+ public static final String IMAGE_LAYOUT_HIERARCHICAL = "icons/hierarchicalLayout.gif"; //$NON-NLS-1$
+ /** Name of flat layout image. */
+ public static final String IMAGE_LAYOUT_FLAT = "icons/flatLayout.gif"; //$NON-NLS-1$
+ public static final String IMAGE_INCOMPLETE_ENTRIES = "icons/incomplete.gif"; //$NON-NLS-1$
+ public static final String IMAGE_EXCLUDED_RESOURCE_ON = "icons/int.gif"; //$NON-NLS-1$
+ public static final String IMAGE_EXCLUDED_RESOURCE_OFF = "icons/exclude.png"; //$NON-NLS-1$
+ public static final String ICON_RESOURCE = "icons/Resource16_small.png";
+ public static final String ICON_RESOURCE_INCOMPLETE = "icons/Resource16_warning_small.png";
- /** Image registry. */
- private static final ImageRegistry imageRegistry = new ImageRegistry();
+ /** Image registry. */
+ private static final ImageRegistry imageRegistry = new ImageRegistry();
- /**
- * Constructor.
- */
- private ImageUtils() {
- super();
- }
+ /**
+ * Constructor.
+ */
+ private ImageUtils() {
+ super();
+ }
- /**
- * Gets an image.
- *
- * @param imageName
- * image name
- * @return image
- */
- public static Image getImage(String imageName) {
- Image image = imageRegistry.get(imageName);
- if (image == null) {
- image = Activator.getImageDescriptor(imageName).createImage();
- imageRegistry.put(imageName, image);
- }
- return image;
- }
+ /**
+ * Gets an image.
+ *
+ * @param imageName
+ * image name
+ * @return image
+ */
+ public static Image getImage(String imageName) {
+ Image image = imageRegistry.get(imageName);
+ if (image == null) {
+ image = Activator.getImageDescriptor(imageName).createImage();
+ imageRegistry.put(imageName, image);
+ }
+ return image;
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LanguageUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LanguageUtils.java
index ecadce3..c4809c9 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LanguageUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LanguageUtils.java
@@ -34,21 +34,21 @@
private static final String INITIALISATION_STRING = PropertiesSerializer.GENERATED_BY;
private static IFile createFile(IContainer container, String fileName,
- IProgressMonitor monitor) throws CoreException, IOException {
- if (!container.exists()) {
- if (container instanceof IFolder) {
- ((IFolder) container).create(false, false, monitor);
- }
- }
+ IProgressMonitor monitor) throws CoreException, IOException {
+ if (!container.exists()) {
+ if (container instanceof IFolder) {
+ ((IFolder) container).create(false, false, monitor);
+ }
+ }
- IFile file = container.getFile(new Path(fileName));
- if (!file.exists()) {
- InputStream s = new StringBufferInputStream(INITIALISATION_STRING);
- file.create(s, true, monitor);
- s.close();
- }
+ IFile file = container.getFile(new Path(fileName));
+ if (!file.exists()) {
+ InputStream s = new StringBufferInputStream(INITIALISATION_STRING);
+ file.create(s, true, monitor);
+ s.close();
+ }
- return file;
+ return file;
}
/**
@@ -61,58 +61,58 @@
* @param locale
*/
public static void addLanguageToResourceBundle(IProject project,
- final String rbId, final Locale locale) {
- ResourceBundleManager rbManager = ResourceBundleManager
- .getManager(project);
+ final String rbId, final Locale locale) {
+ ResourceBundleManager rbManager = ResourceBundleManager
+ .getManager(project);
- if (rbManager.getProvidedLocales(rbId).contains(locale)) {
- return;
- }
+ if (rbManager.getProvidedLocales(rbId).contains(locale)) {
+ return;
+ }
- final IResource file = rbManager.getRandomFile(rbId);
- final IContainer c = ResourceUtils.getCorrespondingFolders(
- file.getParent(), project);
+ final IResource file = rbManager.getRandomFile(rbId);
+ final IContainer c = ResourceUtils.getCorrespondingFolders(
+ file.getParent(), project);
- new Job("create new propertfile") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- String newFilename = ResourceBundleManager
- .getResourceBundleName(file);
- if (locale.getLanguage() != null
- && !locale.getLanguage().equalsIgnoreCase(
- ResourceBundleManager.defaultLocaleTag)
- && !locale.getLanguage().equals("")) {
- newFilename += "_" + locale.getLanguage();
- }
- if (locale.getCountry() != null
- && !locale.getCountry().equals("")) {
- newFilename += "_" + locale.getCountry();
- }
- if (locale.getVariant() != null
- && !locale.getCountry().equals("")) {
- newFilename += "_" + locale.getVariant();
- }
- newFilename += ".properties";
+ new Job("create new propertfile") {
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ try {
+ String newFilename = ResourceBundleManager
+ .getResourceBundleName(file);
+ if (locale.getLanguage() != null
+ && !locale.getLanguage().equalsIgnoreCase(
+ ResourceBundleManager.defaultLocaleTag)
+ && !locale.getLanguage().equals("")) {
+ newFilename += "_" + locale.getLanguage();
+ }
+ if (locale.getCountry() != null
+ && !locale.getCountry().equals("")) {
+ newFilename += "_" + locale.getCountry();
+ }
+ if (locale.getVariant() != null
+ && !locale.getCountry().equals("")) {
+ newFilename += "_" + locale.getVariant();
+ }
+ newFilename += ".properties";
- createFile(c, newFilename, monitor);
- } catch (CoreException e) {
- Logger.logError(
- "File for locale "
- + locale
- + " could not be created in ResourceBundle "
- + rbId, e);
- } catch (IOException e) {
- Logger.logError(
- "File for locale "
- + locale
- + " could not be created in ResourceBundle "
- + rbId, e);
- }
- monitor.done();
- return Status.OK_STATUS;
- }
- }.schedule();
+ createFile(c, newFilename, monitor);
+ } catch (CoreException e) {
+ Logger.logError(
+ "File for locale "
+ + locale
+ + " could not be created in ResourceBundle "
+ + rbId, e);
+ } catch (IOException e) {
+ Logger.logError(
+ "File for locale "
+ + locale
+ + " could not be created in ResourceBundle "
+ + rbId, e);
+ }
+ monitor.done();
+ return Status.OK_STATUS;
+ }
+ }.schedule();
}
/**
@@ -124,14 +124,14 @@
* @param locale
*/
public static void addLanguageToProject(IProject project, Locale locale) {
- ResourceBundleManager rbManager = ResourceBundleManager
- .getManager(project);
+ ResourceBundleManager rbManager = ResourceBundleManager
+ .getManager(project);
- // Audit if all resourecbundles provide this locale. if not - add new
- // file
- for (String rbId : rbManager.getResourceBundleIdentifiers()) {
- addLanguageToResourceBundle(project, rbId, locale);
- }
+ // Audit if all resourecbundles provide this locale. if not - add new
+ // file
+ for (String rbId : rbManager.getResourceBundleIdentifiers()) {
+ addLanguageToResourceBundle(project, rbId, locale);
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LocaleUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LocaleUtils.java
index 6f0bb4f..6544b7a 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LocaleUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LocaleUtils.java
@@ -18,33 +18,33 @@
public class LocaleUtils {
public static Locale getLocaleByDisplayName(Set<Locale> locales,
- String displayName) {
- for (Locale l : locales) {
- String name = l == null ? ResourceBundleManager.defaultLocaleTag
- : l.getDisplayName();
- if (name.equals(displayName)
- || (name.trim().length() == 0 && displayName
- .equals(ResourceBundleManager.defaultLocaleTag))) {
- return l;
- }
- }
+ String displayName) {
+ for (Locale l : locales) {
+ String name = l == null ? ResourceBundleManager.defaultLocaleTag
+ : l.getDisplayName();
+ if (name.equals(displayName)
+ || (name.trim().length() == 0 && displayName
+ .equals(ResourceBundleManager.defaultLocaleTag))) {
+ return l;
+ }
+ }
- return null;
+ return null;
}
public static boolean containsLocaleByDisplayName(Set<Locale> locales,
- String displayName) {
- for (Locale l : locales) {
- String name = l == null ? ResourceBundleManager.defaultLocaleTag
- : l.getDisplayName();
- if (name.equals(displayName)
- || (name.trim().length() == 0 && displayName
- .equals(ResourceBundleManager.defaultLocaleTag))) {
- return true;
- }
- }
+ String displayName) {
+ for (Locale l : locales) {
+ String name = l == null ? ResourceBundleManager.defaultLocaleTag
+ : l.getDisplayName();
+ if (name.equals(displayName)
+ || (name.trim().length() == 0 && displayName
+ .equals(ResourceBundleManager.defaultLocaleTag))) {
+ return true;
+ }
+ }
- return false;
+ return false;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/RBFileUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/RBFileUtils.java
index 5f8ff62..9c4d008 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/RBFileUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/RBFileUtils.java
@@ -45,45 +45,45 @@
* Returns true if a file is a ResourceBundle-file
*/
public static boolean isResourceBundleFile(IResource file) {
- boolean isValied = false;
+ boolean isValied = false;
- if (file != null && file instanceof IFile && !file.isDerived()
- && file.getFileExtension() != null
- && file.getFileExtension().equalsIgnoreCase("properties")) {
- isValied = true;
+ if (file != null && file instanceof IFile && !file.isDerived()
+ && file.getFileExtension() != null
+ && file.getFileExtension().equalsIgnoreCase("properties")) {
+ isValied = true;
- // Check if file is not in the blacklist
- IPreferenceStore pref = null;
- if (Activator.getDefault() != null) {
- pref = Activator.getDefault().getPreferenceStore();
- }
+ // Check if file is not in the blacklist
+ IPreferenceStore pref = null;
+ if (Activator.getDefault() != null) {
+ pref = Activator.getDefault().getPreferenceStore();
+ }
- if (pref != null) {
- List<CheckItem> list = TapiJIPreferences
- .getNonRbPatternAsList();
- for (CheckItem item : list) {
- if (item.getChecked()
- && file.getFullPath().toString()
- .matches(item.getName())) {
- isValied = false;
+ if (pref != null) {
+ List<CheckItem> list = TapiJIPreferences
+ .getNonRbPatternAsList();
+ for (CheckItem item : list) {
+ if (item.getChecked()
+ && file.getFullPath().toString()
+ .matches(item.getName())) {
+ isValied = false;
- // if properties-file is not RB-file and has
- // ResouceBundleMarker, deletes all ResouceBundleMarker
- // of the file
- if (org.eclipse.babel.tapiji.tools.core.util.RBFileUtils
- .hasResourceBundleMarker(file)) {
- try {
- file.deleteMarkers(EditorUtils.RB_MARKER_ID,
- true, IResource.DEPTH_INFINITE);
- } catch (CoreException e) {
- }
- }
- }
- }
- }
- }
+ // if properties-file is not RB-file and has
+ // ResouceBundleMarker, deletes all ResouceBundleMarker
+ // of the file
+ if (org.eclipse.babel.tapiji.tools.core.util.RBFileUtils
+ .hasResourceBundleMarker(file)) {
+ try {
+ file.deleteMarkers(EditorUtils.RB_MARKER_ID,
+ true, IResource.DEPTH_INFINITE);
+ } catch (CoreException e) {
+ }
+ }
+ }
+ }
+ }
+ }
- return isValied;
+ return isValied;
}
/**
@@ -91,21 +91,21 @@
* @return Set with all ResourceBundles in this container
*/
public static Set<String> getResourceBundleIds(IContainer container) {
- Set<String> resourcebundles = new HashSet<String>();
+ Set<String> resourcebundles = new HashSet<String>();
- try {
- for (IResource r : container.members()) {
- if (r instanceof IFile) {
- String resourcebundle = getCorrespondingResourceBundleId((IFile) r);
- if (resourcebundle != null) {
- resourcebundles.add(resourcebundle);
- }
- }
- }
- } catch (CoreException e) {/* resourcebundle.size()==0 */
- }
+ try {
+ for (IResource r : container.members()) {
+ if (r instanceof IFile) {
+ String resourcebundle = getCorrespondingResourceBundleId((IFile) r);
+ if (resourcebundle != null) {
+ resourcebundles.add(resourcebundle);
+ }
+ }
+ }
+ } catch (CoreException e) {/* resourcebundle.size()==0 */
+ }
- return resourcebundles;
+ return resourcebundles;
}
/**
@@ -116,20 +116,20 @@
*/
// TODO integrate in ResourceBundleManager
public static String getCorrespondingResourceBundleId(IFile file) {
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(file
- .getProject());
- String possibleRBId = null;
+ ResourceBundleManager rbmanager = ResourceBundleManager.getManager(file
+ .getProject());
+ String possibleRBId = null;
- if (isResourceBundleFile(file)) {
- possibleRBId = ResourceBundleManager.getResourceBundleId(file);
+ if (isResourceBundleFile(file)) {
+ possibleRBId = ResourceBundleManager.getResourceBundleId(file);
- for (String rbId : rbmanager.getResourceBundleIdentifiers()) {
- if (possibleRBId.equals(rbId)) {
- return possibleRBId;
- }
- }
- }
- return null;
+ for (String rbId : rbmanager.getResourceBundleIdentifiers()) {
+ if (possibleRBId.equals(rbId)) {
+ return possibleRBId;
+ }
+ }
+ }
+ return null;
}
/**
@@ -141,31 +141,31 @@
* @param locale
*/
public static void removeFileFromResourceBundle(IProject project,
- String rbId, Locale locale) {
- ResourceBundleManager rbManager = ResourceBundleManager
- .getManager(project);
+ String rbId, Locale locale) {
+ ResourceBundleManager rbManager = ResourceBundleManager
+ .getManager(project);
- if (!rbManager.getProvidedLocales(rbId).contains(locale)) {
- return;
- }
+ if (!rbManager.getProvidedLocales(rbId).contains(locale)) {
+ return;
+ }
- final IFile file = rbManager.getResourceBundleFile(rbId, locale);
- final String filename = file.getName();
+ final IFile file = rbManager.getResourceBundleFile(rbId, locale);
+ final String filename = file.getName();
- new Job("remove properties-file") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- EditorUtils.deleteAuditMarkersForResource(file);
- file.delete(true, monitor);
- } catch (CoreException e) {
- // MessageDialog.openError(Display.getCurrent().getActiveShell(),
- // "Confirm", "File could not be deleted");
- Logger.logError("File could not be deleted", e);
- }
- return Status.OK_STATUS;
- }
- }.schedule();
+ new Job("remove properties-file") {
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ try {
+ EditorUtils.deleteAuditMarkersForResource(file);
+ file.delete(true, monitor);
+ } catch (CoreException e) {
+ // MessageDialog.openError(Display.getCurrent().getActiveShell(),
+ // "Confirm", "File could not be deleted");
+ Logger.logError("File could not be deleted", e);
+ }
+ return Status.OK_STATUS;
+ }
+ }.schedule();
}
/**
@@ -177,12 +177,12 @@
* @return
*/
public static void removeLanguageFromProject(IProject project, Locale locale) {
- ResourceBundleManager rbManager = ResourceBundleManager
- .getManager(project);
+ ResourceBundleManager rbManager = ResourceBundleManager
+ .getManager(project);
- for (String rbId : rbManager.getResourceBundleIdentifiers()) {
- removeFileFromResourceBundle(project, rbId, locale);
- }
+ for (String rbId : rbManager.getResourceBundleIdentifiers()) {
+ removeFileFromResourceBundle(project, rbId, locale);
+ }
}
@@ -190,60 +190,60 @@
* @return the locale of a given properties-file
*/
public static Locale getLocale(IFile file) {
- String localeID = file.getName();
- localeID = localeID.substring(0,
- localeID.length() - "properties".length() - 1);
- String baseBundleName = ResourceBundleManager
- .getResourceBundleName(file);
+ String localeID = file.getName();
+ localeID = localeID.substring(0,
+ localeID.length() - "properties".length() - 1);
+ String baseBundleName = ResourceBundleManager
+ .getResourceBundleName(file);
- Locale locale;
- if (localeID.length() == baseBundleName.length()) {
- locale = null; // Default locale
- } else {
- localeID = localeID.substring(baseBundleName.length() + 1);
- String[] localeTokens = localeID.split("_");
- switch (localeTokens.length) {
- case 1:
- locale = new Locale(localeTokens[0]);
- break;
- case 2:
- locale = new Locale(localeTokens[0], localeTokens[1]);
- break;
- case 3:
- locale = new Locale(localeTokens[0], localeTokens[1],
- localeTokens[2]);
- break;
- default:
- locale = new Locale("");
- break;
- }
- }
- return locale;
+ Locale locale;
+ if (localeID.length() == baseBundleName.length()) {
+ locale = null; // Default locale
+ } else {
+ localeID = localeID.substring(baseBundleName.length() + 1);
+ String[] localeTokens = localeID.split("_");
+ switch (localeTokens.length) {
+ case 1:
+ locale = new Locale(localeTokens[0]);
+ break;
+ case 2:
+ locale = new Locale(localeTokens[0], localeTokens[1]);
+ break;
+ case 3:
+ locale = new Locale(localeTokens[0], localeTokens[1],
+ localeTokens[2]);
+ break;
+ default:
+ locale = new Locale("");
+ break;
+ }
+ }
+ return locale;
}
/**
* @return number of ResourceBundles in the subtree
*/
public static int countRecursiveResourceBundle(IContainer container) {
- return getSubResourceBundle(container).size();
+ return getSubResourceBundle(container).size();
}
private static List<String> getSubResourceBundle(IContainer container) {
- ResourceBundleManager rbmanager = ResourceBundleManager
- .getManager(container.getProject());
+ ResourceBundleManager rbmanager = ResourceBundleManager
+ .getManager(container.getProject());
- String conatinerId = container.getFullPath().toString();
- List<String> subResourceBundles = new ArrayList<String>();
+ String conatinerId = container.getFullPath().toString();
+ List<String> subResourceBundles = new ArrayList<String>();
- for (String rbId : rbmanager.getResourceBundleIdentifiers()) {
- for (IResource r : rbmanager.getResourceBundles(rbId)) {
- if (r.getFullPath().toString().contains(conatinerId)
- && (!subResourceBundles.contains(rbId))) {
- subResourceBundles.add(rbId);
- }
- }
- }
- return subResourceBundles;
+ for (String rbId : rbmanager.getResourceBundleIdentifiers()) {
+ for (IResource r : rbmanager.getResourceBundles(rbId)) {
+ if (r.getFullPath().toString().contains(conatinerId)
+ && (!subResourceBundles.contains(rbId))) {
+ subResourceBundles.add(rbId);
+ }
+ }
+ }
+ return subResourceBundles;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ResourceUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ResourceUtils.java
index d43d840..2aa36fb 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ResourceUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ResourceUtils.java
@@ -25,56 +25,56 @@
private final static String REGEXP_RESOURCE_NO_BUNDLENAME = "[^\\p{Alnum}\\.]*";
public static boolean isValidResourceKey(String key) {
- boolean isValid = false;
+ boolean isValid = false;
- if (key != null && key.trim().length() > 0) {
- isValid = key.matches(REGEXP_RESOURCE_KEY);
- }
+ if (key != null && key.trim().length() > 0) {
+ isValid = key.matches(REGEXP_RESOURCE_KEY);
+ }
- return isValid;
+ return isValid;
}
public static String deriveNonExistingRBName(String nameProposal,
- ResourceBundleManager manager) {
- // Adapt the proposal to the requirements for Resource-Bundle names
- nameProposal = nameProposal.replaceAll(REGEXP_RESOURCE_NO_BUNDLENAME,
- "");
+ ResourceBundleManager manager) {
+ // Adapt the proposal to the requirements for Resource-Bundle names
+ nameProposal = nameProposal.replaceAll(REGEXP_RESOURCE_NO_BUNDLENAME,
+ "");
- int i = 0;
- do {
- if (manager.getResourceBundleIdentifiers().contains(nameProposal)
- || nameProposal.length() == 0) {
- nameProposal = nameProposal + (++i);
- } else {
- break;
- }
- } while (true);
+ int i = 0;
+ do {
+ if (manager.getResourceBundleIdentifiers().contains(nameProposal)
+ || nameProposal.length() == 0) {
+ nameProposal = nameProposal + (++i);
+ } else {
+ break;
+ }
+ } while (true);
- return nameProposal;
+ return nameProposal;
}
public static boolean isJavaCompUnit(IResource res) {
- boolean result = false;
+ boolean result = false;
- if (res.getType() == IResource.FILE && !res.isDerived()
- && res.getFileExtension().equalsIgnoreCase("java")) {
- result = true;
- }
+ if (res.getType() == IResource.FILE && !res.isDerived()
+ && res.getFileExtension().equalsIgnoreCase("java")) {
+ result = true;
+ }
- return result;
+ return result;
}
public static boolean isJSPResource(IResource res) {
- boolean result = false;
+ boolean result = false;
- if (res.getType() == IResource.FILE
- && !res.isDerived()
- && (res.getFileExtension().equalsIgnoreCase("jsp") || res
- .getFileExtension().equalsIgnoreCase("xhtml"))) {
- result = true;
- }
+ if (res.getType() == IResource.FILE
+ && !res.isDerived()
+ && (res.getFileExtension().equalsIgnoreCase("jsp") || res
+ .getFileExtension().equalsIgnoreCase("xhtml"))) {
+ result = true;
+ }
- return result;
+ return result;
}
/**
@@ -85,17 +85,17 @@
* @return List of
*/
public static List<IContainer> getCorrespondingFolders(
- IContainer baseFolder, List<IProject> targetProjects) {
- List<IContainer> correspondingFolder = new ArrayList<IContainer>();
+ IContainer baseFolder, List<IProject> targetProjects) {
+ List<IContainer> correspondingFolder = new ArrayList<IContainer>();
- for (IProject p : targetProjects) {
- IContainer c = getCorrespondingFolders(baseFolder, p);
- if (c.exists()) {
- correspondingFolder.add(c);
- }
- }
+ for (IProject p : targetProjects) {
+ IContainer c = getCorrespondingFolders(baseFolder, p);
+ if (c.exists()) {
+ correspondingFolder.add(c);
+ }
+ }
- return correspondingFolder;
+ return correspondingFolder;
}
/**
@@ -106,15 +106,15 @@
* Container doesn't must exist.
*/
public static IContainer getCorrespondingFolders(IContainer baseFolder,
- IProject targetProject) {
- IPath relativ_folder = baseFolder.getFullPath().makeRelativeTo(
- baseFolder.getProject().getFullPath());
+ IProject targetProject) {
+ IPath relativ_folder = baseFolder.getFullPath().makeRelativeTo(
+ baseFolder.getProject().getFullPath());
- if (!relativ_folder.isEmpty()) {
- return targetProject.getFolder(relativ_folder);
- } else {
- return targetProject;
- }
+ if (!relativ_folder.isEmpty()) {
+ return targetProject.getFolder(relativ_folder);
+ } else {
+ return targetProject;
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesView.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesView.java
index a91ca06..07e865e 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesView.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesView.java
@@ -54,7 +54,7 @@
import org.eclipse.ui.progress.UIJob;
public class MessagesView extends ViewPart implements
- IResourceBundleChangedListener {
+ IResourceBundleChangedListener {
/**
* The ID of the view as specified by the extension.
@@ -95,447 +95,447 @@
* it.
*/
public void createPartControl(Composite parent) {
- this.parent = parent;
+ this.parent = parent;
- initLayout(parent);
- initSearchBar(parent);
- initMessagesTree(parent);
- makeActions();
- hookContextMenu();
- contributeToActionBars();
- initListener(parent);
+ initLayout(parent);
+ initSearchBar(parent);
+ initMessagesTree(parent);
+ makeActions();
+ hookContextMenu();
+ contributeToActionBars();
+ initListener(parent);
}
protected void initListener(Composite parent) {
- filter.addModifyListener(new ModifyListener() {
+ filter.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- treeViewer.setSearchString(filter.getText());
- }
- });
+ @Override
+ public void modifyText(ModifyEvent e) {
+ treeViewer.setSearchString(filter.getText());
+ }
+ });
}
protected void initLayout(Composite parent) {
- GridLayout mainLayout = new GridLayout();
- mainLayout.numColumns = 1;
- parent.setLayout(mainLayout);
+ GridLayout mainLayout = new GridLayout();
+ mainLayout.numColumns = 1;
+ parent.setLayout(mainLayout);
}
protected void initSearchBar(Composite parent) {
- // Construct a new parent container
- Composite parentComp = new Composite(parent, SWT.BORDER);
- parentComp.setLayout(new GridLayout(4, false));
- parentComp
- .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
+ // Construct a new parent container
+ Composite parentComp = new Composite(parent, SWT.BORDER);
+ parentComp.setLayout(new GridLayout(4, false));
+ parentComp
+ .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- Label lblSearchText = new Label(parentComp, SWT.NONE);
- lblSearchText.setText("Search expression:");
+ Label lblSearchText = new Label(parentComp, SWT.NONE);
+ lblSearchText.setText("Search expression:");
- // define the grid data for the layout
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = false;
- gridData.horizontalSpan = 1;
- lblSearchText.setLayoutData(gridData);
+ // define the grid data for the layout
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = false;
+ gridData.horizontalSpan = 1;
+ lblSearchText.setLayoutData(gridData);
- filter = new Text(parentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
- if (viewState.getSearchString() != null) {
- if (viewState.getSearchString().length() > 1
- && viewState.getSearchString().startsWith("*")
- && viewState.getSearchString().endsWith("*"))
- filter.setText(viewState.getSearchString().substring(1)
- .substring(0, viewState.getSearchString().length() - 2));
- else
- filter.setText(viewState.getSearchString());
+ filter = new Text(parentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
+ if (viewState.getSearchString() != null) {
+ if (viewState.getSearchString().length() > 1
+ && viewState.getSearchString().startsWith("*")
+ && viewState.getSearchString().endsWith("*"))
+ filter.setText(viewState.getSearchString().substring(1)
+ .substring(0, viewState.getSearchString().length() - 2));
+ else
+ filter.setText(viewState.getSearchString());
- }
- GridData gridDatas = new GridData();
- gridDatas.horizontalAlignment = SWT.FILL;
- gridDatas.grabExcessHorizontalSpace = true;
- gridDatas.horizontalSpan = 3;
- filter.setLayoutData(gridDatas);
+ }
+ GridData gridDatas = new GridData();
+ gridDatas.horizontalAlignment = SWT.FILL;
+ gridDatas.grabExcessHorizontalSpace = true;
+ gridDatas.horizontalSpan = 3;
+ filter.setLayoutData(gridDatas);
- lblScale = new Label(parentComp, SWT.None);
- lblScale.setText("\nPrecision:");
- GridData gdScaler = new GridData();
- gdScaler.verticalAlignment = SWT.CENTER;
- gdScaler.grabExcessVerticalSpace = true;
- gdScaler.horizontalSpan = 1;
- // gdScaler.widthHint = 150;
- lblScale.setLayoutData(gdScaler);
+ lblScale = new Label(parentComp, SWT.None);
+ lblScale.setText("\nPrecision:");
+ GridData gdScaler = new GridData();
+ gdScaler.verticalAlignment = SWT.CENTER;
+ gdScaler.grabExcessVerticalSpace = true;
+ gdScaler.horizontalSpan = 1;
+ // gdScaler.widthHint = 150;
+ lblScale.setLayoutData(gdScaler);
- // Add a scale for specification of fuzzy Matching precision
- fuzzyScaler = new Scale(parentComp, SWT.None);
- fuzzyScaler.setMaximum(100);
- fuzzyScaler.setMinimum(0);
- fuzzyScaler.setIncrement(1);
- fuzzyScaler.setPageIncrement(5);
- fuzzyScaler
- .setSelection(Math.round((treeViewer != null ? treeViewer
- .getMatchingPrecision() : viewState
- .getMatchingPrecision()) * 100.f));
- fuzzyScaler.addListener(SWT.Selection, new Listener() {
- public void handleEvent(Event event) {
- float val = 1f - (Float.parseFloat((fuzzyScaler.getMaximum()
- - fuzzyScaler.getSelection() + fuzzyScaler.getMinimum())
- + "") / 100.f);
- treeViewer.setMatchingPrecision(val);
- }
- });
- fuzzyScaler.setSize(100, 10);
+ // Add a scale for specification of fuzzy Matching precision
+ fuzzyScaler = new Scale(parentComp, SWT.None);
+ fuzzyScaler.setMaximum(100);
+ fuzzyScaler.setMinimum(0);
+ fuzzyScaler.setIncrement(1);
+ fuzzyScaler.setPageIncrement(5);
+ fuzzyScaler
+ .setSelection(Math.round((treeViewer != null ? treeViewer
+ .getMatchingPrecision() : viewState
+ .getMatchingPrecision()) * 100.f));
+ fuzzyScaler.addListener(SWT.Selection, new Listener() {
+ public void handleEvent(Event event) {
+ float val = 1f - (Float.parseFloat((fuzzyScaler.getMaximum()
+ - fuzzyScaler.getSelection() + fuzzyScaler.getMinimum())
+ + "") / 100.f);
+ treeViewer.setMatchingPrecision(val);
+ }
+ });
+ fuzzyScaler.setSize(100, 10);
- GridData gdScalers = new GridData();
- gdScalers.verticalAlignment = SWT.BEGINNING;
- gdScalers.horizontalAlignment = SWT.FILL;
- gdScalers.horizontalSpan = 3;
- fuzzyScaler.setLayoutData(gdScalers);
- refreshSearchbarState();
+ GridData gdScalers = new GridData();
+ gdScalers.verticalAlignment = SWT.BEGINNING;
+ gdScalers.horizontalAlignment = SWT.FILL;
+ gdScalers.horizontalSpan = 3;
+ fuzzyScaler.setLayoutData(gdScalers);
+ refreshSearchbarState();
}
protected void refreshSearchbarState() {
- lblScale.setVisible(treeViewer != null ? treeViewer
- .isFuzzyMatchingEnabled() : viewState.isFuzzyMatchingEnabled());
- fuzzyScaler.setVisible(treeViewer != null ? treeViewer
- .isFuzzyMatchingEnabled() : viewState.isFuzzyMatchingEnabled());
- if (treeViewer != null ? treeViewer.isFuzzyMatchingEnabled()
- : viewState.isFuzzyMatchingEnabled()) {
- ((GridData) lblScale.getLayoutData()).heightHint = 40;
- ((GridData) fuzzyScaler.getLayoutData()).heightHint = 40;
- } else {
- ((GridData) lblScale.getLayoutData()).heightHint = 0;
- ((GridData) fuzzyScaler.getLayoutData()).heightHint = 0;
- }
+ lblScale.setVisible(treeViewer != null ? treeViewer
+ .isFuzzyMatchingEnabled() : viewState.isFuzzyMatchingEnabled());
+ fuzzyScaler.setVisible(treeViewer != null ? treeViewer
+ .isFuzzyMatchingEnabled() : viewState.isFuzzyMatchingEnabled());
+ if (treeViewer != null ? treeViewer.isFuzzyMatchingEnabled()
+ : viewState.isFuzzyMatchingEnabled()) {
+ ((GridData) lblScale.getLayoutData()).heightHint = 40;
+ ((GridData) fuzzyScaler.getLayoutData()).heightHint = 40;
+ } else {
+ ((GridData) lblScale.getLayoutData()).heightHint = 0;
+ ((GridData) fuzzyScaler.getLayoutData()).heightHint = 0;
+ }
- lblScale.getParent().layout();
- lblScale.getParent().getParent().layout();
+ lblScale.getParent().layout();
+ lblScale.getParent().getParent().layout();
}
protected void initMessagesTree(Composite parent) {
- if (viewState.getSelectedProjectName() != null
- && viewState.getSelectedProjectName().trim().length() > 0) {
- try {
- ResourceBundleManager.getManager(
- viewState.getSelectedProjectName())
- .registerResourceBundleChangeListener(
- viewState.getSelectedBundleId(), this);
+ if (viewState.getSelectedProjectName() != null
+ && viewState.getSelectedProjectName().trim().length() > 0) {
+ try {
+ ResourceBundleManager.getManager(
+ viewState.getSelectedProjectName())
+ .registerResourceBundleChangeListener(
+ viewState.getSelectedBundleId(), this);
- } catch (Exception e) {
- }
- }
- treeViewer = new PropertyKeySelectionTree(getViewSite(), getSite(),
- parent, SWT.NONE, viewState.getSelectedProjectName(),
- viewState.getSelectedBundleId(), viewState.getVisibleLocales());
- if (viewState.getSelectedProjectName() != null
- && viewState.getSelectedProjectName().trim().length() > 0) {
- if (viewState.getVisibleLocales() == null)
- viewState.setVisibleLocales(treeViewer.getVisibleLocales());
+ } catch (Exception e) {
+ }
+ }
+ treeViewer = new PropertyKeySelectionTree(getViewSite(), getSite(),
+ parent, SWT.NONE, viewState.getSelectedProjectName(),
+ viewState.getSelectedBundleId(), viewState.getVisibleLocales());
+ if (viewState.getSelectedProjectName() != null
+ && viewState.getSelectedProjectName().trim().length() > 0) {
+ if (viewState.getVisibleLocales() == null)
+ viewState.setVisibleLocales(treeViewer.getVisibleLocales());
- if (viewState.getSortings() != null)
- treeViewer.setSortInfo(viewState.getSortings());
+ if (viewState.getSortings() != null)
+ treeViewer.setSortInfo(viewState.getSortings());
- treeViewer.enableFuzzyMatching(viewState.isFuzzyMatchingEnabled());
- treeViewer.setMatchingPrecision(viewState.getMatchingPrecision());
- treeViewer.setEditable(viewState.isEditable());
+ treeViewer.enableFuzzyMatching(viewState.isFuzzyMatchingEnabled());
+ treeViewer.setMatchingPrecision(viewState.getMatchingPrecision());
+ treeViewer.setEditable(viewState.isEditable());
- if (viewState.getSearchString() != null)
- treeViewer.setSearchString(viewState.getSearchString());
- }
- // define the grid data for the layout
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.verticalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = true;
- gridData.grabExcessVerticalSpace = true;
- treeViewer.setLayoutData(gridData);
+ if (viewState.getSearchString() != null)
+ treeViewer.setSearchString(viewState.getSearchString());
+ }
+ // define the grid data for the layout
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.verticalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ gridData.grabExcessVerticalSpace = true;
+ treeViewer.setLayoutData(gridData);
}
/**
* Passing the focus request to the viewer's control.
*/
public void setFocus() {
- treeViewer.setFocus();
+ treeViewer.setFocus();
}
protected void redrawTreeViewer() {
- parent.setRedraw(false);
- treeViewer.dispose();
- try {
- initMessagesTree(parent);
- makeActions();
- contributeToActionBars();
- hookContextMenu();
- } catch (Exception e) {
- Logger.logError(e);
- }
- parent.setRedraw(true);
- parent.layout(true);
- treeViewer.layout(true);
- refreshSearchbarState();
+ parent.setRedraw(false);
+ treeViewer.dispose();
+ try {
+ initMessagesTree(parent);
+ makeActions();
+ contributeToActionBars();
+ hookContextMenu();
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+ parent.setRedraw(true);
+ parent.layout(true);
+ treeViewer.layout(true);
+ refreshSearchbarState();
}
/*** ACTIONS ***/
private void makeVisibleLocalesActions() {
- if (viewState.getSelectedProjectName() == null) {
- return;
- }
+ if (viewState.getSelectedProjectName() == null) {
+ return;
+ }
- visibleLocaleActions = new ArrayList<Action>();
- Set<Locale> locales = ResourceBundleManager.getManager(
- viewState.getSelectedProjectName()).getProvidedLocales(
- viewState.getSelectedBundleId());
- List<Locale> visibleLocales = treeViewer.getVisibleLocales();
- for (final Locale locale : locales) {
- Action langAction = new Action() {
+ visibleLocaleActions = new ArrayList<Action>();
+ Set<Locale> locales = ResourceBundleManager.getManager(
+ viewState.getSelectedProjectName()).getProvidedLocales(
+ viewState.getSelectedBundleId());
+ List<Locale> visibleLocales = treeViewer.getVisibleLocales();
+ for (final Locale locale : locales) {
+ Action langAction = new Action() {
- @Override
- public void run() {
- super.run();
- List<Locale> visibleL = treeViewer.getVisibleLocales();
- if (this.isChecked()) {
- if (!visibleL.contains(locale)) {
- visibleL.add(locale);
- }
- } else {
- visibleL.remove(locale);
- }
- viewState.setVisibleLocales(visibleL);
- redrawTreeViewer();
- }
+ @Override
+ public void run() {
+ super.run();
+ List<Locale> visibleL = treeViewer.getVisibleLocales();
+ if (this.isChecked()) {
+ if (!visibleL.contains(locale)) {
+ visibleL.add(locale);
+ }
+ } else {
+ visibleL.remove(locale);
+ }
+ viewState.setVisibleLocales(visibleL);
+ redrawTreeViewer();
+ }
- };
- if (locale != null && locale.getDisplayName().trim().length() > 0) {
- langAction.setText(locale.getDisplayName(Locale.US));
- } else {
- langAction.setText("Default");
- }
- langAction.setChecked(visibleLocales.contains(locale));
- visibleLocaleActions.add(langAction);
- }
+ };
+ if (locale != null && locale.getDisplayName().trim().length() > 0) {
+ langAction.setText(locale.getDisplayName(Locale.US));
+ } else {
+ langAction.setText("Default");
+ }
+ langAction.setChecked(visibleLocales.contains(locale));
+ visibleLocaleActions.add(langAction);
+ }
}
private void makeActions() {
- makeVisibleLocalesActions();
+ makeVisibleLocalesActions();
- selectResourceBundle = new Action() {
+ selectResourceBundle = new Action() {
- @Override
- public void run() {
- super.run();
- ResourceBundleSelectionDialog sd = new ResourceBundleSelectionDialog(
- getViewSite().getShell(), null);
- if (sd.open() == InputDialog.OK) {
- String resourceBundle = sd.getSelectedBundleId();
+ @Override
+ public void run() {
+ super.run();
+ ResourceBundleSelectionDialog sd = new ResourceBundleSelectionDialog(
+ getViewSite().getShell(), null);
+ if (sd.open() == InputDialog.OK) {
+ String resourceBundle = sd.getSelectedBundleId();
- if (resourceBundle != null) {
- int iSep = resourceBundle.indexOf("/");
- viewState.setSelectedProjectName(resourceBundle
- .substring(0, iSep));
- viewState.setSelectedBundleId(resourceBundle
- .substring(iSep + 1));
- viewState.setVisibleLocales(null);
- redrawTreeViewer();
- setTitleToolTip(resourceBundle);
- }
- }
- }
- };
+ if (resourceBundle != null) {
+ int iSep = resourceBundle.indexOf("/");
+ viewState.setSelectedProjectName(resourceBundle
+ .substring(0, iSep));
+ viewState.setSelectedBundleId(resourceBundle
+ .substring(iSep + 1));
+ viewState.setVisibleLocales(null);
+ redrawTreeViewer();
+ setTitleToolTip(resourceBundle);
+ }
+ }
+ }
+ };
- selectResourceBundle.setText("Resource-Bundle ...");
- selectResourceBundle
- .setDescription("Allows you to select the Resource-Bundle which is used as message-source.");
- selectResourceBundle.setImageDescriptor(Activator
- .getImageDescriptor(ImageUtils.IMAGE_RESOURCE_BUNDLE));
+ selectResourceBundle.setText("Resource-Bundle ...");
+ selectResourceBundle
+ .setDescription("Allows you to select the Resource-Bundle which is used as message-source.");
+ selectResourceBundle.setImageDescriptor(Activator
+ .getImageDescriptor(ImageUtils.IMAGE_RESOURCE_BUNDLE));
- contextDependentMenu = new ResourceBundleEntry(treeViewer, treeViewer
- .getViewer().getSelection());
+ contextDependentMenu = new ResourceBundleEntry(treeViewer, treeViewer
+ .getViewer().getSelection());
- enableFuzzyMatching = new Action() {
- public void run() {
- super.run();
- treeViewer.enableFuzzyMatching(!treeViewer
- .isFuzzyMatchingEnabled());
- viewState.setFuzzyMatchingEnabled(treeViewer
- .isFuzzyMatchingEnabled());
- refreshSearchbarState();
- }
- };
- enableFuzzyMatching.setText("Fuzzy-Matching");
- enableFuzzyMatching
- .setDescription("Enables Fuzzy matching for searching Resource-Bundle entries.");
- enableFuzzyMatching.setChecked(viewState.isFuzzyMatchingEnabled());
- enableFuzzyMatching
- .setToolTipText(enableFuzzyMatching.getDescription());
+ enableFuzzyMatching = new Action() {
+ public void run() {
+ super.run();
+ treeViewer.enableFuzzyMatching(!treeViewer
+ .isFuzzyMatchingEnabled());
+ viewState.setFuzzyMatchingEnabled(treeViewer
+ .isFuzzyMatchingEnabled());
+ refreshSearchbarState();
+ }
+ };
+ enableFuzzyMatching.setText("Fuzzy-Matching");
+ enableFuzzyMatching
+ .setDescription("Enables Fuzzy matching for searching Resource-Bundle entries.");
+ enableFuzzyMatching.setChecked(viewState.isFuzzyMatchingEnabled());
+ enableFuzzyMatching
+ .setToolTipText(enableFuzzyMatching.getDescription());
- editable = new Action() {
- public void run() {
- super.run();
- treeViewer.setEditable(!treeViewer.isEditable());
- viewState.setEditable(treeViewer.isEditable());
- }
- };
- editable.setText("Editable");
- editable.setDescription("Allows you to edit Resource-Bundle entries.");
- editable.setChecked(viewState.isEditable());
- editable.setToolTipText(editable.getDescription());
+ editable = new Action() {
+ public void run() {
+ super.run();
+ treeViewer.setEditable(!treeViewer.isEditable());
+ viewState.setEditable(treeViewer.isEditable());
+ }
+ };
+ editable.setText("Editable");
+ editable.setDescription("Allows you to edit Resource-Bundle entries.");
+ editable.setChecked(viewState.isEditable());
+ editable.setToolTipText(editable.getDescription());
}
private void contributeToActionBars() {
- IActionBars bars = getViewSite().getActionBars();
- fillLocalPullDown(bars.getMenuManager());
- fillLocalToolBar(bars.getToolBarManager());
+ IActionBars bars = getViewSite().getActionBars();
+ fillLocalPullDown(bars.getMenuManager());
+ fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalPullDown(IMenuManager manager) {
- manager.removeAll();
- manager.add(selectResourceBundle);
- manager.add(enableFuzzyMatching);
- manager.add(editable);
- manager.add(new Separator());
+ manager.removeAll();
+ manager.add(selectResourceBundle);
+ manager.add(enableFuzzyMatching);
+ manager.add(editable);
+ manager.add(new Separator());
- manager.add(contextDependentMenu);
- manager.add(new Separator());
+ manager.add(contextDependentMenu);
+ manager.add(new Separator());
- if (visibleLocaleActions == null)
- return;
+ if (visibleLocaleActions == null)
+ return;
- for (Action loc : visibleLocaleActions) {
- manager.add(loc);
- }
+ for (Action loc : visibleLocaleActions) {
+ manager.add(loc);
+ }
}
/*** CONTEXT MENU ***/
private void hookContextMenu() {
- new UIJob("set PopupMenu") {
- @Override
- public IStatus runInUIThread(IProgressMonitor monitor) {
- if (!treeViewer.isDisposed()) {
- MenuManager menuMgr = new MenuManager("#PopupMenu");
- menuMgr.setRemoveAllWhenShown(true);
- menuMgr.addMenuListener(new IMenuListener() {
- public void menuAboutToShow(IMenuManager manager) {
- fillContextMenu(manager);
- }
- });
- Menu menu = menuMgr.createContextMenu(treeViewer
- .getViewer().getControl());
- treeViewer.getViewer().getControl().setMenu(menu);
- getViewSite().registerContextMenu(menuMgr,
- treeViewer.getViewer());
- }
- return Status.OK_STATUS;
- }
- }.schedule();
+ new UIJob("set PopupMenu") {
+ @Override
+ public IStatus runInUIThread(IProgressMonitor monitor) {
+ if (!treeViewer.isDisposed()) {
+ MenuManager menuMgr = new MenuManager("#PopupMenu");
+ menuMgr.setRemoveAllWhenShown(true);
+ menuMgr.addMenuListener(new IMenuListener() {
+ public void menuAboutToShow(IMenuManager manager) {
+ fillContextMenu(manager);
+ }
+ });
+ Menu menu = menuMgr.createContextMenu(treeViewer
+ .getViewer().getControl());
+ treeViewer.getViewer().getControl().setMenu(menu);
+ getViewSite().registerContextMenu(menuMgr,
+ treeViewer.getViewer());
+ }
+ return Status.OK_STATUS;
+ }
+ }.schedule();
}
private void fillContextMenu(IMenuManager manager) {
- manager.removeAll();
- manager.add(selectResourceBundle);
- manager.add(enableFuzzyMatching);
- manager.add(editable);
- manager.add(new Separator());
+ manager.removeAll();
+ manager.add(selectResourceBundle);
+ manager.add(enableFuzzyMatching);
+ manager.add(editable);
+ manager.add(new Separator());
- manager.add(new ResourceBundleEntry(treeViewer, treeViewer.getViewer()
- .getSelection()));
- manager.add(new Separator());
+ manager.add(new ResourceBundleEntry(treeViewer, treeViewer.getViewer()
+ .getSelection()));
+ manager.add(new Separator());
- for (Action loc : visibleLocaleActions) {
- manager.add(loc);
- }
- // Other plug-ins can contribute there actions here
- // manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
+ for (Action loc : visibleLocaleActions) {
+ manager.add(loc);
+ }
+ // Other plug-ins can contribute there actions here
+ // manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
private void fillLocalToolBar(IToolBarManager manager) {
- manager.add(selectResourceBundle);
+ manager.add(selectResourceBundle);
}
@Override
public void saveState(IMemento memento) {
- super.saveState(memento);
- try {
- viewState.setEditable(treeViewer.isEditable());
- viewState.setSortings(treeViewer.getSortInfo());
- viewState.setSearchString(treeViewer.getSearchString());
- viewState.setFuzzyMatchingEnabled(treeViewer
- .isFuzzyMatchingEnabled());
- viewState.setMatchingPrecision(treeViewer.getMatchingPrecision());
- viewState.saveState(memento);
- } catch (Exception e) {
- }
+ super.saveState(memento);
+ try {
+ viewState.setEditable(treeViewer.isEditable());
+ viewState.setSortings(treeViewer.getSortInfo());
+ viewState.setSearchString(treeViewer.getSearchString());
+ viewState.setFuzzyMatchingEnabled(treeViewer
+ .isFuzzyMatchingEnabled());
+ viewState.setMatchingPrecision(treeViewer.getMatchingPrecision());
+ viewState.saveState(memento);
+ } catch (Exception e) {
+ }
}
@Override
public void init(IViewSite site, IMemento memento) throws PartInitException {
- super.init(site, memento);
+ super.init(site, memento);
- // init Viewstate
- viewState = new MessagesViewState(null, null, false, null);
- viewState.init(memento);
+ // init Viewstate
+ viewState = new MessagesViewState(null, null, false, null);
+ viewState.init(memento);
}
@Override
public void resourceBundleChanged(ResourceBundleChangedEvent event) {
- try {
- if (!event.getBundle().equals(treeViewer.getResourceBundle()))
- return;
+ try {
+ if (!event.getBundle().equals(treeViewer.getResourceBundle()))
+ return;
- switch (event.getType()) {
- case ResourceBundleChangedEvent.ADDED:
- // update visible locales within the context menu
- makeVisibleLocalesActions();
- hookContextMenu();
- break;
- case ResourceBundleChangedEvent.DELETED:
- case ResourceBundleChangedEvent.EXCLUDED:
- if (viewState.getSelectedProjectName().trim().length() > 0) {
- try {
- ResourceBundleManager.getManager(
- viewState.getSelectedProjectName())
- .unregisterResourceBundleChangeListener(
- viewState.getSelectedBundleId(), this);
+ switch (event.getType()) {
+ case ResourceBundleChangedEvent.ADDED:
+ // update visible locales within the context menu
+ makeVisibleLocalesActions();
+ hookContextMenu();
+ break;
+ case ResourceBundleChangedEvent.DELETED:
+ case ResourceBundleChangedEvent.EXCLUDED:
+ if (viewState.getSelectedProjectName().trim().length() > 0) {
+ try {
+ ResourceBundleManager.getManager(
+ viewState.getSelectedProjectName())
+ .unregisterResourceBundleChangeListener(
+ viewState.getSelectedBundleId(), this);
- } catch (Exception e) {
- }
- }
- viewState = new MessagesViewState(null, null, false, null);
+ } catch (Exception e) {
+ }
+ }
+ viewState = new MessagesViewState(null, null, false, null);
- new Thread(new Runnable() {
+ new Thread(new Runnable() {
- public void run() {
- try {
- Thread.sleep(500);
- } catch (Exception e) {
- }
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- try {
- redrawTreeViewer();
- } catch (Exception e) {
- Logger.logError(e);
- }
- }
- });
+ public void run() {
+ try {
+ Thread.sleep(500);
+ } catch (Exception e) {
+ }
+ Display.getDefault().asyncExec(new Runnable() {
+ public void run() {
+ try {
+ redrawTreeViewer();
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+ }
+ });
- }
- }).start();
- }
- } catch (Exception e) {
- Logger.logError(e);
- }
+ }
+ }).start();
+ }
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
}
@Override
public void dispose() {
- try {
- super.dispose();
- treeViewer.dispose();
- ResourceBundleManager
- .getManager(viewState.getSelectedProjectName())
- .unregisterResourceBundleChangeListener(
- viewState.getSelectedBundleId(), this);
- } catch (Exception e) {
- }
+ try {
+ super.dispose();
+ treeViewer.dispose();
+ ResourceBundleManager
+ .getManager(viewState.getSelectedProjectName())
+ .unregisterResourceBundleChangeListener(
+ viewState.getSelectedBundleId(), this);
+ } catch (Exception e) {
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesViewState.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesViewState.java
index 6c7a2d4..0d82c93 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesViewState.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesViewState.java
@@ -42,176 +42,176 @@
private boolean editable;
public void saveState(IMemento memento) {
- try {
- if (memento == null)
- return;
+ try {
+ if (memento == null)
+ return;
- if (visibleLocales != null) {
- IMemento memVL = memento.createChild(TAG_VISIBLE_LOCALES);
- for (Locale loc : visibleLocales) {
- IMemento memLoc = memVL.createChild(TAG_LOCALE);
- memLoc.putString(TAG_LOCALE_LANGUAGE, loc.getLanguage());
- memLoc.putString(TAG_LOCALE_COUNTRY, loc.getCountry());
- memLoc.putString(TAG_LOCALE_VARIANT, loc.getVariant());
- }
- }
+ if (visibleLocales != null) {
+ IMemento memVL = memento.createChild(TAG_VISIBLE_LOCALES);
+ for (Locale loc : visibleLocales) {
+ IMemento memLoc = memVL.createChild(TAG_LOCALE);
+ memLoc.putString(TAG_LOCALE_LANGUAGE, loc.getLanguage());
+ memLoc.putString(TAG_LOCALE_COUNTRY, loc.getCountry());
+ memLoc.putString(TAG_LOCALE_VARIANT, loc.getVariant());
+ }
+ }
- if (sortings != null) {
- sortings.saveState(memento);
- }
+ if (sortings != null) {
+ sortings.saveState(memento);
+ }
- IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING);
- memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled);
+ IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING);
+ memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled);
- IMemento memMatchingPrec = memento
- .createChild(TAG_MATCHING_PRECISION);
- memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision);
+ IMemento memMatchingPrec = memento
+ .createChild(TAG_MATCHING_PRECISION);
+ memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision);
- selectedProjectName = selectedProjectName != null ? selectedProjectName
- : "";
- selectedBundleId = selectedBundleId != null ? selectedBundleId : "";
+ selectedProjectName = selectedProjectName != null ? selectedProjectName
+ : "";
+ selectedBundleId = selectedBundleId != null ? selectedBundleId : "";
- IMemento memSP = memento.createChild(TAG_SELECTED_PROJECT);
- memSP.putString(TAG_VALUE, selectedProjectName);
+ IMemento memSP = memento.createChild(TAG_SELECTED_PROJECT);
+ memSP.putString(TAG_VALUE, selectedProjectName);
- IMemento memSB = memento.createChild(TAG_SELECTED_BUNDLE);
- memSB.putString(TAG_VALUE, selectedBundleId);
+ IMemento memSB = memento.createChild(TAG_SELECTED_BUNDLE);
+ memSB.putString(TAG_VALUE, selectedBundleId);
- IMemento memSStr = memento.createChild(TAG_SEARCH_STRING);
- memSStr.putString(TAG_VALUE, searchString);
+ IMemento memSStr = memento.createChild(TAG_SEARCH_STRING);
+ memSStr.putString(TAG_VALUE, searchString);
- IMemento memEditable = memento.createChild(TAG_EDITABLE);
- memEditable.putBoolean(TAG_ENABLED, editable);
- } catch (Exception e) {
+ IMemento memEditable = memento.createChild(TAG_EDITABLE);
+ memEditable.putBoolean(TAG_ENABLED, editable);
+ } catch (Exception e) {
- }
+ }
}
public void init(IMemento memento) {
- if (memento == null)
- return;
+ if (memento == null)
+ return;
- if (memento.getChild(TAG_VISIBLE_LOCALES) != null) {
- if (visibleLocales == null)
- visibleLocales = new ArrayList<Locale>();
- IMemento[] mLocales = memento.getChild(TAG_VISIBLE_LOCALES)
- .getChildren(TAG_LOCALE);
- for (IMemento mLocale : mLocales) {
- if (mLocale.getString(TAG_LOCALE_LANGUAGE) == null
- && mLocale.getString(TAG_LOCALE_COUNTRY) == null
- && mLocale.getString(TAG_LOCALE_VARIANT) == null) {
- continue;
- }
- Locale newLocale = new Locale(
- mLocale.getString(TAG_LOCALE_LANGUAGE),
- mLocale.getString(TAG_LOCALE_COUNTRY),
- mLocale.getString(TAG_LOCALE_VARIANT));
- if (!this.visibleLocales.contains(newLocale)) {
- visibleLocales.add(newLocale);
- }
- }
- }
+ if (memento.getChild(TAG_VISIBLE_LOCALES) != null) {
+ if (visibleLocales == null)
+ visibleLocales = new ArrayList<Locale>();
+ IMemento[] mLocales = memento.getChild(TAG_VISIBLE_LOCALES)
+ .getChildren(TAG_LOCALE);
+ for (IMemento mLocale : mLocales) {
+ if (mLocale.getString(TAG_LOCALE_LANGUAGE) == null
+ && mLocale.getString(TAG_LOCALE_COUNTRY) == null
+ && mLocale.getString(TAG_LOCALE_VARIANT) == null) {
+ continue;
+ }
+ Locale newLocale = new Locale(
+ mLocale.getString(TAG_LOCALE_LANGUAGE),
+ mLocale.getString(TAG_LOCALE_COUNTRY),
+ mLocale.getString(TAG_LOCALE_VARIANT));
+ if (!this.visibleLocales.contains(newLocale)) {
+ visibleLocales.add(newLocale);
+ }
+ }
+ }
- if (sortings == null)
- sortings = new SortInfo();
- sortings.init(memento);
+ if (sortings == null)
+ sortings = new SortInfo();
+ sortings.init(memento);
- IMemento mFuzzyMatching = memento.getChild(TAG_FUZZY_MATCHING);
- if (mFuzzyMatching != null)
- fuzzyMatchingEnabled = mFuzzyMatching.getBoolean(TAG_ENABLED);
+ IMemento mFuzzyMatching = memento.getChild(TAG_FUZZY_MATCHING);
+ if (mFuzzyMatching != null)
+ fuzzyMatchingEnabled = mFuzzyMatching.getBoolean(TAG_ENABLED);
- IMemento mMP = memento.getChild(TAG_MATCHING_PRECISION);
- if (mMP != null)
- matchingPrecision = mMP.getFloat(TAG_VALUE);
+ IMemento mMP = memento.getChild(TAG_MATCHING_PRECISION);
+ if (mMP != null)
+ matchingPrecision = mMP.getFloat(TAG_VALUE);
- IMemento mSelProj = memento.getChild(TAG_SELECTED_PROJECT);
- if (mSelProj != null)
- selectedProjectName = mSelProj.getString(TAG_VALUE);
+ IMemento mSelProj = memento.getChild(TAG_SELECTED_PROJECT);
+ if (mSelProj != null)
+ selectedProjectName = mSelProj.getString(TAG_VALUE);
- IMemento mSelBundle = memento.getChild(TAG_SELECTED_BUNDLE);
- if (mSelBundle != null)
- selectedBundleId = mSelBundle.getString(TAG_VALUE);
+ IMemento mSelBundle = memento.getChild(TAG_SELECTED_BUNDLE);
+ if (mSelBundle != null)
+ selectedBundleId = mSelBundle.getString(TAG_VALUE);
- IMemento mSStr = memento.getChild(TAG_SEARCH_STRING);
- if (mSStr != null)
- searchString = mSStr.getString(TAG_VALUE);
+ IMemento mSStr = memento.getChild(TAG_SEARCH_STRING);
+ if (mSStr != null)
+ searchString = mSStr.getString(TAG_VALUE);
- IMemento mEditable = memento.getChild(TAG_EDITABLE);
- if (mEditable != null)
- editable = mEditable.getBoolean(TAG_ENABLED);
+ IMemento mEditable = memento.getChild(TAG_EDITABLE);
+ if (mEditable != null)
+ editable = mEditable.getBoolean(TAG_ENABLED);
}
public MessagesViewState(List<Locale> visibleLocales, SortInfo sortings,
- boolean fuzzyMatchingEnabled, String selectedBundleId) {
- super();
- this.visibleLocales = visibleLocales;
- this.sortings = sortings;
- this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
- this.selectedBundleId = selectedBundleId;
+ boolean fuzzyMatchingEnabled, String selectedBundleId) {
+ super();
+ this.visibleLocales = visibleLocales;
+ this.sortings = sortings;
+ this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
+ this.selectedBundleId = selectedBundleId;
}
public List<Locale> getVisibleLocales() {
- return visibleLocales;
+ return visibleLocales;
}
public void setVisibleLocales(List<Locale> visibleLocales) {
- this.visibleLocales = visibleLocales;
+ this.visibleLocales = visibleLocales;
}
public SortInfo getSortings() {
- return sortings;
+ return sortings;
}
public void setSortings(SortInfo sortings) {
- this.sortings = sortings;
+ this.sortings = sortings;
}
public boolean isFuzzyMatchingEnabled() {
- return fuzzyMatchingEnabled;
+ return fuzzyMatchingEnabled;
}
public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) {
- this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
+ this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
}
public void setSelectedBundleId(String selectedBundleId) {
- this.selectedBundleId = selectedBundleId;
+ this.selectedBundleId = selectedBundleId;
}
public void setSelectedProjectName(String selectedProjectName) {
- this.selectedProjectName = selectedProjectName;
+ this.selectedProjectName = selectedProjectName;
}
public void setSearchString(String searchString) {
- this.searchString = searchString;
+ this.searchString = searchString;
}
public String getSelectedBundleId() {
- return selectedBundleId;
+ return selectedBundleId;
}
public String getSelectedProjectName() {
- return selectedProjectName;
+ return selectedProjectName;
}
public String getSearchString() {
- return searchString;
+ return searchString;
}
public boolean isEditable() {
- return editable;
+ return editable;
}
public void setEditable(boolean editable) {
- this.editable = editable;
+ this.editable = editable;
}
public float getMatchingPrecision() {
- return matchingPrecision;
+ return matchingPrecision;
}
public void setMatchingPrecision(float value) {
- this.matchingPrecision = value;
+ this.matchingPrecision = value;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java
index 9bc7dec..2844fb6 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java
@@ -24,7 +24,7 @@
import org.eclipse.ui.PlatformUI;
public class ResourceBundleEntry extends ContributionItem implements
- ISelectionChangedListener {
+ ISelectionChangedListener {
private PropertyKeySelectionTree parentView;
private ISelection selection;
@@ -39,86 +39,86 @@
}
public ResourceBundleEntry(PropertyKeySelectionTree view,
- ISelection selection) {
- this.selection = selection;
- this.legalSelection = !selection.isEmpty();
- this.parentView = view;
- parentView.addSelectionChangedListener(this);
+ ISelection selection) {
+ this.selection = selection;
+ this.legalSelection = !selection.isEmpty();
+ this.parentView = view;
+ parentView.addSelectionChangedListener(this);
}
@Override
public void fill(Menu menu, int index) {
- // MenuItem for adding a new entry
- addItem = new MenuItem(menu, SWT.NONE, index);
- addItem.setText("Add ...");
- addItem.setImage(PlatformUI.getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage());
- addItem.addSelectionListener(new SelectionListener() {
+ // MenuItem for adding a new entry
+ addItem = new MenuItem(menu, SWT.NONE, index);
+ addItem.setText("Add ...");
+ addItem.setImage(PlatformUI.getWorkbench().getSharedImages()
+ .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage());
+ addItem.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- parentView.addNewItem(selection);
- }
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ parentView.addNewItem(selection);
+ }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
+ }
+ });
- if ((parentView == null && legalSelection) || parentView != null) {
- // MenuItem for editing the currently selected entry
- editItem = new MenuItem(menu, SWT.NONE, index + 1);
- editItem.setText("Edit");
- editItem.addSelectionListener(new SelectionListener() {
+ if ((parentView == null && legalSelection) || parentView != null) {
+ // MenuItem for editing the currently selected entry
+ editItem = new MenuItem(menu, SWT.NONE, index + 1);
+ editItem.setText("Edit");
+ editItem.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- parentView.editSelectedItem();
- }
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ parentView.editSelectedItem();
+ }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
+ }
+ });
- // MenuItem for deleting the currently selected entry
- removeItem = new MenuItem(menu, SWT.NONE, index + 2);
- removeItem.setText("Remove");
- removeItem.setImage(PlatformUI.getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE)
- .createImage());
- removeItem.addSelectionListener(new SelectionListener() {
+ // MenuItem for deleting the currently selected entry
+ removeItem = new MenuItem(menu, SWT.NONE, index + 2);
+ removeItem.setText("Remove");
+ removeItem.setImage(PlatformUI.getWorkbench().getSharedImages()
+ .getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE)
+ .createImage());
+ removeItem.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- parentView.deleteSelectedItems();
- }
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ parentView.deleteSelectedItems();
+ }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
- enableMenuItems();
- }
+ }
+ });
+ enableMenuItems();
+ }
}
protected void enableMenuItems() {
- try {
- editItem.setEnabled(legalSelection);
- removeItem.setEnabled(legalSelection);
- } catch (Exception e) {
- // silent catch
- }
+ try {
+ editItem.setEnabled(legalSelection);
+ removeItem.setEnabled(legalSelection);
+ } catch (Exception e) {
+ // silent catch
+ }
}
@Override
public void selectionChanged(SelectionChangedEvent event) {
- legalSelection = !event.getSelection().isEmpty();
- // enableMenuItems ();
+ legalSelection = !event.getSelection().isEmpty();
+ // enableMenuItems ();
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/SortInfo.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/SortInfo.java
index 0744235..0ede994 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/SortInfo.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/SortInfo.java
@@ -26,40 +26,40 @@
private List<Locale> visibleLocales;
public void setDESC(boolean dESC) {
- DESC = dESC;
+ DESC = dESC;
}
public boolean isDESC() {
- return DESC;
+ return DESC;
}
public void setColIdx(int colIdx) {
- this.colIdx = colIdx;
+ this.colIdx = colIdx;
}
public int getColIdx() {
- return colIdx;
+ return colIdx;
}
public void setVisibleLocales(List<Locale> visibleLocales) {
- this.visibleLocales = visibleLocales;
+ this.visibleLocales = visibleLocales;
}
public List<Locale> getVisibleLocales() {
- return visibleLocales;
+ return visibleLocales;
}
public void saveState(IMemento memento) {
- IMemento mCI = memento.createChild(TAG_SORT_INFO);
- mCI.putInteger(TAG_COLUMN_INDEX, colIdx);
- mCI.putBoolean(TAG_ORDER, DESC);
+ IMemento mCI = memento.createChild(TAG_SORT_INFO);
+ mCI.putInteger(TAG_COLUMN_INDEX, colIdx);
+ mCI.putBoolean(TAG_ORDER, DESC);
}
public void init(IMemento memento) {
- IMemento mCI = memento.getChild(TAG_SORT_INFO);
- if (mCI == null)
- return;
- colIdx = mCI.getInteger(TAG_COLUMN_INDEX);
- DESC = mCI.getBoolean(TAG_ORDER);
+ IMemento mCI = memento.getChild(TAG_SORT_INFO);
+ if (mCI == null)
+ return;
+ colIdx = mCI.getInteger(TAG_COLUMN_INDEX);
+ DESC = mCI.getBoolean(TAG_ORDER);
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java
index 3033bad..7416afb 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java
@@ -36,145 +36,145 @@
private final TreeViewer target;
public KeyTreeItemDropTarget(TreeViewer viewer) {
- super();
- this.target = viewer;
+ super();
+ this.target = viewer;
}
public void dragEnter(DropTargetEvent event) {
- // if (((DropTarget)event.getSource()).getControl() instanceof Tree)
- // event.detail = DND.DROP_MOVE;
+ // if (((DropTarget)event.getSource()).getControl() instanceof Tree)
+ // event.detail = DND.DROP_MOVE;
}
private void addBundleEntries(final String keyPrefix, // new prefix
- final IKeyTreeNode children, final IMessagesBundleGroup bundleGroup) {
+ final IKeyTreeNode children, final IMessagesBundleGroup bundleGroup) {
- try {
- String oldKey = children.getMessageKey();
- String key = children.getName();
- String newKey = keyPrefix + "." + key;
+ try {
+ String oldKey = children.getMessageKey();
+ String key = children.getName();
+ String newKey = keyPrefix + "." + key;
- IMessage[] messages = bundleGroup.getMessages(oldKey);
- for (IMessage message : messages) {
- IMessagesBundle messagesBundle = bundleGroup
- .getMessagesBundle(message.getLocale());
- IMessage m = MessageFactory.createMessage(newKey,
- message.getLocale());
- m.setText(message.getValue());
- m.setComment(message.getComment());
- messagesBundle.addMessage(m);
- }
+ IMessage[] messages = bundleGroup.getMessages(oldKey);
+ for (IMessage message : messages) {
+ IMessagesBundle messagesBundle = bundleGroup
+ .getMessagesBundle(message.getLocale());
+ IMessage m = MessageFactory.createMessage(newKey,
+ message.getLocale());
+ m.setText(message.getValue());
+ m.setComment(message.getComment());
+ messagesBundle.addMessage(m);
+ }
- if (messages.length == 0) {
- bundleGroup.addMessages(newKey);
- }
+ if (messages.length == 0) {
+ bundleGroup.addMessages(newKey);
+ }
- for (IKeyTreeNode childs : children.getChildren()) {
- addBundleEntries(keyPrefix + "." + key, childs, bundleGroup);
- }
+ for (IKeyTreeNode childs : children.getChildren()) {
+ addBundleEntries(keyPrefix + "." + key, childs, bundleGroup);
+ }
- } catch (Exception e) {
- Logger.logError(e);
- }
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
}
private void remBundleEntries(IKeyTreeNode children,
- IMessagesBundleGroup group) {
- String key = children.getMessageKey();
+ IMessagesBundleGroup group) {
+ String key = children.getMessageKey();
- for (IKeyTreeNode childs : children.getChildren()) {
- remBundleEntries(childs, group);
- }
+ for (IKeyTreeNode childs : children.getChildren()) {
+ remBundleEntries(childs, group);
+ }
- group.removeMessagesAddParentKey(key);
+ group.removeMessagesAddParentKey(key);
}
public void drop(final DropTargetEvent event) {
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- try {
+ Display.getDefault().asyncExec(new Runnable() {
+ public void run() {
+ try {
- if (TextTransfer.getInstance().isSupportedType(
- event.currentDataType)) {
- String newKeyPrefix = "";
+ if (TextTransfer.getInstance().isSupportedType(
+ event.currentDataType)) {
+ String newKeyPrefix = "";
- if (event.item instanceof TreeItem
- && ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) {
- IValuedKeyTreeNode targetTreeNode = (IValuedKeyTreeNode) ((TreeItem) event.item)
- .getData();
- newKeyPrefix = targetTreeNode.getMessageKey();
- }
+ if (event.item instanceof TreeItem
+ && ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) {
+ IValuedKeyTreeNode targetTreeNode = (IValuedKeyTreeNode) ((TreeItem) event.item)
+ .getData();
+ newKeyPrefix = targetTreeNode.getMessageKey();
+ }
- String message = (String) event.data;
- String oldKey = message.replaceAll("\"", "");
+ String message = (String) event.data;
+ String oldKey = message.replaceAll("\"", "");
- String[] keyArr = (oldKey).split("\\.");
- String key = keyArr[keyArr.length - 1];
+ String[] keyArr = (oldKey).split("\\.");
+ String key = keyArr[keyArr.length - 1];
- ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider) target
- .getContentProvider();
- IAbstractKeyTreeModel keyTree = (IAbstractKeyTreeModel) target
- .getInput();
+ ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider) target
+ .getContentProvider();
+ IAbstractKeyTreeModel keyTree = (IAbstractKeyTreeModel) target
+ .getInput();
- // key gets dropped into it's parent node
- if (oldKey.equals(newKeyPrefix + "." + key))
- return; // TODO: give user feedback
+ // key gets dropped into it's parent node
+ if (oldKey.equals(newKeyPrefix + "." + key))
+ return; // TODO: give user feedback
- // prevent cycle loop if key gets dropped into its child
- // node
- if (newKeyPrefix.contains(oldKey))
- return; // TODO: give user feedback
+ // prevent cycle loop if key gets dropped into its child
+ // node
+ if (newKeyPrefix.contains(oldKey))
+ return; // TODO: give user feedback
- // source node already exists in target
- IKeyTreeNode targetTreeNode = keyTree
- .getChild(newKeyPrefix);
- for (IKeyTreeNode targetChild : targetTreeNode
- .getChildren()) {
- if (targetChild.getName().equals(key))
- return; // TODO: give user feedback
- }
+ // source node already exists in target
+ IKeyTreeNode targetTreeNode = keyTree
+ .getChild(newKeyPrefix);
+ for (IKeyTreeNode targetChild : targetTreeNode
+ .getChildren()) {
+ if (targetChild.getName().equals(key))
+ return; // TODO: give user feedback
+ }
- IKeyTreeNode sourceTreeNode = keyTree.getChild(oldKey);
+ IKeyTreeNode sourceTreeNode = keyTree.getChild(oldKey);
- IMessagesBundleGroup bundleGroup = contentProvider
- .getBundle();
+ IMessagesBundleGroup bundleGroup = contentProvider
+ .getBundle();
- DirtyHack.setFireEnabled(false);
- DirtyHack.setEditorModificationEnabled(false); // editor
- // won't
- // get
- // dirty
+ DirtyHack.setFireEnabled(false);
+ DirtyHack.setEditorModificationEnabled(false); // editor
+ // won't
+ // get
+ // dirty
- // add new bundle entries of source node + all children
- addBundleEntries(newKeyPrefix, sourceTreeNode,
- bundleGroup);
+ // add new bundle entries of source node + all children
+ addBundleEntries(newKeyPrefix, sourceTreeNode,
+ bundleGroup);
- // if drag & drop is move event, delete source entry +
- // it's children
- if (event.detail == DND.DROP_MOVE) {
- remBundleEntries(sourceTreeNode, bundleGroup);
- }
+ // if drag & drop is move event, delete source entry +
+ // it's children
+ if (event.detail == DND.DROP_MOVE) {
+ remBundleEntries(sourceTreeNode, bundleGroup);
+ }
- // Store changes
- RBManager manager = RBManager
- .getInstance(((MessagesBundleGroup) bundleGroup)
- .getProjectName());
+ // Store changes
+ RBManager manager = RBManager
+ .getInstance(((MessagesBundleGroup) bundleGroup)
+ .getProjectName());
- manager.writeToFile(bundleGroup);
- manager.fireEditorChanged(); // refresh the View
+ manager.writeToFile(bundleGroup);
+ manager.fireEditorChanged(); // refresh the View
- target.refresh();
- } else {
- event.detail = DND.DROP_NONE;
- }
+ target.refresh();
+ } else {
+ event.detail = DND.DROP_NONE;
+ }
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- DirtyHack.setFireEnabled(true);
- DirtyHack.setEditorModificationEnabled(true);
- }
- }
- });
+ } catch (Exception e) {
+ Logger.logError(e);
+ } finally {
+ DirtyHack.setFireEnabled(true);
+ DirtyHack.setEditorModificationEnabled(true);
+ }
+ }
+ });
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java
index 0739878..b5aa199 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java
@@ -33,84 +33,84 @@
private static KeyTreeItemTransfer transfer = new KeyTreeItemTransfer();
public static KeyTreeItemTransfer getInstance() {
- return transfer;
+ return transfer;
}
public void javaToNative(Object object, TransferData transferData) {
- if (!checkType(object) || !isSupportedType(transferData)) {
- DND.error(DND.ERROR_INVALID_DATA);
- }
- IKeyTreeNode[] terms = (IKeyTreeNode[]) object;
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ObjectOutputStream oOut = new ObjectOutputStream(out);
- for (int i = 0, length = terms.length; i < length; i++) {
- oOut.writeObject(terms[i]);
- }
- byte[] buffer = out.toByteArray();
- oOut.close();
+ if (!checkType(object) || !isSupportedType(transferData)) {
+ DND.error(DND.ERROR_INVALID_DATA);
+ }
+ IKeyTreeNode[] terms = (IKeyTreeNode[]) object;
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ObjectOutputStream oOut = new ObjectOutputStream(out);
+ for (int i = 0, length = terms.length; i < length; i++) {
+ oOut.writeObject(terms[i]);
+ }
+ byte[] buffer = out.toByteArray();
+ oOut.close();
- super.javaToNative(buffer, transferData);
- } catch (IOException e) {
- Logger.logError(e);
- }
+ super.javaToNative(buffer, transferData);
+ } catch (IOException e) {
+ Logger.logError(e);
+ }
}
public Object nativeToJava(TransferData transferData) {
- if (isSupportedType(transferData)) {
+ if (isSupportedType(transferData)) {
- byte[] buffer;
- try {
- buffer = (byte[]) super.nativeToJava(transferData);
- } catch (Exception e) {
- Logger.logError(e);
- buffer = null;
- }
- if (buffer == null)
- return null;
+ byte[] buffer;
+ try {
+ buffer = (byte[]) super.nativeToJava(transferData);
+ } catch (Exception e) {
+ Logger.logError(e);
+ buffer = null;
+ }
+ if (buffer == null)
+ return null;
- List<IKeyTreeNode> terms = new ArrayList<IKeyTreeNode>();
- try {
- ByteArrayInputStream in = new ByteArrayInputStream(buffer);
- ObjectInputStream readIn = new ObjectInputStream(in);
- // while (readIn.available() > 0) {
- IKeyTreeNode newTerm = (IKeyTreeNode) readIn.readObject();
- terms.add(newTerm);
- // }
- readIn.close();
- } catch (Exception ex) {
- Logger.logError(ex);
- return null;
- }
- return terms.toArray(new IKeyTreeNode[terms.size()]);
- }
+ List<IKeyTreeNode> terms = new ArrayList<IKeyTreeNode>();
+ try {
+ ByteArrayInputStream in = new ByteArrayInputStream(buffer);
+ ObjectInputStream readIn = new ObjectInputStream(in);
+ // while (readIn.available() > 0) {
+ IKeyTreeNode newTerm = (IKeyTreeNode) readIn.readObject();
+ terms.add(newTerm);
+ // }
+ readIn.close();
+ } catch (Exception ex) {
+ Logger.logError(ex);
+ return null;
+ }
+ return terms.toArray(new IKeyTreeNode[terms.size()]);
+ }
- return null;
+ return null;
}
protected String[] getTypeNames() {
- return new String[] { KEY_TREE_ITEM };
+ return new String[] { KEY_TREE_ITEM };
}
protected int[] getTypeIds() {
- return new int[] { TYPEID };
+ return new int[] { TYPEID };
}
boolean checkType(Object object) {
- if (object == null || !(object instanceof IKeyTreeNode[])
- || ((IKeyTreeNode[]) object).length == 0) {
- return false;
- }
- IKeyTreeNode[] myTypes = (IKeyTreeNode[]) object;
- for (int i = 0; i < myTypes.length; i++) {
- if (myTypes[i] == null) {
- return false;
- }
- }
- return true;
+ if (object == null || !(object instanceof IKeyTreeNode[])
+ || ((IKeyTreeNode[]) object).length == 0) {
+ return false;
+ }
+ IKeyTreeNode[] myTypes = (IKeyTreeNode[]) object;
+ for (int i = 0; i < myTypes.length; i++) {
+ if (myTypes[i] == null) {
+ return false;
+ }
+ }
+ return true;
}
protected boolean validate(Object object) {
- return checkType(object);
+ return checkType(object);
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java
index d6c0094..8329c58 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java
@@ -22,8 +22,8 @@
private String bundleId;
public MessagesDragSource(TreeViewer sourceView, String bundleId) {
- source = sourceView;
- this.bundleId = bundleId;
+ source = sourceView;
+ this.bundleId = bundleId;
}
@Override
@@ -33,22 +33,22 @@
@Override
public void dragSetData(DragSourceEvent event) {
- IKeyTreeNode selectionObject = (IKeyTreeNode) ((IStructuredSelection) source
- .getSelection()).toList().get(0);
+ IKeyTreeNode selectionObject = (IKeyTreeNode) ((IStructuredSelection) source
+ .getSelection()).toList().get(0);
- String key = selectionObject.getMessageKey();
+ String key = selectionObject.getMessageKey();
- // TODO Solve the problem that its not possible to retrieve the editor
- // position of the drop event
+ // TODO Solve the problem that its not possible to retrieve the editor
+ // position of the drop event
- // event.data = "(new ResourceBundle(\"" + bundleId +
- // "\")).getString(\"" + key + "\")";
- event.data = "\"" + key + "\"";
+ // event.data = "(new ResourceBundle(\"" + bundleId +
+ // "\")).getString(\"" + key + "\")";
+ event.data = "\"" + key + "\"";
}
@Override
public void dragStart(DragSourceEvent event) {
- event.doit = !source.getSelection().isEmpty();
+ event.doit = !source.getSelection().isEmpty();
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java
index 8d0906a..be8e81f 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java
@@ -28,48 +28,48 @@
private String bundleName;
public MessagesDropTarget(TreeViewer viewer, String projectName,
- String bundleName) {
- super();
- this.projectName = projectName;
- this.bundleName = bundleName;
+ String bundleName) {
+ super();
+ this.projectName = projectName;
+ this.bundleName = bundleName;
}
public void dragEnter(DropTargetEvent event) {
}
public void drop(DropTargetEvent event) {
- if (event.detail != DND.DROP_COPY)
- return;
+ if (event.detail != DND.DROP_COPY)
+ return;
- if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) {
- // event.feedback = DND.FEEDBACK_INSERT_BEFORE;
- String newKeyPrefix = "";
+ if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) {
+ // event.feedback = DND.FEEDBACK_INSERT_BEFORE;
+ String newKeyPrefix = "";
- if (event.item instanceof TreeItem
- && ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) {
- newKeyPrefix = ((IValuedKeyTreeNode) ((TreeItem) event.item)
- .getData()).getMessageKey();
- }
+ if (event.item instanceof TreeItem
+ && ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) {
+ newKeyPrefix = ((IValuedKeyTreeNode) ((TreeItem) event.item)
+ .getData()).getMessageKey();
+ }
- String message = (String) event.data;
+ String message = (String) event.data;
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell());
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
- DialogConfiguration config = dialog.new DialogConfiguration();
- config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix
- + "." + "[Platzhalter]"
- : "");
- config.setPreselectedMessage(message);
- config.setPreselectedBundle(bundleName);
- config.setPreselectedLocale("");
- config.setProjectName(projectName);
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix
+ + "." + "[Platzhalter]"
+ : "");
+ config.setPreselectedMessage(message);
+ config.setPreselectedBundle(bundleName);
+ config.setPreselectedLocale("");
+ config.setProjectName(projectName);
- dialog.setDialogConfiguration(config);
+ dialog.setDialogConfiguration(config);
- if (dialog.open() != InputDialog.OK)
- return;
- } else
- event.detail = DND.DROP_NONE;
+ if (dialog.open() != InputDialog.OK)
+ return;
+ } else
+ event.detail = DND.DROP_NONE;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java
index b4900a4..71d64d2 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java
@@ -90,7 +90,7 @@
import org.eclipse.ui.PlatformUI;
public class PropertyKeySelectionTree extends Composite implements
- IResourceBundleChangedListener {
+ IResourceBundleChangedListener {
private final int KEY_COLUMN_WEIGHT = 1;
private final int LOCALE_COLUMN_WEIGHT = 1;
@@ -130,686 +130,686 @@
private String projectName;
public PropertyKeySelectionTree(IViewSite viewSite,
- IWorkbenchPartSite site, Composite parent, int style,
- String projectName, String resources, List<Locale> locales) {
- super(parent, style);
- this.site = site;
- this.resourceBundle = resources;
- this.projectName = projectName;
+ IWorkbenchPartSite site, Composite parent, int style,
+ String projectName, String resources, List<Locale> locales) {
+ super(parent, style);
+ this.site = site;
+ this.resourceBundle = resources;
+ this.projectName = projectName;
- if (resourceBundle != null && resourceBundle.trim().length() > 0) {
- if (locales == null)
- initVisibleLocales();
- else
- this.visibleLocales = locales;
- }
+ if (resourceBundle != null && resourceBundle.trim().length() > 0) {
+ if (locales == null)
+ initVisibleLocales();
+ else
+ this.visibleLocales = locales;
+ }
- constructWidget();
+ constructWidget();
- if (resourceBundle != null && resourceBundle.trim().length() > 0) {
- initTreeViewer();
- initMatchers();
- initSorters();
- treeViewer.expandAll();
- }
+ if (resourceBundle != null && resourceBundle.trim().length() > 0) {
+ initTreeViewer();
+ initMatchers();
+ initSorters();
+ treeViewer.expandAll();
+ }
- hookDragAndDrop();
- registerListeners();
+ hookDragAndDrop();
+ registerListeners();
}
@Override
public void dispose() {
- super.dispose();
- unregisterListeners();
+ super.dispose();
+ unregisterListeners();
}
protected void initSorters() {
- sorter = new ValuedKeyTreeItemSorter(treeViewer, sortInfo);
- treeViewer.setSorter(sorter);
+ sorter = new ValuedKeyTreeItemSorter(treeViewer, sortInfo);
+ treeViewer.setSorter(sorter);
}
public void enableFuzzyMatching(boolean enable) {
- String pattern = "";
- if (matcher != null) {
- pattern = matcher.getPattern();
+ String pattern = "";
+ if (matcher != null) {
+ pattern = matcher.getPattern();
- if (!fuzzyMatchingEnabled && enable) {
- if (matcher.getPattern().trim().length() > 1
- && matcher.getPattern().startsWith("*")
- && matcher.getPattern().endsWith("*"))
- pattern = pattern.substring(1).substring(0,
- pattern.length() - 2);
- matcher.setPattern(null);
- }
- }
- fuzzyMatchingEnabled = enable;
- initMatchers();
+ if (!fuzzyMatchingEnabled && enable) {
+ if (matcher.getPattern().trim().length() > 1
+ && matcher.getPattern().startsWith("*")
+ && matcher.getPattern().endsWith("*"))
+ pattern = pattern.substring(1).substring(0,
+ pattern.length() - 2);
+ matcher.setPattern(null);
+ }
+ }
+ fuzzyMatchingEnabled = enable;
+ initMatchers();
- matcher.setPattern(pattern);
- treeViewer.refresh();
+ matcher.setPattern(pattern);
+ treeViewer.refresh();
}
public boolean isFuzzyMatchingEnabled() {
- return fuzzyMatchingEnabled;
+ return fuzzyMatchingEnabled;
}
protected void initMatchers() {
- treeViewer.resetFilters();
+ treeViewer.resetFilters();
- if (fuzzyMatchingEnabled) {
- matcher = new FuzzyMatcher(treeViewer);
- ((FuzzyMatcher) matcher).setMinimumSimilarity(matchingPrecision);
- } else
- matcher = new ExactMatcher(treeViewer);
+ if (fuzzyMatchingEnabled) {
+ matcher = new FuzzyMatcher(treeViewer);
+ ((FuzzyMatcher) matcher).setMinimumSimilarity(matchingPrecision);
+ } else
+ matcher = new ExactMatcher(treeViewer);
}
protected void initTreeViewer() {
- this.setRedraw(false);
- // init content provider
- contentProvider = new ResKeyTreeContentProvider(visibleLocales,
- projectName, resourceBundle, treeType);
- treeViewer.setContentProvider(contentProvider);
+ this.setRedraw(false);
+ // init content provider
+ contentProvider = new ResKeyTreeContentProvider(visibleLocales,
+ projectName, resourceBundle, treeType);
+ treeViewer.setContentProvider(contentProvider);
- // init label provider
- labelProvider = new ResKeyTreeLabelProvider(visibleLocales);
- treeViewer.setLabelProvider(labelProvider);
+ // init label provider
+ labelProvider = new ResKeyTreeLabelProvider(visibleLocales);
+ treeViewer.setLabelProvider(labelProvider);
- // we need this to keep the tree expanded
- treeViewer.setComparer(new IElementComparer() {
+ // we need this to keep the tree expanded
+ treeViewer.setComparer(new IElementComparer() {
- @Override
- public int hashCode(Object element) {
- final int prime = 31;
- int result = 1;
- result = prime * result
- + ((toString() == null) ? 0 : toString().hashCode());
- return result;
- }
+ @Override
+ public int hashCode(Object element) {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result
+ + ((toString() == null) ? 0 : toString().hashCode());
+ return result;
+ }
- @Override
- public boolean equals(Object a, Object b) {
- if (a == b) {
- return true;
- }
- if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) {
- IKeyTreeNode nodeA = (IKeyTreeNode) a;
- IKeyTreeNode nodeB = (IKeyTreeNode) b;
- return nodeA.equals(nodeB);
- }
- return false;
- }
- });
+ @Override
+ public boolean equals(Object a, Object b) {
+ if (a == b) {
+ return true;
+ }
+ if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) {
+ IKeyTreeNode nodeA = (IKeyTreeNode) a;
+ IKeyTreeNode nodeB = (IKeyTreeNode) b;
+ return nodeA.equals(nodeB);
+ }
+ return false;
+ }
+ });
- setTreeStructure();
- this.setRedraw(true);
+ setTreeStructure();
+ this.setRedraw(true);
}
public void setTreeStructure() {
- IAbstractKeyTreeModel model = KeyTreeFactory
- .createModel(ResourceBundleManager.getManager(projectName)
- .getResourceBundle(resourceBundle));
- if (treeViewer.getInput() == null) {
- treeViewer.setUseHashlookup(true);
- }
- org.eclipse.jface.viewers.TreePath[] expandedTreePaths = treeViewer
- .getExpandedTreePaths();
- treeViewer.setInput(model);
- treeViewer.refresh();
- treeViewer.setExpandedTreePaths(expandedTreePaths);
+ IAbstractKeyTreeModel model = KeyTreeFactory
+ .createModel(ResourceBundleManager.getManager(projectName)
+ .getResourceBundle(resourceBundle));
+ if (treeViewer.getInput() == null) {
+ treeViewer.setUseHashlookup(true);
+ }
+ org.eclipse.jface.viewers.TreePath[] expandedTreePaths = treeViewer
+ .getExpandedTreePaths();
+ treeViewer.setInput(model);
+ treeViewer.refresh();
+ treeViewer.setExpandedTreePaths(expandedTreePaths);
}
protected void refreshContent(ResourceBundleChangedEvent event) {
- if (visibleLocales == null) {
- initVisibleLocales();
- }
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(projectName);
+ if (visibleLocales == null) {
+ initVisibleLocales();
+ }
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
- // update content provider
- contentProvider.setLocales(visibleLocales);
- contentProvider.setProjectName(manager.getProject().getName());
- contentProvider.setBundleId(resourceBundle);
+ // update content provider
+ contentProvider.setLocales(visibleLocales);
+ contentProvider.setProjectName(manager.getProject().getName());
+ contentProvider.setBundleId(resourceBundle);
- // init label provider
- IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle);
- labelProvider.setLocales(visibleLocales);
- if (treeViewer.getLabelProvider() != labelProvider)
- treeViewer.setLabelProvider(labelProvider);
+ // init label provider
+ IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle);
+ labelProvider.setLocales(visibleLocales);
+ if (treeViewer.getLabelProvider() != labelProvider)
+ treeViewer.setLabelProvider(labelProvider);
- // define input of treeviewer
- setTreeStructure();
+ // define input of treeviewer
+ setTreeStructure();
}
protected void initVisibleLocales() {
- SortedMap<String, Locale> locSorted = new TreeMap<String, Locale>();
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(projectName);
- sortInfo = new SortInfo();
- visibleLocales.clear();
- if (resourceBundle != null) {
- for (Locale l : manager.getProvidedLocales(resourceBundle)) {
- if (l == null) {
- locSorted.put("Default", null);
- } else {
- locSorted.put(l.getDisplayName(uiLocale), l);
- }
- }
- }
+ SortedMap<String, Locale> locSorted = new TreeMap<String, Locale>();
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ sortInfo = new SortInfo();
+ visibleLocales.clear();
+ if (resourceBundle != null) {
+ for (Locale l : manager.getProvidedLocales(resourceBundle)) {
+ if (l == null) {
+ locSorted.put("Default", null);
+ } else {
+ locSorted.put(l.getDisplayName(uiLocale), l);
+ }
+ }
+ }
- for (String lString : locSorted.keySet()) {
- visibleLocales.add(locSorted.get(lString));
- }
- sortInfo.setVisibleLocales(visibleLocales);
+ for (String lString : locSorted.keySet()) {
+ visibleLocales.add(locSorted.get(lString));
+ }
+ sortInfo.setVisibleLocales(visibleLocales);
}
protected void constructWidget() {
- basicLayout = new TreeColumnLayout();
- this.setLayout(basicLayout);
+ basicLayout = new TreeColumnLayout();
+ this.setLayout(basicLayout);
- treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE
- | SWT.BORDER);
- Tree tree = treeViewer.getTree();
+ treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE
+ | SWT.BORDER);
+ Tree tree = treeViewer.getTree();
- if (resourceBundle != null) {
- tree.setHeaderVisible(true);
- tree.setLinesVisible(true);
+ if (resourceBundle != null) {
+ tree.setHeaderVisible(true);
+ tree.setLinesVisible(true);
- // create tree-columns
- constructTreeColumns(tree);
- } else {
- tree.setHeaderVisible(false);
- tree.setLinesVisible(false);
- }
+ // create tree-columns
+ constructTreeColumns(tree);
+ } else {
+ tree.setHeaderVisible(false);
+ tree.setLinesVisible(false);
+ }
- makeActions();
- hookDoubleClickAction();
+ makeActions();
+ hookDoubleClickAction();
- // register messages table as selection provider
- site.setSelectionProvider(treeViewer);
+ // register messages table as selection provider
+ site.setSelectionProvider(treeViewer);
}
protected void constructTreeColumns(Tree tree) {
- tree.removeAll();
- // tree.getColumns().length;
+ tree.removeAll();
+ // tree.getColumns().length;
- // construct key-column
- keyColumn = new TreeColumn(tree, SWT.NONE);
- keyColumn.setText("Key");
- keyColumn.addSelectionListener(new SelectionListener() {
+ // construct key-column
+ keyColumn = new TreeColumn(tree, SWT.NONE);
+ keyColumn.setText("Key");
+ keyColumn.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSorter(0);
- }
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSorter(0);
+ }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSorter(0);
- }
- });
- basicLayout.setColumnData(keyColumn, new ColumnWeightData(
- KEY_COLUMN_WEIGHT));
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSorter(0);
+ }
+ });
+ basicLayout.setColumnData(keyColumn, new ColumnWeightData(
+ KEY_COLUMN_WEIGHT));
- if (visibleLocales != null) {
- final ResourceBundleManager manager = ResourceBundleManager
- .getManager(projectName);
- for (final Locale l : visibleLocales) {
- TreeColumn col = new TreeColumn(tree, SWT.NONE);
+ if (visibleLocales != null) {
+ final ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ for (final Locale l : visibleLocales) {
+ TreeColumn col = new TreeColumn(tree, SWT.NONE);
- // Add editing support to this table column
- TreeViewerColumn tCol = new TreeViewerColumn(treeViewer, col);
- tCol.setEditingSupport(new EditingSupport(treeViewer) {
+ // Add editing support to this table column
+ TreeViewerColumn tCol = new TreeViewerColumn(treeViewer, col);
+ tCol.setEditingSupport(new EditingSupport(treeViewer) {
- TextCellEditor editor = null;
+ TextCellEditor editor = null;
- @Override
- protected void setValue(Object element, Object value) {
+ @Override
+ protected void setValue(Object element, Object value) {
- if (element instanceof IValuedKeyTreeNode) {
- IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
- String activeKey = vkti.getMessageKey();
+ if (element instanceof IValuedKeyTreeNode) {
+ IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
+ String activeKey = vkti.getMessageKey();
- if (activeKey != null) {
- IMessagesBundleGroup bundleGroup = manager
- .getResourceBundle(resourceBundle);
- IMessage entry = bundleGroup.getMessage(
- activeKey, l);
+ if (activeKey != null) {
+ IMessagesBundleGroup bundleGroup = manager
+ .getResourceBundle(resourceBundle);
+ IMessage entry = bundleGroup.getMessage(
+ activeKey, l);
- if (entry == null
- || !value.equals(entry.getValue())) {
- String comment = null;
- if (entry != null) {
- comment = entry.getComment();
- }
+ if (entry == null
+ || !value.equals(entry.getValue())) {
+ String comment = null;
+ if (entry != null) {
+ comment = entry.getComment();
+ }
- IMessagesBundle messagesBundle = bundleGroup
- .getMessagesBundle(l);
+ IMessagesBundle messagesBundle = bundleGroup
+ .getMessagesBundle(l);
- DirtyHack.setFireEnabled(false);
+ DirtyHack.setFireEnabled(false);
- IMessage message = messagesBundle
- .getMessage(activeKey);
- if (message == null) {
- IMessage newMessage = MessageFactory
- .createMessage(activeKey, l);
- newMessage.setText(String
- .valueOf(value));
- newMessage.setComment(comment);
- messagesBundle.addMessage(newMessage);
- } else {
- message.setText(String.valueOf(value));
- message.setComment(comment);
- }
+ IMessage message = messagesBundle
+ .getMessage(activeKey);
+ if (message == null) {
+ IMessage newMessage = MessageFactory
+ .createMessage(activeKey, l);
+ newMessage.setText(String
+ .valueOf(value));
+ newMessage.setComment(comment);
+ messagesBundle.addMessage(newMessage);
+ } else {
+ message.setText(String.valueOf(value));
+ message.setComment(comment);
+ }
- FileUtils.writeToFile(messagesBundle);
- RBManager
- .getInstance(manager.getProject())
- .fireResourceChanged(messagesBundle);
+ FileUtils.writeToFile(messagesBundle);
+ RBManager
+ .getInstance(manager.getProject())
+ .fireResourceChanged(messagesBundle);
- // update TreeViewer
- vkti.setValue(l, String.valueOf(value));
- treeViewer.refresh();
+ // update TreeViewer
+ vkti.setValue(l, String.valueOf(value));
+ treeViewer.refresh();
- DirtyHack.setFireEnabled(true);
- }
- }
- }
- }
+ DirtyHack.setFireEnabled(true);
+ }
+ }
+ }
+ }
- @Override
- protected Object getValue(Object element) {
- return labelProvider.getColumnText(element,
- visibleLocales.indexOf(l) + 1);
- }
+ @Override
+ protected Object getValue(Object element) {
+ return labelProvider.getColumnText(element,
+ visibleLocales.indexOf(l) + 1);
+ }
- @Override
- protected CellEditor getCellEditor(Object element) {
- if (editor == null) {
- Composite tree = (Composite) treeViewer
- .getControl();
- editor = new TextCellEditor(tree);
- editor.getControl().addTraverseListener(
- new TraverseListener() {
+ @Override
+ protected CellEditor getCellEditor(Object element) {
+ if (editor == null) {
+ Composite tree = (Composite) treeViewer
+ .getControl();
+ editor = new TextCellEditor(tree);
+ editor.getControl().addTraverseListener(
+ new TraverseListener() {
- @Override
- public void keyTraversed(TraverseEvent e) {
- Logger.logInfo("CELL_EDITOR: "
- + e.toString());
- if (e.detail == SWT.TRAVERSE_TAB_NEXT
- || e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
+ @Override
+ public void keyTraversed(TraverseEvent e) {
+ Logger.logInfo("CELL_EDITOR: "
+ + e.toString());
+ if (e.detail == SWT.TRAVERSE_TAB_NEXT
+ || e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
- e.doit = false;
- int colIndex = visibleLocales
- .indexOf(l) + 1;
- Object sel = ((IStructuredSelection) treeViewer
- .getSelection())
- .getFirstElement();
- int noOfCols = treeViewer
- .getTree()
- .getColumnCount();
+ e.doit = false;
+ int colIndex = visibleLocales
+ .indexOf(l) + 1;
+ Object sel = ((IStructuredSelection) treeViewer
+ .getSelection())
+ .getFirstElement();
+ int noOfCols = treeViewer
+ .getTree()
+ .getColumnCount();
- // go to next cell
- if (e.detail == SWT.TRAVERSE_TAB_NEXT) {
- int nextColIndex = colIndex + 1;
- if (nextColIndex < noOfCols)
- treeViewer.editElement(
- sel,
- nextColIndex);
- // go to previous cell
- } else if (e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
- int prevColIndex = colIndex - 1;
- if (prevColIndex > 0)
- treeViewer.editElement(
- sel,
- colIndex - 1);
- }
- }
- }
- });
- }
- return editor;
- }
+ // go to next cell
+ if (e.detail == SWT.TRAVERSE_TAB_NEXT) {
+ int nextColIndex = colIndex + 1;
+ if (nextColIndex < noOfCols)
+ treeViewer.editElement(
+ sel,
+ nextColIndex);
+ // go to previous cell
+ } else if (e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
+ int prevColIndex = colIndex - 1;
+ if (prevColIndex > 0)
+ treeViewer.editElement(
+ sel,
+ colIndex - 1);
+ }
+ }
+ }
+ });
+ }
+ return editor;
+ }
- @Override
- protected boolean canEdit(Object element) {
- return editable;
- }
- });
+ @Override
+ protected boolean canEdit(Object element) {
+ return editable;
+ }
+ });
- String displayName = l == null ? ResourceBundleManager.defaultLocaleTag
- : l.getDisplayName(uiLocale);
+ String displayName = l == null ? ResourceBundleManager.defaultLocaleTag
+ : l.getDisplayName(uiLocale);
- col.setText(displayName);
- col.addSelectionListener(new SelectionListener() {
+ col.setText(displayName);
+ col.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSorter(visibleLocales.indexOf(l) + 1);
- }
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSorter(visibleLocales.indexOf(l) + 1);
+ }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSorter(visibleLocales.indexOf(l) + 1);
- }
- });
- basicLayout.setColumnData(col, new ColumnWeightData(
- LOCALE_COLUMN_WEIGHT));
- }
- }
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSorter(visibleLocales.indexOf(l) + 1);
+ }
+ });
+ basicLayout.setColumnData(col, new ColumnWeightData(
+ LOCALE_COLUMN_WEIGHT));
+ }
+ }
}
protected void updateSorter(int idx) {
- SortInfo sortInfo = sorter.getSortInfo();
- if (idx == sortInfo.getColIdx())
- sortInfo.setDESC(!sortInfo.isDESC());
- else {
- sortInfo.setColIdx(idx);
- sortInfo.setDESC(false);
- }
- sortInfo.setVisibleLocales(visibleLocales);
- sorter.setSortInfo(sortInfo);
- treeType = idx == 0 ? TreeType.Tree : TreeType.Flat;
- setTreeStructure();
- treeViewer.refresh();
+ SortInfo sortInfo = sorter.getSortInfo();
+ if (idx == sortInfo.getColIdx())
+ sortInfo.setDESC(!sortInfo.isDESC());
+ else {
+ sortInfo.setColIdx(idx);
+ sortInfo.setDESC(false);
+ }
+ sortInfo.setVisibleLocales(visibleLocales);
+ sorter.setSortInfo(sortInfo);
+ treeType = idx == 0 ? TreeType.Tree : TreeType.Flat;
+ setTreeStructure();
+ treeViewer.refresh();
}
@Override
public boolean setFocus() {
- return treeViewer.getControl().setFocus();
+ return treeViewer.getControl().setFocus();
}
/*** DRAG AND DROP ***/
protected void hookDragAndDrop() {
- // KeyTreeItemDragSource ktiSource = new KeyTreeItemDragSource
- // (treeViewer);
- KeyTreeItemDropTarget ktiTarget = new KeyTreeItemDropTarget(treeViewer);
- MessagesDragSource source = new MessagesDragSource(treeViewer,
- this.resourceBundle);
- MessagesDropTarget target = new MessagesDropTarget(treeViewer,
- projectName, resourceBundle);
+ // KeyTreeItemDragSource ktiSource = new KeyTreeItemDragSource
+ // (treeViewer);
+ KeyTreeItemDropTarget ktiTarget = new KeyTreeItemDropTarget(treeViewer);
+ MessagesDragSource source = new MessagesDragSource(treeViewer,
+ this.resourceBundle);
+ MessagesDropTarget target = new MessagesDropTarget(treeViewer,
+ projectName, resourceBundle);
- // Initialize drag source for copy event
- DragSource dragSource = new DragSource(treeViewer.getControl(),
- DND.DROP_COPY | DND.DROP_MOVE);
- dragSource.setTransfer(new Transfer[] { TextTransfer.getInstance() });
- // dragSource.addDragListener(ktiSource);
- dragSource.addDragListener(source);
+ // Initialize drag source for copy event
+ DragSource dragSource = new DragSource(treeViewer.getControl(),
+ DND.DROP_COPY | DND.DROP_MOVE);
+ dragSource.setTransfer(new Transfer[] { TextTransfer.getInstance() });
+ // dragSource.addDragListener(ktiSource);
+ dragSource.addDragListener(source);
- // Initialize drop target for copy event
- DropTarget dropTarget = new DropTarget(treeViewer.getControl(),
- DND.DROP_MOVE | DND.DROP_COPY);
- dropTarget.setTransfer(new Transfer[] { TextTransfer.getInstance(),
- JavaUI.getJavaElementClipboardTransfer() });
- dropTarget.addDropListener(ktiTarget);
- dropTarget.addDropListener(target);
+ // Initialize drop target for copy event
+ DropTarget dropTarget = new DropTarget(treeViewer.getControl(),
+ DND.DROP_MOVE | DND.DROP_COPY);
+ dropTarget.setTransfer(new Transfer[] { TextTransfer.getInstance(),
+ JavaUI.getJavaElementClipboardTransfer() });
+ dropTarget.addDropListener(ktiTarget);
+ dropTarget.addDropListener(target);
}
/*** ACTIONS ***/
private void makeActions() {
- doubleClickAction = new Action() {
+ doubleClickAction = new Action() {
- @Override
- public void run() {
- editSelectedItem();
- }
+ @Override
+ public void run() {
+ editSelectedItem();
+ }
- };
+ };
}
private void hookDoubleClickAction() {
- treeViewer.addDoubleClickListener(new IDoubleClickListener() {
+ treeViewer.addDoubleClickListener(new IDoubleClickListener() {
- public void doubleClick(DoubleClickEvent event) {
- doubleClickAction.run();
- }
- });
+ public void doubleClick(DoubleClickEvent event) {
+ doubleClickAction.run();
+ }
+ });
}
/*** SELECTION LISTENER ***/
protected void registerListeners() {
- this.editorListener = new MessagesEditorListener();
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(projectName);
- if (manager != null) {
- RBManager.getInstance(manager.getProject())
- .addMessagesEditorListener(editorListener);
- }
+ this.editorListener = new MessagesEditorListener();
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ if (manager != null) {
+ RBManager.getInstance(manager.getProject())
+ .addMessagesEditorListener(editorListener);
+ }
- treeViewer.getControl().addKeyListener(new KeyAdapter() {
+ treeViewer.getControl().addKeyListener(new KeyAdapter() {
- public void keyPressed(KeyEvent event) {
- if (event.character == SWT.DEL && event.stateMask == 0) {
- deleteSelectedItems();
- }
- }
- });
+ public void keyPressed(KeyEvent event) {
+ if (event.character == SWT.DEL && event.stateMask == 0) {
+ deleteSelectedItems();
+ }
+ }
+ });
}
protected void unregisterListeners() {
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(projectName);
- if (manager != null) {
- RBManager.getInstance(manager.getProject())
- .removeMessagesEditorListener(editorListener);
- }
- treeViewer.removeSelectionChangedListener(selectionChangedListener);
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ if (manager != null) {
+ RBManager.getInstance(manager.getProject())
+ .removeMessagesEditorListener(editorListener);
+ }
+ treeViewer.removeSelectionChangedListener(selectionChangedListener);
}
public void addSelectionChangedListener(ISelectionChangedListener listener) {
- treeViewer.addSelectionChangedListener(listener);
- selectionChangedListener = listener;
+ treeViewer.addSelectionChangedListener(listener);
+ selectionChangedListener = listener;
}
@Override
public void resourceBundleChanged(final ResourceBundleChangedEvent event) {
- if (event.getType() != ResourceBundleChangedEvent.MODIFIED
- || !event.getBundle().equals(this.getResourceBundle()))
- return;
+ if (event.getType() != ResourceBundleChangedEvent.MODIFIED
+ || !event.getBundle().equals(this.getResourceBundle()))
+ return;
- if (Display.getCurrent() != null) {
- refreshViewer(event, true);
- return;
- }
+ if (Display.getCurrent() != null) {
+ refreshViewer(event, true);
+ return;
+ }
- Display.getDefault().asyncExec(new Runnable() {
+ Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- refreshViewer(event, true);
- }
- });
+ public void run() {
+ refreshViewer(event, true);
+ }
+ });
}
private void refreshViewer(ResourceBundleChangedEvent event,
- boolean computeVisibleLocales) {
- // manager.loadResourceBundle(resourceBundle);
- if (computeVisibleLocales) {
- refreshContent(event);
- }
+ boolean computeVisibleLocales) {
+ // manager.loadResourceBundle(resourceBundle);
+ if (computeVisibleLocales) {
+ refreshContent(event);
+ }
- // Display.getDefault().asyncExec(new Runnable() {
- // public void run() {
- treeViewer.refresh();
- // }
- // });
+ // Display.getDefault().asyncExec(new Runnable() {
+ // public void run() {
+ treeViewer.refresh();
+ // }
+ // });
}
public StructuredViewer getViewer() {
- return this.treeViewer;
+ return this.treeViewer;
}
public void setSearchString(String pattern) {
- matcher.setPattern(pattern);
- treeType = matcher.getPattern().trim().length() > 0 ? TreeType.Flat
- : TreeType.Tree;
- labelProvider.setSearchEnabled(treeType.equals(TreeType.Flat));
- // WTF?
- treeType = treeType.equals(TreeType.Tree)
- && sorter.getSortInfo().getColIdx() == 0 ? TreeType.Tree
- : TreeType.Flat;
- treeViewer.refresh();
+ matcher.setPattern(pattern);
+ treeType = matcher.getPattern().trim().length() > 0 ? TreeType.Flat
+ : TreeType.Tree;
+ labelProvider.setSearchEnabled(treeType.equals(TreeType.Flat));
+ // WTF?
+ treeType = treeType.equals(TreeType.Tree)
+ && sorter.getSortInfo().getColIdx() == 0 ? TreeType.Tree
+ : TreeType.Flat;
+ treeViewer.refresh();
- this.refreshContent(null);
+ this.refreshContent(null);
- // highlight the search results
- labelProvider.updateTreeViewer(treeViewer);
+ // highlight the search results
+ labelProvider.updateTreeViewer(treeViewer);
}
public SortInfo getSortInfo() {
- if (this.sorter != null)
- return this.sorter.getSortInfo();
- else
- return null;
+ if (this.sorter != null)
+ return this.sorter.getSortInfo();
+ else
+ return null;
}
public void setSortInfo(SortInfo sortInfo) {
- sortInfo.setVisibleLocales(visibleLocales);
- if (sorter != null) {
- sorter.setSortInfo(sortInfo);
- treeType = sortInfo.getColIdx() == 0 ? TreeType.Tree
- : TreeType.Flat;
- treeViewer.refresh();
- }
+ sortInfo.setVisibleLocales(visibleLocales);
+ if (sorter != null) {
+ sorter.setSortInfo(sortInfo);
+ treeType = sortInfo.getColIdx() == 0 ? TreeType.Tree
+ : TreeType.Flat;
+ treeViewer.refresh();
+ }
}
public String getSearchString() {
- return matcher.getPattern();
+ return matcher.getPattern();
}
public boolean isEditable() {
- return editable;
+ return editable;
}
public void setEditable(boolean editable) {
- this.editable = editable;
+ this.editable = editable;
}
public List<Locale> getVisibleLocales() {
- return visibleLocales;
+ return visibleLocales;
}
public String getResourceBundle() {
- return resourceBundle;
+ return resourceBundle;
}
public void editSelectedItem() {
- String key = "";
- ISelection selection = treeViewer.getSelection();
- if (selection instanceof IStructuredSelection) {
- IStructuredSelection structSel = (IStructuredSelection) selection;
- if (structSel.getFirstElement() instanceof IKeyTreeNode) {
- IKeyTreeNode keyTreeNode = (IKeyTreeNode) structSel
- .getFirstElement();
- key = keyTreeNode.getMessageKey();
- }
- }
+ String key = "";
+ ISelection selection = treeViewer.getSelection();
+ if (selection instanceof IStructuredSelection) {
+ IStructuredSelection structSel = (IStructuredSelection) selection;
+ if (structSel.getFirstElement() instanceof IKeyTreeNode) {
+ IKeyTreeNode keyTreeNode = (IKeyTreeNode) structSel
+ .getFirstElement();
+ key = keyTreeNode.getMessageKey();
+ }
+ }
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(projectName);
- EditorUtils.openEditor(site.getPage(),
- manager.getRandomFile(resourceBundle),
- EditorUtils.RESOURCE_BUNDLE_EDITOR, key);
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ EditorUtils.openEditor(site.getPage(),
+ manager.getRandomFile(resourceBundle),
+ EditorUtils.RESOURCE_BUNDLE_EDITOR, key);
}
public void deleteSelectedItems() {
- List<String> keys = new ArrayList<String>();
+ List<String> keys = new ArrayList<String>();
- IWorkbenchWindow window = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow();
- ISelection selection = window.getActivePage().getSelection();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection) selection)
- .iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof IKeyTreeNode) {
- addKeysToRemove((IKeyTreeNode) elem, keys);
- }
- }
- }
+ IWorkbenchWindow window = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow();
+ ISelection selection = window.getActivePage().getSelection();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection)
+ .iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof IKeyTreeNode) {
+ addKeysToRemove((IKeyTreeNode) elem, keys);
+ }
+ }
+ }
- try {
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(projectName);
- manager.removeResourceBundleEntry(getResourceBundle(), keys);
- } catch (Exception ex) {
- Logger.logError(ex);
- }
+ try {
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ manager.removeResourceBundleEntry(getResourceBundle(), keys);
+ } catch (Exception ex) {
+ Logger.logError(ex);
+ }
}
private void addKeysToRemove(IKeyTreeNode node, List<String> keys) {
- keys.add(node.getMessageKey());
- for (IKeyTreeNode ktn : node.getChildren()) {
- addKeysToRemove(ktn, keys);
- }
+ keys.add(node.getMessageKey());
+ for (IKeyTreeNode ktn : node.getChildren()) {
+ addKeysToRemove(ktn, keys);
+ }
}
public void addNewItem(ISelection selection) {
- // event.feedback = DND.FEEDBACK_INSERT_BEFORE;
- String newKeyPrefix = "";
+ // event.feedback = DND.FEEDBACK_INSERT_BEFORE;
+ String newKeyPrefix = "";
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection) selection)
- .iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof IKeyTreeNode) {
- newKeyPrefix = ((IKeyTreeNode) elem).getMessageKey();
- break;
- }
- }
- }
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection)
+ .iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof IKeyTreeNode) {
+ newKeyPrefix = ((IKeyTreeNode) elem).getMessageKey();
+ break;
+ }
+ }
+ }
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell());
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
- DialogConfiguration config = dialog.new DialogConfiguration();
- config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix
- + "." + "[Platzhalter]"
- : "");
- config.setPreselectedMessage("");
- config.setPreselectedBundle(getResourceBundle());
- config.setPreselectedLocale("");
- config.setProjectName(projectName);
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix
+ + "." + "[Platzhalter]"
+ : "");
+ config.setPreselectedMessage("");
+ config.setPreselectedBundle(getResourceBundle());
+ config.setPreselectedLocale("");
+ config.setProjectName(projectName);
- dialog.setDialogConfiguration(config);
+ dialog.setDialogConfiguration(config);
- if (dialog.open() != InputDialog.OK)
- return;
+ if (dialog.open() != InputDialog.OK)
+ return;
}
public void setMatchingPrecision(float value) {
- matchingPrecision = value;
- if (matcher instanceof FuzzyMatcher) {
- ((FuzzyMatcher) matcher).setMinimumSimilarity(value);
- treeViewer.refresh();
- }
+ matchingPrecision = value;
+ if (matcher instanceof FuzzyMatcher) {
+ ((FuzzyMatcher) matcher).setMinimumSimilarity(value);
+ treeViewer.refresh();
+ }
}
public float getMatchingPrecision() {
- return matchingPrecision;
+ return matchingPrecision;
}
private class MessagesEditorListener implements IMessagesEditorListener {
- @Override
- public void onSave() {
- if (resourceBundle != null) {
- setTreeStructure();
- }
- }
+ @Override
+ public void onSave() {
+ if (resourceBundle != null) {
+ setTreeStructure();
+ }
+ }
- @Override
- public void onModify() {
- if (resourceBundle != null) {
- setTreeStructure();
- }
- }
+ @Override
+ public void onModify() {
+ if (resourceBundle != null) {
+ setTreeStructure();
+ }
+ }
- @Override
- public void onResourceChanged(IMessagesBundle bundle) {
- // TODO Auto-generated method stub
+ @Override
+ public void onResourceChanged(IMessagesBundle bundle) {
+ // TODO Auto-generated method stub
- }
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java
index d14feb6..bd1466e 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java
@@ -61,210 +61,210 @@
private StyledCellLabelProvider labelProvider;
public ResourceSelector(Composite parent, int style) {
- super(parent, style);
+ super(parent, style);
- initLayout(this);
- initViewer(this);
+ initLayout(this);
+ initViewer(this);
}
protected void updateContentProvider(IMessagesBundleGroup group) {
- // define input of treeviewer
- if (!showTree || displayMode == DISPLAY_TEXT) {
- treeType = TreeType.Flat;
- }
+ // define input of treeviewer
+ if (!showTree || displayMode == DISPLAY_TEXT) {
+ treeType = TreeType.Flat;
+ }
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(projectName);
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
- IAbstractKeyTreeModel model = KeyTreeFactory.createModel(manager
- .getResourceBundle(resourceBundle));
- ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider) viewer
- .getContentProvider();
- contentProvider.setProjectName(manager.getProject().getName());
- contentProvider.setBundleId(resourceBundle);
- contentProvider.setTreeType(treeType);
- if (viewer.getInput() == null) {
- viewer.setUseHashlookup(true);
- }
+ IAbstractKeyTreeModel model = KeyTreeFactory.createModel(manager
+ .getResourceBundle(resourceBundle));
+ ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider) viewer
+ .getContentProvider();
+ contentProvider.setProjectName(manager.getProject().getName());
+ contentProvider.setBundleId(resourceBundle);
+ contentProvider.setTreeType(treeType);
+ if (viewer.getInput() == null) {
+ viewer.setUseHashlookup(true);
+ }
- // viewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
- org.eclipse.jface.viewers.TreePath[] expandedTreePaths = viewer
- .getExpandedTreePaths();
- viewer.setInput(model);
- viewer.refresh();
- viewer.setExpandedTreePaths(expandedTreePaths);
+ // viewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
+ org.eclipse.jface.viewers.TreePath[] expandedTreePaths = viewer
+ .getExpandedTreePaths();
+ viewer.setInput(model);
+ viewer.refresh();
+ viewer.setExpandedTreePaths(expandedTreePaths);
}
protected void updateViewer(boolean updateContent) {
- IMessagesBundleGroup group = ResourceBundleManager.getManager(
- projectName).getResourceBundle(resourceBundle);
+ IMessagesBundleGroup group = ResourceBundleManager.getManager(
+ projectName).getResourceBundle(resourceBundle);
- if (group == null)
- return;
+ if (group == null)
+ return;
- if (displayMode == DISPLAY_TEXT) {
- labelProvider = new ValueKeyTreeLabelProvider(
- group.getMessagesBundle(displayLocale));
- treeType = TreeType.Flat;
- ((ResKeyTreeContentProvider) viewer.getContentProvider())
- .setTreeType(treeType);
- } else {
- labelProvider = new ResKeyTreeLabelProvider(null);
- treeType = TreeType.Tree;
- ((ResKeyTreeContentProvider) viewer.getContentProvider())
- .setTreeType(treeType);
- }
+ if (displayMode == DISPLAY_TEXT) {
+ labelProvider = new ValueKeyTreeLabelProvider(
+ group.getMessagesBundle(displayLocale));
+ treeType = TreeType.Flat;
+ ((ResKeyTreeContentProvider) viewer.getContentProvider())
+ .setTreeType(treeType);
+ } else {
+ labelProvider = new ResKeyTreeLabelProvider(null);
+ treeType = TreeType.Tree;
+ ((ResKeyTreeContentProvider) viewer.getContentProvider())
+ .setTreeType(treeType);
+ }
- viewer.setLabelProvider(labelProvider);
- if (updateContent)
- updateContentProvider(group);
+ viewer.setLabelProvider(labelProvider);
+ if (updateContent)
+ updateContentProvider(group);
}
protected void initLayout(Composite parent) {
- basicLayout = new TreeColumnLayout();
- parent.setLayout(basicLayout);
+ basicLayout = new TreeColumnLayout();
+ parent.setLayout(basicLayout);
}
protected void initViewer(Composite parent) {
- viewer = new TreeViewer(parent, SWT.BORDER | SWT.SINGLE
- | SWT.FULL_SELECTION);
- Tree table = viewer.getTree();
+ viewer = new TreeViewer(parent, SWT.BORDER | SWT.SINGLE
+ | SWT.FULL_SELECTION);
+ Tree table = viewer.getTree();
- // Init table-columns
- entries = new TreeColumn(table, SWT.NONE);
- basicLayout.setColumnData(entries, new ColumnWeightData(1));
+ // Init table-columns
+ entries = new TreeColumn(table, SWT.NONE);
+ basicLayout.setColumnData(entries, new ColumnWeightData(1));
- viewer.setContentProvider(new ResKeyTreeContentProvider());
- viewer.addSelectionChangedListener(new ISelectionChangedListener() {
+ viewer.setContentProvider(new ResKeyTreeContentProvider());
+ viewer.addSelectionChangedListener(new ISelectionChangedListener() {
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- ISelection selection = event.getSelection();
- String selectionSummary = "";
- String selectedKey = "";
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(projectName);
+ @Override
+ public void selectionChanged(SelectionChangedEvent event) {
+ ISelection selection = event.getSelection();
+ String selectionSummary = "";
+ String selectedKey = "";
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
- if (selection instanceof IStructuredSelection) {
- Iterator<IKeyTreeNode> itSel = ((IStructuredSelection) selection)
- .iterator();
- if (itSel.hasNext()) {
- IKeyTreeNode selItem = itSel.next();
- IMessagesBundleGroup group = manager
- .getResourceBundle(resourceBundle);
- selectedKey = selItem.getMessageKey();
+ if (selection instanceof IStructuredSelection) {
+ Iterator<IKeyTreeNode> itSel = ((IStructuredSelection) selection)
+ .iterator();
+ if (itSel.hasNext()) {
+ IKeyTreeNode selItem = itSel.next();
+ IMessagesBundleGroup group = manager
+ .getResourceBundle(resourceBundle);
+ selectedKey = selItem.getMessageKey();
- if (group == null)
- return;
- Iterator<Locale> itLocales = manager
- .getProvidedLocales(resourceBundle).iterator();
- while (itLocales.hasNext()) {
- Locale l = itLocales.next();
- try {
- selectionSummary += (l == null ? ResourceBundleManager.defaultLocaleTag
- : l.getDisplayLanguage())
- + ":\n";
- selectionSummary += "\t"
- + group.getMessagesBundle(l)
- .getMessage(
- selItem.getMessageKey())
- .getValue() + "\n";
- } catch (Exception e) {
- }
- }
- }
- }
+ if (group == null)
+ return;
+ Iterator<Locale> itLocales = manager
+ .getProvidedLocales(resourceBundle).iterator();
+ while (itLocales.hasNext()) {
+ Locale l = itLocales.next();
+ try {
+ selectionSummary += (l == null ? ResourceBundleManager.defaultLocaleTag
+ : l.getDisplayLanguage())
+ + ":\n";
+ selectionSummary += "\t"
+ + group.getMessagesBundle(l)
+ .getMessage(
+ selItem.getMessageKey())
+ .getValue() + "\n";
+ } catch (Exception e) {
+ }
+ }
+ }
+ }
- // construct ResourceSelectionEvent
- ResourceSelectionEvent e = new ResourceSelectionEvent(
- selectedKey, selectionSummary);
- fireSelectionChanged(e);
- }
- });
+ // construct ResourceSelectionEvent
+ ResourceSelectionEvent e = new ResourceSelectionEvent(
+ selectedKey, selectionSummary);
+ fireSelectionChanged(e);
+ }
+ });
- // we need this to keep the tree expanded
- viewer.setComparer(new IElementComparer() {
+ // we need this to keep the tree expanded
+ viewer.setComparer(new IElementComparer() {
- @Override
- public int hashCode(Object element) {
- final int prime = 31;
- int result = 1;
- result = prime * result
- + ((toString() == null) ? 0 : toString().hashCode());
- return result;
- }
+ @Override
+ public int hashCode(Object element) {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result
+ + ((toString() == null) ? 0 : toString().hashCode());
+ return result;
+ }
- @Override
- public boolean equals(Object a, Object b) {
- if (a == b) {
- return true;
- }
- if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) {
- IKeyTreeNode nodeA = (IKeyTreeNode) a;
- IKeyTreeNode nodeB = (IKeyTreeNode) b;
- return nodeA.equals(nodeB);
- }
- return false;
- }
- });
+ @Override
+ public boolean equals(Object a, Object b) {
+ if (a == b) {
+ return true;
+ }
+ if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) {
+ IKeyTreeNode nodeA = (IKeyTreeNode) a;
+ IKeyTreeNode nodeB = (IKeyTreeNode) b;
+ return nodeA.equals(nodeB);
+ }
+ return false;
+ }
+ });
}
public Locale getDisplayLocale() {
- return displayLocale;
+ return displayLocale;
}
public void setDisplayLocale(Locale displayLocale) {
- this.displayLocale = displayLocale;
- updateViewer(false);
+ this.displayLocale = displayLocale;
+ updateViewer(false);
}
public int getDisplayMode() {
- return displayMode;
+ return displayMode;
}
public void setDisplayMode(int displayMode) {
- this.displayMode = displayMode;
- updateViewer(true);
+ this.displayMode = displayMode;
+ updateViewer(true);
}
public void setResourceBundle(String resourceBundle) {
- this.resourceBundle = resourceBundle;
- updateViewer(true);
+ this.resourceBundle = resourceBundle;
+ updateViewer(true);
}
public String getResourceBundle() {
- return resourceBundle;
+ return resourceBundle;
}
public void addSelectionChangedListener(IResourceSelectionListener l) {
- listeners.add(l);
+ listeners.add(l);
}
public void removeSelectionChangedListener(IResourceSelectionListener l) {
- listeners.remove(l);
+ listeners.remove(l);
}
private void fireSelectionChanged(ResourceSelectionEvent event) {
- Iterator<IResourceSelectionListener> itResList = listeners.iterator();
- while (itResList.hasNext()) {
- itResList.next().selectionChanged(event);
- }
+ Iterator<IResourceSelectionListener> itResList = listeners.iterator();
+ while (itResList.hasNext()) {
+ itResList.next().selectionChanged(event);
+ }
}
public void setProjectName(String projectName) {
- this.projectName = projectName;
+ this.projectName = projectName;
}
public boolean isShowTree() {
- return showTree;
+ return showTree;
}
public void setShowTree(boolean showTree) {
- if (this.showTree != showTree) {
- this.showTree = showTree;
- this.treeType = showTree ? TreeType.Tree : TreeType.Flat;
- updateViewer(false);
- }
+ if (this.showTree != showTree) {
+ this.showTree = showTree;
+ this.treeType = showTree ? TreeType.Tree : TreeType.Flat;
+ updateViewer(false);
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java
index 586ce13..955b2a0 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java
@@ -16,24 +16,24 @@
private String selectedKey;
public ResourceSelectionEvent(String selectedKey, String selectionSummary) {
- this.setSelectionSummary(selectionSummary);
- this.setSelectedKey(selectedKey);
+ this.setSelectionSummary(selectionSummary);
+ this.setSelectedKey(selectedKey);
}
public void setSelectedKey(String key) {
- selectedKey = key;
+ selectedKey = key;
}
public void setSelectionSummary(String selectionSummary) {
- this.selectionSummary = selectionSummary;
+ this.selectionSummary = selectionSummary;
}
public String getSelectionSummary() {
- return selectionSummary;
+ return selectionSummary;
}
public String getSelectedKey() {
- return selectedKey;
+ return selectedKey;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java
index da60456..c2c7747 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java
@@ -24,66 +24,66 @@
protected StringMatcher matcher;
public ExactMatcher(StructuredViewer viewer) {
- this.viewer = viewer;
+ this.viewer = viewer;
}
public String getPattern() {
- return pattern;
+ return pattern;
}
public void setPattern(String p) {
- boolean filtering = matcher != null;
- if (p != null && p.trim().length() > 0) {
- pattern = p;
- matcher = new StringMatcher("*" + pattern + "*", true, false);
- if (!filtering)
- viewer.addFilter(this);
- else
- viewer.refresh();
- } else {
- pattern = "";
- matcher = null;
- if (filtering) {
- viewer.removeFilter(this);
- }
- }
+ boolean filtering = matcher != null;
+ if (p != null && p.trim().length() > 0) {
+ pattern = p;
+ matcher = new StringMatcher("*" + pattern + "*", true, false);
+ if (!filtering)
+ viewer.addFilter(this);
+ else
+ viewer.refresh();
+ } else {
+ pattern = "";
+ matcher = null;
+ if (filtering) {
+ viewer.removeFilter(this);
+ }
+ }
}
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
- IValuedKeyTreeNode vEle = (IValuedKeyTreeNode) element;
- FilterInfo filterInfo = new FilterInfo();
- boolean selected = matcher.match(vEle.getMessageKey());
+ IValuedKeyTreeNode vEle = (IValuedKeyTreeNode) element;
+ FilterInfo filterInfo = new FilterInfo();
+ boolean selected = matcher.match(vEle.getMessageKey());
- if (selected) {
- int start = -1;
- while ((start = vEle.getMessageKey().toLowerCase()
- .indexOf(pattern.toLowerCase(), start + 1)) >= 0) {
- filterInfo.addKeyOccurrence(start, pattern.length());
- }
- filterInfo.setFoundInKey(selected);
- filterInfo.setFoundInKey(true);
- } else
- filterInfo.setFoundInKey(false);
+ if (selected) {
+ int start = -1;
+ while ((start = vEle.getMessageKey().toLowerCase()
+ .indexOf(pattern.toLowerCase(), start + 1)) >= 0) {
+ filterInfo.addKeyOccurrence(start, pattern.length());
+ }
+ filterInfo.setFoundInKey(selected);
+ filterInfo.setFoundInKey(true);
+ } else
+ filterInfo.setFoundInKey(false);
- // Iterate translations
- for (Locale l : vEle.getLocales()) {
- String value = vEle.getValue(l);
- if (matcher.match(value)) {
- filterInfo.addFoundInLocale(l);
- filterInfo.addSimilarity(l, 1d);
- int start = -1;
- while ((start = value.toLowerCase().indexOf(
- pattern.toLowerCase(), start + 1)) >= 0) {
- filterInfo
- .addFoundInLocaleRange(l, start, pattern.length());
- }
- selected = true;
- }
- }
+ // Iterate translations
+ for (Locale l : vEle.getLocales()) {
+ String value = vEle.getValue(l);
+ if (matcher.match(value)) {
+ filterInfo.addFoundInLocale(l);
+ filterInfo.addSimilarity(l, 1d);
+ int start = -1;
+ while ((start = value.toLowerCase().indexOf(
+ pattern.toLowerCase(), start + 1)) >= 0) {
+ filterInfo
+ .addFoundInLocaleRange(l, start, pattern.length());
+ }
+ selected = true;
+ }
+ }
- vEle.setInfo(filterInfo);
- return selected;
+ vEle.setInfo(filterInfo);
+ return selected;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java
index e53959a..654d4d2 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java
@@ -32,63 +32,63 @@
}
public void setKeySimilarity(Double similarity) {
- keySimilarity = similarity;
+ keySimilarity = similarity;
}
public Double getKeySimilarity() {
- return keySimilarity;
+ return keySimilarity;
}
public void addSimilarity(Locale l, Double similarity) {
- localeSimilarity.put(l, similarity);
+ localeSimilarity.put(l, similarity);
}
public Double getSimilarityLevel(Locale l) {
- return localeSimilarity.get(l);
+ return localeSimilarity.get(l);
}
public void setFoundInKey(boolean foundInKey) {
- this.foundInKey = foundInKey;
+ this.foundInKey = foundInKey;
}
public boolean isFoundInKey() {
- return foundInKey;
+ return foundInKey;
}
public void addFoundInLocale(Locale loc) {
- foundInLocales.add(loc);
+ foundInLocales.add(loc);
}
public void removeFoundInLocale(Locale loc) {
- foundInLocales.remove(loc);
+ foundInLocales.remove(loc);
}
public void clearFoundInLocale() {
- foundInLocales.clear();
+ foundInLocales.clear();
}
public boolean hasFoundInLocale(Locale l) {
- return foundInLocales.contains(l);
+ return foundInLocales.contains(l);
}
public List<Region> getFoundInLocaleRanges(Locale locale) {
- List<Region> reg = occurrences.get(locale);
- return (reg == null ? new ArrayList<Region>() : reg);
+ List<Region> reg = occurrences.get(locale);
+ return (reg == null ? new ArrayList<Region>() : reg);
}
public void addFoundInLocaleRange(Locale locale, int start, int length) {
- List<Region> regions = occurrences.get(locale);
- if (regions == null)
- regions = new ArrayList<Region>();
- regions.add(new Region(start, length));
- occurrences.put(locale, regions);
+ List<Region> regions = occurrences.get(locale);
+ if (regions == null)
+ regions = new ArrayList<Region>();
+ regions.add(new Region(start, length));
+ occurrences.put(locale, regions);
}
public List<Region> getKeyOccurrences() {
- return keyOccurrences;
+ return keyOccurrences;
}
public void addKeyOccurrence(int start, int length) {
- keyOccurrences.add(new Region(start, length));
+ keyOccurrences.add(new Region(start, length));
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java
index aee3c11..e328801 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java
@@ -24,42 +24,42 @@
protected float minimumSimilarity = 0.75f;
public FuzzyMatcher(StructuredViewer viewer) {
- super(viewer);
- lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer();
- ;
+ super(viewer);
+ lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer();
+ ;
}
public double getMinimumSimilarity() {
- return minimumSimilarity;
+ return minimumSimilarity;
}
public void setMinimumSimilarity(float similarity) {
- this.minimumSimilarity = similarity;
+ this.minimumSimilarity = similarity;
}
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
- boolean exactMatch = super.select(viewer, parentElement, element);
- boolean match = exactMatch;
+ boolean exactMatch = super.select(viewer, parentElement, element);
+ boolean match = exactMatch;
- IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
- FilterInfo filterInfo = (FilterInfo) vkti.getInfo();
+ IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
+ FilterInfo filterInfo = (FilterInfo) vkti.getInfo();
- for (Locale l : vkti.getLocales()) {
- String value = vkti.getValue(l);
- if (filterInfo.hasFoundInLocale(l))
- continue;
- double dist = lvda.analyse(value, getPattern());
- if (dist >= minimumSimilarity) {
- filterInfo.addFoundInLocale(l);
- filterInfo.addSimilarity(l, dist);
- match = true;
- filterInfo.addFoundInLocaleRange(l, 0, value.length());
- }
- }
+ for (Locale l : vkti.getLocales()) {
+ String value = vkti.getValue(l);
+ if (filterInfo.hasFoundInLocale(l))
+ continue;
+ double dist = lvda.analyse(value, getPattern());
+ if (dist >= minimumSimilarity) {
+ filterInfo.addFoundInLocale(l);
+ filterInfo.addSimilarity(l, dist);
+ match = true;
+ filterInfo.addFoundInLocaleRange(l, 0, value.length());
+ }
+ }
- vkti.setInfo(filterInfo);
- return match;
+ vkti.setInfo(filterInfo);
+ return match;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/StringMatcher.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/StringMatcher.java
index 841f0d9..8affc33 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/StringMatcher.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/StringMatcher.java
@@ -29,7 +29,7 @@
protected boolean fHasTrailingStar;
protected String fSegments[]; // the given pattern is split into * separated
- // segments
+ // segments
/* boundary value beyond which we don't need to search in the text */
protected int fBound = 0;
@@ -37,22 +37,22 @@
protected static final char fSingleWildCard = '\u0000';
public static class Position {
- int start; // inclusive
+ int start; // inclusive
- int end; // exclusive
+ int end; // exclusive
- public Position(int start, int end) {
- this.start = start;
- this.end = end;
- }
+ public Position(int start, int end) {
+ this.start = start;
+ this.end = end;
+ }
- public int getStart() {
- return start;
- }
+ public int getStart() {
+ return start;
+ }
- public int getEnd() {
- return end;
- }
+ public int getEnd() {
+ return end;
+ }
}
/**
@@ -79,20 +79,20 @@
* (everything is taken literally).
*/
public StringMatcher(String pattern, boolean ignoreCase,
- boolean ignoreWildCards) {
- if (pattern == null) {
- throw new IllegalArgumentException();
- }
- fIgnoreCase = ignoreCase;
- fIgnoreWildCards = ignoreWildCards;
- fPattern = pattern;
- fLength = pattern.length();
+ boolean ignoreWildCards) {
+ if (pattern == null) {
+ throw new IllegalArgumentException();
+ }
+ fIgnoreCase = ignoreCase;
+ fIgnoreWildCards = ignoreWildCards;
+ fPattern = pattern;
+ fLength = pattern.length();
- if (fIgnoreWildCards) {
- parseNoWildCards();
- } else {
- parseWildCards();
- }
+ if (fIgnoreWildCards) {
+ parseNoWildCards();
+ } else {
+ parseWildCards();
+ }
}
/**
@@ -115,54 +115,54 @@
* "abcdf", (1,3) is returned
*/
public StringMatcher.Position find(String text, int start, int end) {
- if (text == null) {
- throw new IllegalArgumentException();
- }
+ if (text == null) {
+ throw new IllegalArgumentException();
+ }
- int tlen = text.length();
- if (start < 0) {
- start = 0;
- }
- if (end > tlen) {
- end = tlen;
- }
- if (end < 0 || start >= end) {
- return null;
- }
- if (fLength == 0) {
- return new Position(start, start);
- }
- if (fIgnoreWildCards) {
- int x = posIn(text, start, end);
- if (x < 0) {
- return null;
- }
- return new Position(x, x + fLength);
- }
+ int tlen = text.length();
+ if (start < 0) {
+ start = 0;
+ }
+ if (end > tlen) {
+ end = tlen;
+ }
+ if (end < 0 || start >= end) {
+ return null;
+ }
+ if (fLength == 0) {
+ return new Position(start, start);
+ }
+ if (fIgnoreWildCards) {
+ int x = posIn(text, start, end);
+ if (x < 0) {
+ return null;
+ }
+ return new Position(x, x + fLength);
+ }
- int segCount = fSegments.length;
- if (segCount == 0) {
- return new Position(start, end);
- }
+ int segCount = fSegments.length;
+ if (segCount == 0) {
+ return new Position(start, end);
+ }
- int curPos = start;
- int matchStart = -1;
- int i;
- for (i = 0; i < segCount && curPos < end; ++i) {
- String current = fSegments[i];
- int nextMatch = regExpPosIn(text, curPos, end, current);
- if (nextMatch < 0) {
- return null;
- }
- if (i == 0) {
- matchStart = nextMatch;
- }
- curPos = nextMatch + current.length();
- }
- if (i < segCount) {
- return null;
- }
- return new Position(matchStart, curPos);
+ int curPos = start;
+ int matchStart = -1;
+ int i;
+ for (i = 0; i < segCount && curPos < end; ++i) {
+ String current = fSegments[i];
+ int nextMatch = regExpPosIn(text, curPos, end, current);
+ if (nextMatch < 0) {
+ return null;
+ }
+ if (i == 0) {
+ matchStart = nextMatch;
+ }
+ curPos = nextMatch + current.length();
+ }
+ if (i < segCount) {
+ return null;
+ }
+ return new Position(matchStart, curPos);
}
/**
@@ -173,10 +173,10 @@
* a String object
*/
public boolean match(String text) {
- if (text == null) {
- return false;
- }
- return match(text, 0, text.length());
+ if (text == null) {
+ return false;
+ }
+ return match(text, 0, text.length());
}
/**
@@ -193,87 +193,87 @@
* marks the ending index (exclusive) of the substring
*/
public boolean match(String text, int start, int end) {
- if (null == text) {
- throw new IllegalArgumentException();
- }
+ if (null == text) {
+ throw new IllegalArgumentException();
+ }
- if (start > end) {
- return false;
- }
+ if (start > end) {
+ return false;
+ }
- if (fIgnoreWildCards) {
- return (end - start == fLength)
- && fPattern.regionMatches(fIgnoreCase, 0, text, start,
- fLength);
- }
- int segCount = fSegments.length;
- if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) {
- return true;
- }
- if (start == end) {
- return fLength == 0;
- }
- if (fLength == 0) {
- return start == end;
- }
+ if (fIgnoreWildCards) {
+ return (end - start == fLength)
+ && fPattern.regionMatches(fIgnoreCase, 0, text, start,
+ fLength);
+ }
+ int segCount = fSegments.length;
+ if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) {
+ return true;
+ }
+ if (start == end) {
+ return fLength == 0;
+ }
+ if (fLength == 0) {
+ return start == end;
+ }
- int tlen = text.length();
- if (start < 0) {
- start = 0;
- }
- if (end > tlen) {
- end = tlen;
- }
+ int tlen = text.length();
+ if (start < 0) {
+ start = 0;
+ }
+ if (end > tlen) {
+ end = tlen;
+ }
- int tCurPos = start;
- int bound = end - fBound;
- if (bound < 0) {
- return false;
- }
- int i = 0;
- String current = fSegments[i];
- int segLength = current.length();
+ int tCurPos = start;
+ int bound = end - fBound;
+ if (bound < 0) {
+ return false;
+ }
+ int i = 0;
+ String current = fSegments[i];
+ int segLength = current.length();
- /* process first segment */
- if (!fHasLeadingStar) {
- if (!regExpRegionMatches(text, start, current, 0, segLength)) {
- return false;
- } else {
- ++i;
- tCurPos = tCurPos + segLength;
- }
- }
- if ((fSegments.length == 1) && (!fHasLeadingStar)
- && (!fHasTrailingStar)) {
- // only one segment to match, no wildcards specified
- return tCurPos == end;
- }
- /* process middle segments */
- while (i < segCount) {
- current = fSegments[i];
- int currentMatch;
- int k = current.indexOf(fSingleWildCard);
- if (k < 0) {
- currentMatch = textPosIn(text, tCurPos, end, current);
- if (currentMatch < 0) {
- return false;
- }
- } else {
- currentMatch = regExpPosIn(text, tCurPos, end, current);
- if (currentMatch < 0) {
- return false;
- }
- }
- tCurPos = currentMatch + current.length();
- i++;
- }
+ /* process first segment */
+ if (!fHasLeadingStar) {
+ if (!regExpRegionMatches(text, start, current, 0, segLength)) {
+ return false;
+ } else {
+ ++i;
+ tCurPos = tCurPos + segLength;
+ }
+ }
+ if ((fSegments.length == 1) && (!fHasLeadingStar)
+ && (!fHasTrailingStar)) {
+ // only one segment to match, no wildcards specified
+ return tCurPos == end;
+ }
+ /* process middle segments */
+ while (i < segCount) {
+ current = fSegments[i];
+ int currentMatch;
+ int k = current.indexOf(fSingleWildCard);
+ if (k < 0) {
+ currentMatch = textPosIn(text, tCurPos, end, current);
+ if (currentMatch < 0) {
+ return false;
+ }
+ } else {
+ currentMatch = regExpPosIn(text, tCurPos, end, current);
+ if (currentMatch < 0) {
+ return false;
+ }
+ }
+ tCurPos = currentMatch + current.length();
+ i++;
+ }
- /* process final segment */
- if (!fHasTrailingStar && tCurPos != end) {
- int clen = current.length();
- return regExpRegionMatches(text, end - clen, current, 0, clen);
- }
- return i == segCount;
+ /* process final segment */
+ if (!fHasTrailingStar && tCurPos != end) {
+ int clen = current.length();
+ return regExpRegionMatches(text, end - clen, current, 0, clen);
+ }
+ return i == segCount;
}
/**
@@ -282,9 +282,9 @@
* pattern consists of a single segment.
*/
private void parseNoWildCards() {
- fSegments = new String[1];
- fSegments[0] = fPattern;
- fBound = fLength;
+ fSegments = new String[1];
+ fSegments[0] = fPattern;
+ fBound = fLength;
}
/**
@@ -296,63 +296,63 @@
* and/or '?'
*/
private void parseWildCards() {
- if (fPattern.startsWith("*")) { //$NON-NLS-1$
- fHasLeadingStar = true;
- }
- if (fPattern.endsWith("*")) {//$NON-NLS-1$
- /* make sure it's not an escaped wildcard */
- if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
- fHasTrailingStar = true;
- }
- }
+ if (fPattern.startsWith("*")) { //$NON-NLS-1$
+ fHasLeadingStar = true;
+ }
+ if (fPattern.endsWith("*")) {//$NON-NLS-1$
+ /* make sure it's not an escaped wildcard */
+ if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
+ fHasTrailingStar = true;
+ }
+ }
- Vector temp = new Vector();
+ Vector temp = new Vector();
- int pos = 0;
- StringBuffer buf = new StringBuffer();
- while (pos < fLength) {
- char c = fPattern.charAt(pos++);
- switch (c) {
- case '\\':
- if (pos >= fLength) {
- buf.append(c);
- } else {
- char next = fPattern.charAt(pos++);
- /* if it's an escape sequence */
- if (next == '*' || next == '?' || next == '\\') {
- buf.append(next);
- } else {
- /* not an escape sequence, just insert literally */
- buf.append(c);
- buf.append(next);
- }
- }
- break;
- case '*':
- if (buf.length() > 0) {
- /* new segment */
- temp.addElement(buf.toString());
- fBound += buf.length();
- buf.setLength(0);
- }
- break;
- case '?':
- /* append special character representing single match wildcard */
- buf.append(fSingleWildCard);
- break;
- default:
- buf.append(c);
- }
- }
+ int pos = 0;
+ StringBuffer buf = new StringBuffer();
+ while (pos < fLength) {
+ char c = fPattern.charAt(pos++);
+ switch (c) {
+ case '\\':
+ if (pos >= fLength) {
+ buf.append(c);
+ } else {
+ char next = fPattern.charAt(pos++);
+ /* if it's an escape sequence */
+ if (next == '*' || next == '?' || next == '\\') {
+ buf.append(next);
+ } else {
+ /* not an escape sequence, just insert literally */
+ buf.append(c);
+ buf.append(next);
+ }
+ }
+ break;
+ case '*':
+ if (buf.length() > 0) {
+ /* new segment */
+ temp.addElement(buf.toString());
+ fBound += buf.length();
+ buf.setLength(0);
+ }
+ break;
+ case '?':
+ /* append special character representing single match wildcard */
+ buf.append(fSingleWildCard);
+ break;
+ default:
+ buf.append(c);
+ }
+ }
- /* add last buffer to segment list */
- if (buf.length() > 0) {
- temp.addElement(buf.toString());
- fBound += buf.length();
- }
+ /* add last buffer to segment list */
+ if (buf.length() > 0) {
+ temp.addElement(buf.toString());
+ fBound += buf.length();
+ }
- fSegments = new String[temp.size()];
- temp.copyInto(fSegments);
+ fSegments = new String[temp.size()];
+ temp.copyInto(fSegments);
}
/**
@@ -366,24 +366,24 @@
* found
*/
protected int posIn(String text, int start, int end) {// no wild card in
- // pattern
- int max = end - fLength;
+ // pattern
+ int max = end - fLength;
- if (!fIgnoreCase) {
- int i = text.indexOf(fPattern, start);
- if (i == -1 || i > max) {
- return -1;
- }
- return i;
- }
+ if (!fIgnoreCase) {
+ int i = text.indexOf(fPattern, start);
+ if (i == -1 || i > max) {
+ return -1;
+ }
+ return i;
+ }
- for (int i = start; i <= max; ++i) {
- if (text.regionMatches(true, i, fPattern, 0, fLength)) {
- return i;
- }
- }
+ for (int i = start; i <= max; ++i) {
+ if (text.regionMatches(true, i, fPattern, 0, fLength)) {
+ return i;
+ }
+ }
- return -1;
+ return -1;
}
/**
@@ -399,15 +399,15 @@
* found
*/
protected int regExpPosIn(String text, int start, int end, String p) {
- int plen = p.length();
+ int plen = p.length();
- int max = end - plen;
- for (int i = start; i <= max; ++i) {
- if (regExpRegionMatches(text, i, p, 0, plen)) {
- return i;
- }
- }
- return -1;
+ int max = end - plen;
+ for (int i = start; i <= max; ++i) {
+ if (regExpRegionMatches(text, i, p, 0, plen)) {
+ return i;
+ }
+ }
+ return -1;
}
/**
@@ -427,37 +427,37 @@
* boolean indicating wether code>p</code> is case sensitive
*/
protected boolean regExpRegionMatches(String text, int tStart, String p,
- int pStart, int plen) {
- while (plen-- > 0) {
- char tchar = text.charAt(tStart++);
- char pchar = p.charAt(pStart++);
+ int pStart, int plen) {
+ while (plen-- > 0) {
+ char tchar = text.charAt(tStart++);
+ char pchar = p.charAt(pStart++);
- /* process wild cards */
- if (!fIgnoreWildCards) {
- /* skip single wild cards */
- if (pchar == fSingleWildCard) {
- continue;
- }
- }
- if (pchar == tchar) {
- continue;
- }
- if (fIgnoreCase) {
- if (Character.toUpperCase(tchar) == Character
- .toUpperCase(pchar)) {
- continue;
- }
- // comparing after converting to upper case doesn't handle all
- // cases;
- // also compare after converting to lower case
- if (Character.toLowerCase(tchar) == Character
- .toLowerCase(pchar)) {
- continue;
- }
- }
- return false;
- }
- return true;
+ /* process wild cards */
+ if (!fIgnoreWildCards) {
+ /* skip single wild cards */
+ if (pchar == fSingleWildCard) {
+ continue;
+ }
+ }
+ if (pchar == tchar) {
+ continue;
+ }
+ if (fIgnoreCase) {
+ if (Character.toUpperCase(tchar) == Character
+ .toUpperCase(pchar)) {
+ continue;
+ }
+ // comparing after converting to upper case doesn't handle all
+ // cases;
+ // also compare after converting to lower case
+ if (Character.toLowerCase(tchar) == Character
+ .toLowerCase(pchar)) {
+ continue;
+ }
+ }
+ return false;
+ }
+ return true;
}
/**
@@ -474,23 +474,23 @@
*/
protected int textPosIn(String text, int start, int end, String p) {
- int plen = p.length();
- int max = end - plen;
+ int plen = p.length();
+ int max = end - plen;
- if (!fIgnoreCase) {
- int i = text.indexOf(p, start);
- if (i == -1 || i > max) {
- return -1;
- }
- return i;
- }
+ if (!fIgnoreCase) {
+ int i = text.indexOf(p, start);
+ if (i == -1 || i > max) {
+ return -1;
+ }
+ return i;
+ }
- for (int i = start; i <= max; ++i) {
- if (text.regionMatches(true, i, p, 0, plen)) {
- return i;
- }
- }
+ for (int i = start; i <= max; ++i) {
+ if (text.regionMatches(true, i, p, 0, plen)) {
+ return i;
+ }
+ }
- return -1;
+ return -1;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java
index 876dc35..cbc3eae 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java
@@ -23,46 +23,46 @@
*
* @author Alexej Strelzow
*/
-public abstract class KeyTreeLabelProvider extends StyledCellLabelProvider implements
- IFontProvider, IColorProvider {
+public abstract class KeyTreeLabelProvider extends StyledCellLabelProvider
+ implements IFontProvider, IColorProvider {
- public KeyTreeLabelProvider() {
- setOwnerDrawEnabled(true);
- }
-
- /**
- * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object)
- */
- public Font getFont(Object element) {
- return null;
- }
+ public KeyTreeLabelProvider() {
+ setOwnerDrawEnabled(true);
+ }
- /**
- * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
- */
- public Color getForeground(Object element) {
- return null;
- }
+ /**
+ * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object)
+ */
+ public Font getFont(Object element) {
+ return null;
+ }
- /**
- * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object)
- */
- public Color getBackground(Object element) {
- return null;
- }
-
- public abstract String getColumnText(Object element, int columnIndex);
-
- public abstract Image getColumnImage(Object element, int columnIndex);
+ /**
+ * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
+ */
+ public Color getForeground(Object element) {
+ return null;
+ }
- /**
- * {@inheritDoc}
- */
- @Override
- public void update(ViewerCell cell) {
- cell.setText(getColumnText(cell.getElement(), cell.getColumnIndex()));
- cell.setImage(getColumnImage(cell.getElement(), cell.getColumnIndex()));
- super.update(cell);
- }
-
+ /**
+ * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object)
+ */
+ public Color getBackground(Object element) {
+ return null;
+ }
+
+ public abstract String getColumnText(Object element, int columnIndex);
+
+ public abstract Image getColumnImage(Object element, int columnIndex);
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void update(ViewerCell cell) {
+ cell.setText(getColumnText(cell.getElement(), cell.getColumnIndex()));
+ cell.setImage(getColumnImage(cell.getElement(), cell.getColumnIndex()));
+ super.update(cell);
+ }
+
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java
index a2dc85a..ab0e33c 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java
@@ -45,142 +45,142 @@
private String projectName;
public ResKeyTreeContentProvider(List<Locale> locales, String projectName,
- String bundleId, TreeType treeType) {
- this.locales = locales;
- this.projectName = projectName;
- this.bundleId = bundleId;
- this.treeType = treeType;
+ String bundleId, TreeType treeType) {
+ this.locales = locales;
+ this.projectName = projectName;
+ this.bundleId = bundleId;
+ this.treeType = treeType;
}
public void setBundleId(String bundleId) {
- this.bundleId = bundleId;
+ this.bundleId = bundleId;
}
public void setProjectName(String projectName) {
- this.projectName = projectName;
+ this.projectName = projectName;
}
public ResKeyTreeContentProvider() {
- locales = new ArrayList<Locale>();
+ locales = new ArrayList<Locale>();
}
public void setLocales(List<Locale> locales) {
- this.locales = locales;
+ this.locales = locales;
}
@Override
public Object[] getChildren(Object parentElement) {
- IKeyTreeNode parentNode = (IKeyTreeNode) parentElement;
- switch (treeType) {
- case Tree:
- return convertKTItoVKTI(keyTreeModel.getChildren(parentNode));
- case Flat:
- return new IKeyTreeNode[0];
- default:
- // Should not happen
- return new IKeyTreeNode[0];
- }
+ IKeyTreeNode parentNode = (IKeyTreeNode) parentElement;
+ switch (treeType) {
+ case Tree:
+ return convertKTItoVKTI(keyTreeModel.getChildren(parentNode));
+ case Flat:
+ return new IKeyTreeNode[0];
+ default:
+ // Should not happen
+ return new IKeyTreeNode[0];
+ }
}
protected Object[] convertKTItoVKTI(Object[] children) {
- Collection<IValuedKeyTreeNode> items = new ArrayList<IValuedKeyTreeNode>();
- IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(
- this.projectName).getMessagesBundleGroup(this.bundleId);
+ Collection<IValuedKeyTreeNode> items = new ArrayList<IValuedKeyTreeNode>();
+ IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(
+ this.projectName).getMessagesBundleGroup(this.bundleId);
- for (Object o : children) {
- if (o instanceof IValuedKeyTreeNode)
- items.add((IValuedKeyTreeNode) o);
- else {
- IKeyTreeNode kti = (IKeyTreeNode) o;
- IValuedKeyTreeNode vkti = KeyTreeFactory.createKeyTree(
- kti.getParent(), kti.getName(), kti.getMessageKey(),
- messagesBundleGroup);
+ for (Object o : children) {
+ if (o instanceof IValuedKeyTreeNode)
+ items.add((IValuedKeyTreeNode) o);
+ else {
+ IKeyTreeNode kti = (IKeyTreeNode) o;
+ IValuedKeyTreeNode vkti = KeyTreeFactory.createKeyTree(
+ kti.getParent(), kti.getName(), kti.getMessageKey(),
+ messagesBundleGroup);
- for (IKeyTreeNode k : kti.getChildren()) {
- vkti.addChild(k);
- }
+ for (IKeyTreeNode k : kti.getChildren()) {
+ vkti.addChild(k);
+ }
- // init translations
- for (Locale l : locales) {
- try {
- IMessage message = messagesBundleGroup
- .getMessagesBundle(l).getMessage(
- kti.getMessageKey());
- if (message != null) {
- vkti.addValue(l, message.getValue());
- }
- } catch (Exception e) {
- }
- }
- items.add(vkti);
- }
- }
+ // init translations
+ for (Locale l : locales) {
+ try {
+ IMessage message = messagesBundleGroup
+ .getMessagesBundle(l).getMessage(
+ kti.getMessageKey());
+ if (message != null) {
+ vkti.addValue(l, message.getValue());
+ }
+ } catch (Exception e) {
+ }
+ }
+ items.add(vkti);
+ }
+ }
- return items.toArray();
+ return items.toArray();
}
@Override
public Object[] getElements(Object inputElement) {
- switch (treeType) {
- case Tree:
- return convertKTItoVKTI(keyTreeModel.getRootNodes());
- case Flat:
- final Collection<IKeyTreeNode> actualKeys = new ArrayList<IKeyTreeNode>();
- IKeyTreeVisitor visitor = new IKeyTreeVisitor() {
- public void visitKeyTreeNode(IKeyTreeNode node) {
- if (node.isUsedAsKey()) {
- actualKeys.add(node);
- }
- }
- };
- keyTreeModel.accept(visitor, keyTreeModel.getRootNode());
+ switch (treeType) {
+ case Tree:
+ return convertKTItoVKTI(keyTreeModel.getRootNodes());
+ case Flat:
+ final Collection<IKeyTreeNode> actualKeys = new ArrayList<IKeyTreeNode>();
+ IKeyTreeVisitor visitor = new IKeyTreeVisitor() {
+ public void visitKeyTreeNode(IKeyTreeNode node) {
+ if (node.isUsedAsKey()) {
+ actualKeys.add(node);
+ }
+ }
+ };
+ keyTreeModel.accept(visitor, keyTreeModel.getRootNode());
- return actualKeys.toArray();
- default:
- // Should not happen
- return new IKeyTreeNode[0];
- }
+ return actualKeys.toArray();
+ default:
+ // Should not happen
+ return new IKeyTreeNode[0];
+ }
}
@Override
public Object getParent(Object element) {
- IKeyTreeNode node = (IKeyTreeNode) element;
- switch (treeType) {
- case Tree:
- return keyTreeModel.getParent(node);
- case Flat:
- return keyTreeModel;
- default:
- // Should not happen
- return null;
- }
+ IKeyTreeNode node = (IKeyTreeNode) element;
+ switch (treeType) {
+ case Tree:
+ return keyTreeModel.getParent(node);
+ case Flat:
+ return keyTreeModel;
+ default:
+ // Should not happen
+ return null;
+ }
}
/**
* @see ITreeContentProvider#hasChildren(Object)
*/
public boolean hasChildren(Object element) {
- switch (treeType) {
- case Tree:
- return keyTreeModel.getChildren((IKeyTreeNode) element).length > 0;
- case Flat:
- return false;
- default:
- // Should not happen
- return false;
- }
+ switch (treeType) {
+ case Tree:
+ return keyTreeModel.getChildren((IKeyTreeNode) element).length > 0;
+ case Flat:
+ return false;
+ default:
+ // Should not happen
+ return false;
+ }
}
public int countChildren(Object element) {
- if (element instanceof IKeyTreeNode) {
- return ((IKeyTreeNode) element).getChildren().length;
- } else if (element instanceof IValuedKeyTreeNode) {
- return ((IValuedKeyTreeNode) element).getChildren().length;
- } else {
- System.out.println("wait a minute");
- return 1;
- }
+ if (element instanceof IKeyTreeNode) {
+ return ((IKeyTreeNode) element).getChildren().length;
+ } else if (element instanceof IValuedKeyTreeNode) {
+ return ((IValuedKeyTreeNode) element).getChildren().length;
+ } else {
+ System.out.println("wait a minute");
+ return 1;
+ }
}
/**
@@ -189,42 +189,42 @@
* @return key tree item
*/
private IKeyTreeNode getTreeSelection() {
- IStructuredSelection selection = (IStructuredSelection) treeViewer
- .getSelection();
- return ((IKeyTreeNode) selection.getFirstElement());
+ IStructuredSelection selection = (IStructuredSelection) treeViewer
+ .getSelection();
+ return ((IKeyTreeNode) selection.getFirstElement());
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- this.viewer = (TreeViewer) viewer;
- this.keyTreeModel = (IAbstractKeyTreeModel) newInput;
+ this.viewer = (TreeViewer) viewer;
+ this.keyTreeModel = (IAbstractKeyTreeModel) newInput;
}
public IMessagesBundleGroup getBundle() {
- return RBManager.getInstance(projectName).getMessagesBundleGroup(
- this.bundleId);
+ return RBManager.getInstance(projectName).getMessagesBundleGroup(
+ this.bundleId);
}
public String getBundleId() {
- return bundleId;
+ return bundleId;
}
@Override
public void dispose() {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
}
public TreeType getTreeType() {
- return treeType;
+ return treeType;
}
public void setTreeType(TreeType treeType) {
- if (this.treeType != treeType) {
- this.treeType = treeType;
- if (viewer != null) {
- viewer.refresh();
- }
- }
+ if (this.treeType != treeType) {
+ this.treeType = treeType;
+ if (viewer != null) {
+ viewer.refresh();
+ }
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java
index 9b74191..54a8dac 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java
@@ -44,7 +44,7 @@
private Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW);
public ResKeyTreeLabelProvider(List<Locale> locales) {
- this.locales = locales;
+ this.locales = locales;
}
/**
@@ -52,32 +52,32 @@
*/
@Override
public Image getColumnImage(Object element, int columnIndex) {
- if (columnIndex == 0) {
- IKeyTreeNode kti = (IKeyTreeNode) element;
- IMessage[] be = kti.getMessagesBundleGroup().getMessages(
- kti.getMessageKey());
- boolean incomplete = false;
+ if (columnIndex == 0) {
+ IKeyTreeNode kti = (IKeyTreeNode) element;
+ IMessage[] be = kti.getMessagesBundleGroup().getMessages(
+ kti.getMessageKey());
+ boolean incomplete = false;
- if (be.length != kti.getMessagesBundleGroup()
- .getMessagesBundleCount())
- incomplete = true;
- else {
- for (IMessage b : be) {
- if (b.getValue() == null
- || b.getValue().trim().length() == 0) {
- incomplete = true;
- break;
- }
- }
- }
+ if (be.length != kti.getMessagesBundleGroup()
+ .getMessagesBundleCount())
+ incomplete = true;
+ else {
+ for (IMessage b : be) {
+ if (b.getValue() == null
+ || b.getValue().trim().length() == 0) {
+ incomplete = true;
+ break;
+ }
+ }
+ }
- if (incomplete) {
- return ImageUtils.getImage(ImageUtils.ICON_RESOURCE_INCOMPLETE);
- } else {
- return ImageUtils.getImage(ImageUtils.ICON_RESOURCE);
- }
- }
- return null;
+ if (incomplete) {
+ return ImageUtils.getImage(ImageUtils.ICON_RESOURCE_INCOMPLETE);
+ } else {
+ return ImageUtils.getImage(ImageUtils.ICON_RESOURCE);
+ }
+ }
+ return null;
}
/**
@@ -85,107 +85,107 @@
*/
@Override
public String getColumnText(Object element, int columnIndex) {
- if (columnIndex == 0) {
- return ((IKeyTreeNode) element).getName();
- }
+ if (columnIndex == 0) {
+ return ((IKeyTreeNode) element).getName();
+ }
- if (columnIndex <= locales.size()) {
- IValuedKeyTreeNode item = (IValuedKeyTreeNode) element;
- String entry = item.getValue(locales.get(columnIndex - 1));
- if (entry != null) {
- return entry;
- }
- }
- return "";
+ if (columnIndex <= locales.size()) {
+ IValuedKeyTreeNode item = (IValuedKeyTreeNode) element;
+ String entry = item.getValue(locales.get(columnIndex - 1));
+ if (entry != null) {
+ return entry;
+ }
+ }
+ return "";
}
public void setSearchEnabled(boolean enabled) {
- this.searchEnabled = enabled;
+ this.searchEnabled = enabled;
}
public boolean isSearchEnabled() {
- return this.searchEnabled;
+ return this.searchEnabled;
}
public void setLocales(List<Locale> visibleLocales) {
- locales = visibleLocales;
+ locales = visibleLocales;
}
protected boolean isMatchingToPattern(Object element, int columnIndex) {
- boolean matching = false;
+ boolean matching = false;
- if (element instanceof IValuedKeyTreeNode) {
- IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
+ if (element instanceof IValuedKeyTreeNode) {
+ IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
- if (vkti.getInfo() == null)
- return false;
+ if (vkti.getInfo() == null)
+ return false;
- FilterInfo filterInfo = (FilterInfo) vkti.getInfo();
+ FilterInfo filterInfo = (FilterInfo) vkti.getInfo();
- if (columnIndex == 0) {
- matching = filterInfo.isFoundInKey();
- } else {
- matching = filterInfo.hasFoundInLocale(locales
- .get(columnIndex - 1));
- }
- }
+ if (columnIndex == 0) {
+ matching = filterInfo.isFoundInKey();
+ } else {
+ matching = filterInfo.hasFoundInLocale(locales
+ .get(columnIndex - 1));
+ }
+ }
- return matching;
+ return matching;
}
protected boolean isSearchEnabled(Object element) {
- return (element instanceof IValuedKeyTreeNode && searchEnabled);
+ return (element instanceof IValuedKeyTreeNode && searchEnabled);
}
public void updateTreeViewer(TreeViewer treeViewer) {
- for (TreeItem item : treeViewer.getTree().getItems()) {
- Rectangle bounds = item.getBounds();
- ViewerCell cell = treeViewer.getCell(new Point(bounds.x, bounds.y));
- ViewerRow viewerRow = cell.getViewerRow();
+ for (TreeItem item : treeViewer.getTree().getItems()) {
+ Rectangle bounds = item.getBounds();
+ ViewerCell cell = treeViewer.getCell(new Point(bounds.x, bounds.y));
+ ViewerRow viewerRow = cell.getViewerRow();
- for (int i = 0; i < viewerRow.getColumnCount(); i++) {
- updateCell(viewerRow.getCell(i));
- }
- }
+ for (int i = 0; i < viewerRow.getColumnCount(); i++) {
+ updateCell(viewerRow.getCell(i));
+ }
+ }
}
private void updateCell(ViewerCell cell) {
- Object element = cell.getElement();
- int columnIndex = cell.getColumnIndex();
+ Object element = cell.getElement();
+ int columnIndex = cell.getColumnIndex();
- if (isSearchEnabled(element)) {
- if (isMatchingToPattern(element, columnIndex)) {
- List<StyleRange> styleRanges = new ArrayList<StyleRange>();
- FilterInfo filterInfo = (FilterInfo) ((IValuedKeyTreeNode) element)
- .getInfo();
+ if (isSearchEnabled(element)) {
+ if (isMatchingToPattern(element, columnIndex)) {
+ List<StyleRange> styleRanges = new ArrayList<StyleRange>();
+ FilterInfo filterInfo = (FilterInfo) ((IValuedKeyTreeNode) element)
+ .getInfo();
- if (columnIndex > 0) {
- for (Region reg : filterInfo.getFoundInLocaleRanges(locales
- .get(columnIndex - 1))) {
- styleRanges.add(new StyleRange(reg.getOffset(), reg
- .getLength(), black, info_color, SWT.BOLD));
- }
- } else {
- // check if the pattern has been found within the key
- // section
- if (filterInfo.isFoundInKey()) {
- for (Region reg : filterInfo.getKeyOccurrences()) {
- StyleRange sr = new StyleRange(reg.getOffset(),
- reg.getLength(), black, info_color,
- SWT.BOLD);
- styleRanges.add(sr);
- }
- }
- }
- cell.setStyleRanges(styleRanges
- .toArray(new StyleRange[styleRanges.size()]));
- } else {
- cell.setForeground(gray);
- }
- } else if (columnIndex == 0) {
- super.update(cell);
- }
+ if (columnIndex > 0) {
+ for (Region reg : filterInfo.getFoundInLocaleRanges(locales
+ .get(columnIndex - 1))) {
+ styleRanges.add(new StyleRange(reg.getOffset(), reg
+ .getLength(), black, info_color, SWT.BOLD));
+ }
+ } else {
+ // check if the pattern has been found within the key
+ // section
+ if (filterInfo.isFoundInKey()) {
+ for (Region reg : filterInfo.getKeyOccurrences()) {
+ StyleRange sr = new StyleRange(reg.getOffset(),
+ reg.getLength(), black, info_color,
+ SWT.BOLD);
+ styleRanges.add(sr);
+ }
+ }
+ }
+ cell.setStyleRanges(styleRanges
+ .toArray(new StyleRange[styleRanges.size()]));
+ } else {
+ cell.setForeground(gray);
+ }
+ } else if (columnIndex == 0) {
+ super.update(cell);
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java
index 4efa9f2..5593898 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java
@@ -20,12 +20,12 @@
import org.eclipse.swt.graphics.Image;
public class ValueKeyTreeLabelProvider extends KeyTreeLabelProvider implements
- ITableColorProvider, ITableFontProvider {
+ ITableColorProvider, ITableFontProvider {
private IMessagesBundle locale;
public ValueKeyTreeLabelProvider(IMessagesBundle iBundle) {
- this.locale = iBundle;
+ this.locale = iBundle;
}
/**
@@ -33,7 +33,7 @@
*/
@Override
public Image getColumnImage(Object element, int columnIndex) {
- return null;
+ return null;
}
/**
@@ -41,17 +41,17 @@
*/
@Override
public String getColumnText(Object element, int columnIndex) {
- try {
- IKeyTreeNode item = (IKeyTreeNode) element;
- IMessage entry = locale.getMessage(item.getMessageKey());
- if (entry != null) {
- String value = entry.getValue();
- if (value.length() > 40)
- value = value.substring(0, 39) + "...";
- }
- } catch (Exception e) {
- }
- return "";
+ try {
+ IKeyTreeNode item = (IKeyTreeNode) element;
+ IMessage entry = locale.getMessage(item.getMessageKey());
+ if (entry != null) {
+ String value = entry.getValue();
+ if (value.length() > 40)
+ value = value.substring(0, 39) + "...";
+ }
+ } catch (Exception e) {
+ }
+ return "";
}
/**
@@ -59,7 +59,7 @@
*/
@Override
public Color getBackground(Object element, int columnIndex) {
- return null;// return new Color(Display.getDefault(), 255, 0, 0);
+ return null;// return new Color(Display.getDefault(), 255, 0, 0);
}
/**
@@ -67,7 +67,7 @@
*/
@Override
public Color getForeground(Object element, int columnIndex) {
- return null;
+ return null;
}
/**
@@ -75,7 +75,7 @@
*/
@Override
public Font getFont(Object element, int columnIndex) {
- return null; // UIUtils.createFont(SWT.BOLD);
+ return null; // UIUtils.createFont(SWT.BOLD);
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java
index 824f7b4..e7d1c19 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java
@@ -24,54 +24,54 @@
private SortInfo sortInfo;
public ValuedKeyTreeItemSorter(StructuredViewer viewer, SortInfo sortInfo) {
- this.viewer = viewer;
- this.sortInfo = sortInfo;
+ this.viewer = viewer;
+ this.sortInfo = sortInfo;
}
public StructuredViewer getViewer() {
- return viewer;
+ return viewer;
}
public void setViewer(StructuredViewer viewer) {
- this.viewer = viewer;
+ this.viewer = viewer;
}
public SortInfo getSortInfo() {
- return sortInfo;
+ return sortInfo;
}
public void setSortInfo(SortInfo sortInfo) {
- this.sortInfo = sortInfo;
+ this.sortInfo = sortInfo;
}
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
- try {
- if (!(e1 instanceof IValuedKeyTreeNode && e2 instanceof IValuedKeyTreeNode))
- return super.compare(viewer, e1, e2);
- IValuedKeyTreeNode comp1 = (IValuedKeyTreeNode) e1;
- IValuedKeyTreeNode comp2 = (IValuedKeyTreeNode) e2;
+ try {
+ if (!(e1 instanceof IValuedKeyTreeNode && e2 instanceof IValuedKeyTreeNode))
+ return super.compare(viewer, e1, e2);
+ IValuedKeyTreeNode comp1 = (IValuedKeyTreeNode) e1;
+ IValuedKeyTreeNode comp2 = (IValuedKeyTreeNode) e2;
- int result = 0;
+ int result = 0;
- if (sortInfo == null)
- return 0;
+ if (sortInfo == null)
+ return 0;
- if (sortInfo.getColIdx() == 0)
- result = comp1.getMessageKey().compareTo(comp2.getMessageKey());
- else {
- Locale loc = sortInfo.getVisibleLocales().get(
- sortInfo.getColIdx() - 1);
- result = (comp1.getValue(loc) == null ? "" : comp1
- .getValue(loc))
- .compareTo((comp2.getValue(loc) == null ? "" : comp2
- .getValue(loc)));
- }
+ if (sortInfo.getColIdx() == 0)
+ result = comp1.getMessageKey().compareTo(comp2.getMessageKey());
+ else {
+ Locale loc = sortInfo.getVisibleLocales().get(
+ sortInfo.getColIdx() - 1);
+ result = (comp1.getValue(loc) == null ? "" : comp1
+ .getValue(loc))
+ .compareTo((comp2.getValue(loc) == null ? "" : comp2
+ .getValue(loc)));
+ }
- return result * (sortInfo.isDESC() ? -1 : 1);
- } catch (Exception e) {
- return 0;
- }
+ return result * (sortInfo.isDESC() ? -1 : 1);
+ } catch (Exception e) {
+ return 0;
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java
index 84c0844..8d7bdf9 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java
@@ -50,11 +50,11 @@
*/
@Override
public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
-
- // detect resource bundles
- RBManager.getAllMessagesBundleGroupNames();
+ super.start(context);
+ plugin = this;
+
+ // detect resource bundles
+ RBManager.getAllMessagesBundleGroupNames();
}
/*
@@ -66,8 +66,8 @@
*/
@Override
public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
+ plugin = null;
+ super.stop(context);
}
/**
@@ -76,7 +76,7 @@
* @return the shared instance
*/
public static Activator getDefault() {
- return plugin;
+ return plugin;
}
/**
@@ -88,12 +88,12 @@
* @return localized string corresponding to key
*/
public static String getString(String key) {
- ResourceBundle bundle = Activator.getDefault().getResourceBundle();
- try {
- return (bundle != null) ? bundle.getString(key) : key;
- } catch (MissingResourceException e) {
- return key;
- }
+ ResourceBundle bundle = Activator.getDefault().getResourceBundle();
+ try {
+ return (bundle != null) ? bundle.getString(key) : key;
+ } catch (MissingResourceException e) {
+ return key;
+ }
}
/**
@@ -107,7 +107,7 @@
* @return localized string corresponding to key
*/
public static String getString(String key, String arg1) {
- return MessageFormat.format(getString(key), new String[] { arg1 });
+ return MessageFormat.format(getString(key), new String[] { arg1 });
}
/**
@@ -123,8 +123,8 @@
* @return localized string corresponding to key
*/
public static String getString(String key, String arg1, String arg2) {
- return MessageFormat
- .format(getString(key), new String[] { arg1, arg2 });
+ return MessageFormat
+ .format(getString(key), new String[] { arg1, arg2 });
}
/**
@@ -142,9 +142,9 @@
* @return localized string corresponding to key
*/
public static String getString(String key, String arg1, String arg2,
- String arg3) {
- return MessageFormat.format(getString(key), new String[] { arg1, arg2,
- arg3 });
+ String arg3) {
+ return MessageFormat.format(getString(key), new String[] { arg1, arg2,
+ arg3 });
}
/**
@@ -153,7 +153,7 @@
* @return resource bundle
*/
protected ResourceBundle getResourceBundle() {
- return resourceBundle;
+ return resourceBundle;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
index 8bfd10a..7f21d7b 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
@@ -15,30 +15,30 @@
public class Logger {
- public static void logInfo(String message) {
- log(IStatus.INFO, IStatus.OK, message, null);
- }
+ public static void logInfo(String message) {
+ log(IStatus.INFO, IStatus.OK, message, null);
+ }
- public static void logError(Throwable exception) {
- logError("Unexpected Exception", exception);
- }
+ public static void logError(Throwable exception) {
+ logError("Unexpected Exception", exception);
+ }
- public static void logError(String message, Throwable exception) {
- log(IStatus.ERROR, IStatus.OK, message, exception);
- }
+ public static void logError(String message, Throwable exception) {
+ log(IStatus.ERROR, IStatus.OK, message, exception);
+ }
- public static void log(int severity, int code, String message,
- Throwable exception) {
- log(createStatus(severity, code, message, exception));
- }
+ public static void log(int severity, int code, String message,
+ Throwable exception) {
+ log(createStatus(severity, code, message, exception));
+ }
- public static IStatus createStatus(int severity, int code, String message,
- Throwable exception) {
- return new Status(severity, Activator.PLUGIN_ID, code, message,
- exception);
- }
+ public static IStatus createStatus(int severity, int code, String message,
+ Throwable exception) {
+ return new Status(severity, Activator.PLUGIN_ID, code, message,
+ exception);
+ }
- public static void log(IStatus status) {
- Activator.getDefault().getLog().log(status);
- }
+ public static void log(IStatus status) {
+ Activator.getDefault().getLog().log(status);
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/ILocation.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/ILocation.java
index e53d2b9..1faa7c3 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/ILocation.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/ILocation.java
@@ -21,40 +21,40 @@
*/
public interface ILocation {
- /**
- * Returns the source resource's physical location.
- *
- * @return The file within the text fragment is located
- */
- public IFile getFile();
+ /**
+ * Returns the source resource's physical location.
+ *
+ * @return The file within the text fragment is located
+ */
+ public IFile getFile();
- /**
- * Returns the position of the text fragments starting character.
- *
- * @return The position of the first character
- */
- public int getStartPos();
+ /**
+ * Returns the position of the text fragments starting character.
+ *
+ * @return The position of the first character
+ */
+ public int getStartPos();
- /**
- * Returns the position of the text fragments last character.
- *
- * @return The position of the last character
- */
- public int getEndPos();
+ /**
+ * Returns the position of the text fragments last character.
+ *
+ * @return The position of the last character
+ */
+ public int getEndPos();
- /**
- * Returns the text fragment.
- *
- * @return The text fragment
- */
- public String getLiteral();
+ /**
+ * Returns the text fragment.
+ *
+ * @return The text fragment
+ */
+ public String getLiteral();
- /**
- * Returns additional metadata. The type and content of this property is not
- * specified and can be used to marshal additional data for the computation
- * of resolution proposals.
- *
- * @return The metadata associated with the text fragment
- */
- public Serializable getData();
+ /**
+ * Returns additional metadata. The type and content of this property is not
+ * specified and can be used to marshal additional data for the computation
+ * of resolution proposals.
+ *
+ * @return The metadata associated with the text fragment
+ */
+ public Serializable getData();
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java
index 916f6ec..36e21bf 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java
@@ -11,11 +11,11 @@
package org.eclipse.babel.tapiji.tools.core.extensions;
public interface IMarkerConstants {
- public static final int CAUSE_BROKEN_REFERENCE = 0;
- public static final int CAUSE_CONSTANT_LITERAL = 1;
- public static final int CAUSE_BROKEN_RB_REFERENCE = 2;
+ public static final int CAUSE_BROKEN_REFERENCE = 0;
+ public static final int CAUSE_CONSTANT_LITERAL = 1;
+ public static final int CAUSE_BROKEN_RB_REFERENCE = 2;
- public static final int CAUSE_UNSPEZIFIED_KEY = 3;
- public static final int CAUSE_SAME_VALUE = 4;
- public static final int CAUSE_MISSING_LANGUAGE = 5;
+ public static final int CAUSE_UNSPEZIFIED_KEY = 3;
+ public static final int CAUSE_SAME_VALUE = 4;
+ public static final int CAUSE_MISSING_LANGUAGE = 5;
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java
index f51fbca..26727ee 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java
@@ -14,6 +14,6 @@
public interface IResourceBundleChangedListener {
- public void resourceBundleChanged(ResourceBundleChangedEvent event);
+ public void resourceBundleChanged(ResourceBundleChangedEvent event);
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java
index 83f073b..cb80a2f 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java
@@ -12,20 +12,20 @@
public interface IResourceDescriptor {
- public void setProjectName(String projName);
+ public void setProjectName(String projName);
- public void setRelativePath(String relPath);
+ public void setRelativePath(String relPath);
- public void setAbsolutePath(String absPath);
+ public void setAbsolutePath(String absPath);
- public void setBundleId(String bundleId);
+ public void setBundleId(String bundleId);
- public String getProjectName();
+ public String getProjectName();
- public String getRelativePath();
+ public String getRelativePath();
- public String getAbsolutePath();
+ public String getAbsolutePath();
- public String getBundleId();
+ public String getBundleId();
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java
index 4a85add..31f913b 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java
@@ -14,6 +14,6 @@
public interface IResourceExclusionListener {
- public void exclusionChanged(ResourceExclusionEvent event);
+ public void exclusionChanged(ResourceExclusionEvent event);
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java
index dfd91df..fc556c3 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java
@@ -14,71 +14,71 @@
public class ResourceDescriptor implements IResourceDescriptor {
- private String projectName;
- private String relativePath;
- private String absolutePath;
- private String bundleId;
+ private String projectName;
+ private String relativePath;
+ private String absolutePath;
+ private String bundleId;
- public ResourceDescriptor(IResource resource) {
- projectName = resource.getProject().getName();
- relativePath = resource.getProjectRelativePath().toString();
- absolutePath = resource.getRawLocation().toString();
- }
+ public ResourceDescriptor(IResource resource) {
+ projectName = resource.getProject().getName();
+ relativePath = resource.getProjectRelativePath().toString();
+ absolutePath = resource.getRawLocation().toString();
+ }
- public ResourceDescriptor() {
- }
+ public ResourceDescriptor() {
+ }
- @Override
- public String getAbsolutePath() {
- return absolutePath;
- }
+ @Override
+ public String getAbsolutePath() {
+ return absolutePath;
+ }
- @Override
- public String getProjectName() {
- return projectName;
- }
+ @Override
+ public String getProjectName() {
+ return projectName;
+ }
- @Override
- public String getRelativePath() {
- return relativePath;
- }
+ @Override
+ public String getRelativePath() {
+ return relativePath;
+ }
- @Override
- public int hashCode() {
- return projectName.hashCode() + relativePath.hashCode();
- }
+ @Override
+ public int hashCode() {
+ return projectName.hashCode() + relativePath.hashCode();
+ }
- @Override
- public boolean equals(Object other) {
- if (!(other instanceof ResourceDescriptor))
- return false;
+ @Override
+ public boolean equals(Object other) {
+ if (!(other instanceof ResourceDescriptor))
+ return false;
- return absolutePath.equals(absolutePath);
- }
+ return absolutePath.equals(absolutePath);
+ }
- @Override
- public void setAbsolutePath(String absPath) {
- this.absolutePath = absPath;
- }
+ @Override
+ public void setAbsolutePath(String absPath) {
+ this.absolutePath = absPath;
+ }
- @Override
- public void setProjectName(String projName) {
- this.projectName = projName;
- }
+ @Override
+ public void setProjectName(String projName) {
+ this.projectName = projName;
+ }
- @Override
- public void setRelativePath(String relPath) {
- this.relativePath = relPath;
- }
+ @Override
+ public void setRelativePath(String relPath) {
+ this.relativePath = relPath;
+ }
- @Override
- public String getBundleId() {
- return this.bundleId;
- }
+ @Override
+ public String getBundleId() {
+ return this.bundleId;
+ }
- @Override
- public void setBundleId(String bundleId) {
- this.bundleId = bundleId;
- }
+ @Override
+ public void setBundleId(String bundleId) {
+ this.bundleId = bundleId;
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java
index 036af55..5ac24c8 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java
@@ -17,55 +17,55 @@
public class SLLocation implements Serializable, ILocation {
- private static final long serialVersionUID = 1L;
- private IFile file = null;
- private int startPos = -1;
- private int endPos = -1;
- private String literal;
- private Serializable data;
+ private static final long serialVersionUID = 1L;
+ private IFile file = null;
+ private int startPos = -1;
+ private int endPos = -1;
+ private String literal;
+ private Serializable data;
- public SLLocation(IFile file, int startPos, int endPos, String literal) {
- super();
- this.file = file;
- this.startPos = startPos;
- this.endPos = endPos;
- this.literal = literal;
- }
+ public SLLocation(IFile file, int startPos, int endPos, String literal) {
+ super();
+ this.file = file;
+ this.startPos = startPos;
+ this.endPos = endPos;
+ this.literal = literal;
+ }
- public IFile getFile() {
- return file;
- }
+ public IFile getFile() {
+ return file;
+ }
- public void setFile(IFile file) {
- this.file = file;
- }
+ public void setFile(IFile file) {
+ this.file = file;
+ }
- public int getStartPos() {
- return startPos;
- }
+ public int getStartPos() {
+ return startPos;
+ }
- public void setStartPos(int startPos) {
- this.startPos = startPos;
- }
+ public void setStartPos(int startPos) {
+ this.startPos = startPos;
+ }
- public int getEndPos() {
- return endPos;
- }
+ public int getEndPos() {
+ return endPos;
+ }
- public void setEndPos(int endPos) {
- this.endPos = endPos;
- }
+ public void setEndPos(int endPos) {
+ this.endPos = endPos;
+ }
- public String getLiteral() {
- return literal;
- }
+ public String getLiteral() {
+ return literal;
+ }
- public Serializable getData() {
- return data;
- }
+ public Serializable getData() {
+ return data;
+ }
- public void setData(Serializable data) {
- this.data = data;
- }
+ public void setData(Serializable data) {
+ this.data = data;
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java
index 408fd50..767a761 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java
@@ -12,14 +12,14 @@
public class ResourceBundleException extends Exception {
- private static final long serialVersionUID = -2039182473628481126L;
+ private static final long serialVersionUID = -2039182473628481126L;
- public ResourceBundleException(String msg) {
- super(msg);
- }
+ public ResourceBundleException(String msg) {
+ super(msg);
+ }
- public ResourceBundleException() {
- super();
- }
+ public ResourceBundleException() {
+ super();
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/IStateLoader.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/IStateLoader.java
index 762687f..73166a2 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/IStateLoader.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/IStateLoader.java
@@ -21,18 +21,18 @@
*/
public interface IStateLoader {
- /**
- * Loads the state from a xml-file
- */
- void loadState();
+ /**
+ * Loads the state from a xml-file
+ */
+ void loadState();
- /**
- * Stores the state into a xml-file
- */
- void saveState();
+ /**
+ * Stores the state into a xml-file
+ */
+ void saveState();
- /**
- * @return The excluded resources
- */
- Set<IResourceDescriptor> getExcludedResources();
+ /**
+ * @return The excluded resources
+ */
+ Set<IResourceDescriptor> getExcludedResources();
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java
index 17f6286..1196f11 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java
@@ -14,43 +14,43 @@
public class ResourceBundleChangedEvent {
- public final static int ADDED = 0;
- public final static int DELETED = 1;
- public final static int MODIFIED = 2;
- public final static int EXCLUDED = 3;
- public final static int INCLUDED = 4;
+ public final static int ADDED = 0;
+ public final static int DELETED = 1;
+ public final static int MODIFIED = 2;
+ public final static int EXCLUDED = 3;
+ public final static int INCLUDED = 4;
- private IProject project;
- private String bundle = "";
- private int type = -1;
+ private IProject project;
+ private String bundle = "";
+ private int type = -1;
- public ResourceBundleChangedEvent(int type, String bundle, IProject project) {
- this.type = type;
- this.bundle = bundle;
- this.project = project;
- }
+ public ResourceBundleChangedEvent(int type, String bundle, IProject project) {
+ this.type = type;
+ this.bundle = bundle;
+ this.project = project;
+ }
- public IProject getProject() {
- return project;
- }
+ public IProject getProject() {
+ return project;
+ }
- public void setProject(IProject project) {
- this.project = project;
- }
+ public void setProject(IProject project) {
+ this.project = project;
+ }
- public String getBundle() {
- return bundle;
- }
+ public String getBundle() {
+ return bundle;
+ }
- public void setBundle(String bundle) {
- this.bundle = bundle;
- }
+ public void setBundle(String bundle) {
+ this.bundle = bundle;
+ }
- public int getType() {
- return type;
- }
+ public int getType() {
+ return type;
+ }
- public void setType(int type) {
- this.type = type;
- }
+ public void setType(int type) {
+ this.type = type;
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceExclusionEvent.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceExclusionEvent.java
index 769d49a..1230be2 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceExclusionEvent.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceExclusionEvent.java
@@ -14,19 +14,19 @@
public class ResourceExclusionEvent {
- private Collection<Object> changedResources;
+ private Collection<Object> changedResources;
- public ResourceExclusionEvent(Collection<Object> changedResources) {
- super();
- this.changedResources = changedResources;
- }
+ public ResourceExclusionEvent(Collection<Object> changedResources) {
+ super();
+ this.changedResources = changedResources;
+ }
- public void setChangedResources(Collection<Object> changedResources) {
- this.changedResources = changedResources;
- }
+ public void setChangedResources(Collection<Object> changedResources) {
+ this.changedResources = changedResources;
+ }
- public Collection<Object> getChangedResources() {
- return changedResources;
- }
+ public Collection<Object> getChangedResources() {
+ return changedResources;
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/EditorUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/EditorUtils.java
index 94c1a7a..3c7b920 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/EditorUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/EditorUtils.java
@@ -18,36 +18,36 @@
public class EditorUtils {
- /** Marker constants **/
- public static final String MARKER_ID = "org.eclipse.babel.tapiji.tools.core.ui.StringLiteralAuditMarker";
- public static final String RB_MARKER_ID = "org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleAuditMarker";
+ /** Marker constants **/
+ public static final String MARKER_ID = "org.eclipse.babel.tapiji.tools.core.ui.StringLiteralAuditMarker";
+ public static final String RB_MARKER_ID = "org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleAuditMarker";
- /** Error messages **/
- public static final String MESSAGE_NON_LOCALIZED_LITERAL = "Non-localized string literal ''{0}'' has been found";
- public static final String MESSAGE_BROKEN_RESOURCE_REFERENCE = "Cannot find the key ''{0}'' within the resource-bundle ''{1}''";
- public static final String MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE = "The resource bundle with id ''{0}'' cannot be found";
+ /** Error messages **/
+ public static final String MESSAGE_NON_LOCALIZED_LITERAL = "Non-localized string literal ''{0}'' has been found";
+ public static final String MESSAGE_BROKEN_RESOURCE_REFERENCE = "Cannot find the key ''{0}'' within the resource-bundle ''{1}''";
+ public static final String MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE = "The resource bundle with id ''{0}'' cannot be found";
- public static final String MESSAGE_UNSPECIFIED_KEYS = "Missing or unspecified key ''{0}'' has been found in ''{1}''";
- public static final String MESSAGE_SAME_VALUE = "''{0}'' and ''{1}'' have the same translation for the key ''{2}''";
- public static final String MESSAGE_MISSING_LANGUAGE = "ResourceBundle ''{0}'' lacks a translation for ''{1}''";
+ public static final String MESSAGE_UNSPECIFIED_KEYS = "Missing or unspecified key ''{0}'' has been found in ''{1}''";
+ public static final String MESSAGE_SAME_VALUE = "''{0}'' and ''{1}'' have the same translation for the key ''{2}''";
+ public static final String MESSAGE_MISSING_LANGUAGE = "ResourceBundle ''{0}'' lacks a translation for ''{1}''";
- public static String getFormattedMessage(String pattern, Object[] arguments) {
- String formattedMessage = "";
+ public static String getFormattedMessage(String pattern, Object[] arguments) {
+ String formattedMessage = "";
- MessageFormat formatter = new MessageFormat(pattern);
- formattedMessage = formatter.format(arguments);
+ MessageFormat formatter = new MessageFormat(pattern);
+ formattedMessage = formatter.format(arguments);
- return formattedMessage;
- }
+ return formattedMessage;
+ }
- public static IMarker[] concatMarkerArray(IMarker[] ms, IMarker[] ms_to_add) {
- IMarker[] old_ms = ms;
- ms = new IMarker[old_ms.length + ms_to_add.length];
+ public static IMarker[] concatMarkerArray(IMarker[] ms, IMarker[] ms_to_add) {
+ IMarker[] old_ms = ms;
+ ms = new IMarker[old_ms.length + ms_to_add.length];
- System.arraycopy(old_ms, 0, ms, 0, old_ms.length);
- System.arraycopy(ms_to_add, 0, ms, old_ms.length, ms_to_add.length);
+ System.arraycopy(old_ms, 0, ms, 0, old_ms.length);
+ System.arraycopy(ms_to_add, 0, ms, old_ms.length, ms_to_add.length);
- return ms;
- }
+ return ms;
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java
index 491d087..986bded 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java
@@ -26,36 +26,36 @@
public class FileUtils {
public static String readFile(IResource resource) {
- return readFileAsString(resource.getRawLocation().toFile());
+ return readFileAsString(resource.getRawLocation().toFile());
}
protected static String readFileAsString(File filePath) {
- String content = "";
+ String content = "";
- if (!filePath.exists())
- return content;
- try {
- BufferedReader fileReader = new BufferedReader(new FileReader(
- filePath));
- String line = "";
+ if (!filePath.exists())
+ return content;
+ try {
+ BufferedReader fileReader = new BufferedReader(new FileReader(
+ filePath));
+ String line = "";
- while ((line = fileReader.readLine()) != null) {
- content += line + "\n";
- }
+ while ((line = fileReader.readLine()) != null) {
+ content += line + "\n";
+ }
- // close filereader
- fileReader.close();
- } catch (Exception e) {
- // TODO log error output
- Logger.logError(e);
- }
+ // close filereader
+ fileReader.close();
+ } catch (Exception e) {
+ // TODO log error output
+ Logger.logError(e);
+ }
- return content;
+ return content;
}
public static File getRBManagerStateFile() {
- return Activator.getDefault().getStateLocation()
- .append("internationalization.xml").toFile();
+ return Activator.getDefault().getStateLocation()
+ .append("internationalization.xml").toFile();
}
/**
@@ -68,14 +68,14 @@
* @throws OperationCanceledException
*/
public synchronized void saveTextFile(IFile file, String editorContent)
- throws CoreException, OperationCanceledException {
- try {
- file.setContents(
- new ByteArrayInputStream(editorContent.getBytes()), false,
- true, null);
- } catch (Exception e) {
- e.printStackTrace();
- }
+ throws CoreException, OperationCanceledException {
+ try {
+ file.setContents(
+ new ByteArrayInputStream(editorContent.getBytes()), false,
+ true, null);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java
index 8ffcf52..99c4924 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java
@@ -17,28 +17,28 @@
public class FragmentProjectUtils {
- public static String getPluginId(IProject project) {
- return PDEUtils.getPluginId(project);
- }
+ public static String getPluginId(IProject project) {
+ return PDEUtils.getPluginId(project);
+ }
- public static IProject[] lookupFragment(IProject pluginProject) {
- return PDEUtils.lookupFragment(pluginProject);
- }
+ public static IProject[] lookupFragment(IProject pluginProject) {
+ return PDEUtils.lookupFragment(pluginProject);
+ }
- public static boolean isFragment(IProject pluginProject) {
- return PDEUtils.isFragment(pluginProject);
- }
+ public static boolean isFragment(IProject pluginProject) {
+ return PDEUtils.isFragment(pluginProject);
+ }
- public static List<IProject> getFragments(IProject hostProject) {
- return PDEUtils.getFragments(hostProject);
- }
+ public static List<IProject> getFragments(IProject hostProject) {
+ return PDEUtils.getFragments(hostProject);
+ }
- public static String getFragmentId(IProject project, String hostPluginId) {
- return PDEUtils.getFragmentId(project, hostPluginId);
- }
+ public static String getFragmentId(IProject project, String hostPluginId) {
+ return PDEUtils.getFragmentId(project, hostPluginId);
+ }
- public static IProject getFragmentHost(IProject fragment) {
- return PDEUtils.getFragmentHost(fragment);
- }
+ public static IProject getFragmentHost(IProject fragment) {
+ return PDEUtils.getFragmentHost(fragment);
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java
index e23e07d..56465ce 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java
@@ -17,50 +17,50 @@
public class OverlayIcon extends CompositeImageDescriptor {
- public static final int TOP_LEFT = 0;
- public static final int TOP_RIGHT = 1;
- public static final int BOTTOM_LEFT = 2;
- public static final int BOTTOM_RIGHT = 3;
+ public static final int TOP_LEFT = 0;
+ public static final int TOP_RIGHT = 1;
+ public static final int BOTTOM_LEFT = 2;
+ public static final int BOTTOM_RIGHT = 3;
- private Image img;
- private Image overlay;
- private int location;
- private Point imgSize;
+ private Image img;
+ private Image overlay;
+ private int location;
+ private Point imgSize;
- public OverlayIcon(Image baseImage, Image overlayImage, int location) {
- super();
- this.img = baseImage;
- this.overlay = overlayImage;
- this.location = location;
- this.imgSize = new Point(baseImage.getImageData().width,
- baseImage.getImageData().height);
- }
+ public OverlayIcon(Image baseImage, Image overlayImage, int location) {
+ super();
+ this.img = baseImage;
+ this.overlay = overlayImage;
+ this.location = location;
+ this.imgSize = new Point(baseImage.getImageData().width,
+ baseImage.getImageData().height);
+ }
- @Override
- protected void drawCompositeImage(int width, int height) {
- drawImage(img.getImageData(), 0, 0);
- ImageData imageData = overlay.getImageData();
+ @Override
+ protected void drawCompositeImage(int width, int height) {
+ drawImage(img.getImageData(), 0, 0);
+ ImageData imageData = overlay.getImageData();
- switch (location) {
- case TOP_LEFT:
- drawImage(imageData, 0, 0);
- break;
- case TOP_RIGHT:
- drawImage(imageData, imgSize.x - imageData.width, 0);
- break;
- case BOTTOM_LEFT:
- drawImage(imageData, 0, imgSize.y - imageData.height);
- break;
- case BOTTOM_RIGHT:
- drawImage(imageData, imgSize.x - imageData.width, imgSize.y
- - imageData.height);
- break;
- }
- }
+ switch (location) {
+ case TOP_LEFT:
+ drawImage(imageData, 0, 0);
+ break;
+ case TOP_RIGHT:
+ drawImage(imageData, imgSize.x - imageData.width, 0);
+ break;
+ case BOTTOM_LEFT:
+ drawImage(imageData, 0, imgSize.y - imageData.height);
+ break;
+ case BOTTOM_RIGHT:
+ drawImage(imageData, imgSize.x - imageData.width, imgSize.y
+ - imageData.height);
+ break;
+ }
+ }
- @Override
- protected Point getSize() {
- return new Point(img.getImageData().width, img.getImageData().height);
- }
+ @Override
+ protected Point getSize() {
+ return new Point(img.getImageData().width, img.getImageData().height);
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/RBFileUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/RBFileUtils.java
index f5cfe74..915f70a 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/RBFileUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/RBFileUtils.java
@@ -21,16 +21,16 @@
* Checks whether a RB-file has a problem-marker
*/
public static boolean hasResourceBundleMarker(IResource r) {
- try {
- if (r.findMarkers(EditorUtils.RB_MARKER_ID, true,
- IResource.DEPTH_INFINITE).length > 0) {
- return true;
- } else {
- return false;
- }
- } catch (CoreException e) {
- return false;
- }
+ try {
+ if (r.findMarkers(EditorUtils.RB_MARKER_ID, true,
+ IResource.DEPTH_INFINITE).length > 0) {
+ return true;
+ } else {
+ return false;
+ }
+ } catch (CoreException e) {
+ return false;
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java
index a564ecf..93d8463 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java
@@ -29,69 +29,69 @@
@Override
public void setEditor(IEditorPart editor) {
- this.editor = editor;
- initConstantStringAuditor();
+ this.editor = editor;
+ initConstantStringAuditor();
}
protected void initConstantStringAuditor() {
- // parse editor content and extract resource-bundle access strings
+ // parse editor content and extract resource-bundle access strings
- // get the type of the currently loaded resource
- ITypeRoot typeRoot = JavaUI.getEditorInputTypeRoot(editor
- .getEditorInput());
+ // get the type of the currently loaded resource
+ ITypeRoot typeRoot = JavaUI.getEditorInputTypeRoot(editor
+ .getEditorInput());
- if (typeRoot == null) {
- return;
- }
+ if (typeRoot == null) {
+ return;
+ }
- CompilationUnit cu = ASTutilsUI.getCompilationUnit(typeRoot);
+ CompilationUnit cu = ASTutilsUI.getCompilationUnit(typeRoot);
- if (cu == null) {
- return;
- }
+ if (cu == null) {
+ return;
+ }
- manager = ResourceBundleManager.getManager(cu.getJavaElement()
- .getResource().getProject());
+ manager = ResourceBundleManager.getManager(cu.getJavaElement()
+ .getResource().getProject());
- // determine the element at the position of the cursur
- csf = new ResourceAuditVisitor(null, manager.getProject().getName());
- cu.accept(csf);
+ // determine the element at the position of the cursur
+ csf = new ResourceAuditVisitor(null, manager.getProject().getName());
+ cu.accept(csf);
}
@Override
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
- initConstantStringAuditor();
- if (hoverRegion == null) {
- return null;
- }
+ initConstantStringAuditor();
+ if (hoverRegion == null) {
+ return null;
+ }
- // get region for string literals
- hoverRegion = getHoverRegion(textViewer, hoverRegion.getOffset());
+ // get region for string literals
+ hoverRegion = getHoverRegion(textViewer, hoverRegion.getOffset());
- if (hoverRegion == null) {
- return null;
- }
+ if (hoverRegion == null) {
+ return null;
+ }
- String bundleName = csf.getBundleReference(hoverRegion);
- String key = csf.getKeyAt(hoverRegion);
+ String bundleName = csf.getBundleReference(hoverRegion);
+ String key = csf.getKeyAt(hoverRegion);
- String hoverText = manager.getKeyHoverString(bundleName, key);
- if (hoverText == null || hoverText.equals("")) {
- return null;
- } else {
- return hoverText;
- }
+ String hoverText = manager.getKeyHoverString(bundleName, key);
+ if (hoverText == null || hoverText.equals("")) {
+ return null;
+ } else {
+ return hoverText;
+ }
}
@Override
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
- if (editor == null) {
- return null;
- }
+ if (editor == null) {
+ return null;
+ }
- // Retrieve the property key at this position. Otherwise, null is
- // returned.
- return csf.getKeyAt(Long.valueOf(offset));
+ // Retrieve the property key at this position. Otherwise, null is
+ // returned.
+ return csf.getKeyAt(Long.valueOf(offset));
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java
index ac69712..f201c42 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java
@@ -43,123 +43,123 @@
@Override
public String[] getFileEndings() {
- return new String[] { "java" };
+ return new String[] { "java" };
}
@Override
public void audit(IResource resource) {
- ResourceAuditVisitor csav = new ResourceAuditVisitor(resource
- .getProject().getFile(resource.getProjectRelativePath()),
- resource.getProject().getName());
+ ResourceAuditVisitor csav = new ResourceAuditVisitor(resource
+ .getProject().getFile(resource.getProjectRelativePath()),
+ resource.getProject().getName());
- // get a reference to the shared AST of the loaded CompilationUnit
- CompilationUnit cu = ASTutilsUI.getCompilationUnit(resource);
- if (cu == null) {
- System.out.println("Cannot audit resource: "
- + resource.getFullPath());
- return;
- }
- cu.accept(csav);
+ // get a reference to the shared AST of the loaded CompilationUnit
+ CompilationUnit cu = ASTutilsUI.getCompilationUnit(resource);
+ if (cu == null) {
+ System.out.println("Cannot audit resource: "
+ + resource.getFullPath());
+ return;
+ }
+ cu.accept(csav);
- // Report all constant string literals
- constantLiterals = csav.getConstantStringLiterals();
+ // Report all constant string literals
+ constantLiterals = csav.getConstantStringLiterals();
- // Report all broken Resource-Bundle references
- brokenResourceReferences = csav.getBrokenResourceReferences();
+ // Report all broken Resource-Bundle references
+ brokenResourceReferences = csav.getBrokenResourceReferences();
- // Report all broken definitions to Resource-Bundle references
- brokenBundleReferences = csav.getBrokenRBReferences();
+ // Report all broken definitions to Resource-Bundle references
+ brokenBundleReferences = csav.getBrokenRBReferences();
}
@Override
public List<ILocation> getConstantStringLiterals() {
- return new ArrayList<ILocation>(constantLiterals);
+ return new ArrayList<ILocation>(constantLiterals);
}
@Override
public List<ILocation> getBrokenResourceReferences() {
- return new ArrayList<ILocation>(brokenResourceReferences);
+ return new ArrayList<ILocation>(brokenResourceReferences);
}
@Override
public List<ILocation> getBrokenBundleReferences() {
- return new ArrayList<ILocation>(brokenBundleReferences);
+ return new ArrayList<ILocation>(brokenBundleReferences);
}
@Override
public String getContextId() {
- return "java";
+ return "java";
}
@Override
public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
- List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
+ List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
- switch (marker.getAttribute("cause", -1)) {
- case IMarkerConstants.CAUSE_CONSTANT_LITERAL:
- resolutions.add(new IgnoreStringFromInternationalization());
- resolutions.add(new ExcludeResourceFromInternationalization());
- resolutions.add(new ExportToResourceBundleResolution());
- break;
- case IMarkerConstants.CAUSE_BROKEN_REFERENCE:
- String dataName = marker.getAttribute("bundleName", "");
- int dataStart = marker.getAttribute("bundleStart", 0);
- int dataEnd = marker.getAttribute("bundleEnd", 0);
+ switch (marker.getAttribute("cause", -1)) {
+ case IMarkerConstants.CAUSE_CONSTANT_LITERAL:
+ resolutions.add(new IgnoreStringFromInternationalization());
+ resolutions.add(new ExcludeResourceFromInternationalization());
+ resolutions.add(new ExportToResourceBundleResolution());
+ break;
+ case IMarkerConstants.CAUSE_BROKEN_REFERENCE:
+ String dataName = marker.getAttribute("bundleName", "");
+ int dataStart = marker.getAttribute("bundleStart", 0);
+ int dataEnd = marker.getAttribute("bundleEnd", 0);
- IProject project = marker.getResource().getProject();
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(project);
+ IProject project = marker.getResource().getProject();
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(project);
- if (manager.getResourceBundle(dataName) != null) {
- String key = marker.getAttribute("key", "");
+ if (manager.getResourceBundle(dataName) != null) {
+ String key = marker.getAttribute("key", "");
- resolutions.add(new CreateResourceBundleEntry(key, dataName));
- resolutions.add(new ReplaceResourceBundleReference(key,
- dataName));
- resolutions.add(new ReplaceResourceBundleDefReference(dataName,
- dataStart, dataEnd));
- } else {
- String bname = dataName;
+ resolutions.add(new CreateResourceBundleEntry(key, dataName));
+ resolutions.add(new ReplaceResourceBundleReference(key,
+ dataName));
+ resolutions.add(new ReplaceResourceBundleDefReference(dataName,
+ dataStart, dataEnd));
+ } else {
+ String bname = dataName;
- Set<IResource> bundleResources = ResourceBundleManager
- .getManager(marker.getResource().getProject())
- .getAllResourceBundleResources(bname);
+ Set<IResource> bundleResources = ResourceBundleManager
+ .getManager(marker.getResource().getProject())
+ .getAllResourceBundleResources(bname);
- if (bundleResources != null && bundleResources.size() > 0) {
- resolutions
- .add(new IncludeResource(bname, bundleResources));
- } else {
- resolutions.add(new CreateResourceBundle(bname, marker
- .getResource(), dataStart, dataEnd));
- }
- resolutions.add(new ReplaceResourceBundleDefReference(bname,
- dataStart, dataEnd));
- }
+ if (bundleResources != null && bundleResources.size() > 0) {
+ resolutions
+ .add(new IncludeResource(bname, bundleResources));
+ } else {
+ resolutions.add(new CreateResourceBundle(bname, marker
+ .getResource(), dataStart, dataEnd));
+ }
+ resolutions.add(new ReplaceResourceBundleDefReference(bname,
+ dataStart, dataEnd));
+ }
- break;
- case IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE:
- String bname = marker.getAttribute("key", "");
+ break;
+ case IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE:
+ String bname = marker.getAttribute("key", "");
- Set<IResource> bundleResources = ResourceBundleManager.getManager(
- marker.getResource().getProject())
- .getAllResourceBundleResources(bname);
+ Set<IResource> bundleResources = ResourceBundleManager.getManager(
+ marker.getResource().getProject())
+ .getAllResourceBundleResources(bname);
- if (bundleResources != null && bundleResources.size() > 0) {
- resolutions.add(new IncludeResource(bname, bundleResources));
- } else {
- resolutions.add(new CreateResourceBundle(marker.getAttribute(
- "key", ""), marker.getResource(), marker.getAttribute(
- IMarker.CHAR_START, 0), marker.getAttribute(
- IMarker.CHAR_END, 0)));
- }
- resolutions.add(new ReplaceResourceBundleDefReference(marker
- .getAttribute("key", ""), marker.getAttribute(
- IMarker.CHAR_START, 0), marker.getAttribute(
- IMarker.CHAR_END, 0)));
- }
+ if (bundleResources != null && bundleResources.size() > 0) {
+ resolutions.add(new IncludeResource(bname, bundleResources));
+ } else {
+ resolutions.add(new CreateResourceBundle(marker.getAttribute(
+ "key", ""), marker.getResource(), marker.getAttribute(
+ IMarker.CHAR_START, 0), marker.getAttribute(
+ IMarker.CHAR_END, 0)));
+ }
+ resolutions.add(new ReplaceResourceBundleDefReference(marker
+ .getAttribute("key", ""), marker.getAttribute(
+ IMarker.CHAR_START, 0), marker.getAttribute(
+ IMarker.CHAR_END, 0)));
+ }
- return resolutions;
+ return resolutions;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java
index efe9c95..29894c5 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java
@@ -39,7 +39,7 @@
import org.eclipse.jface.text.contentassist.IContextInformation;
public class MessageCompletionProposalComputer implements
- IJavaCompletionProposalComputer {
+ IJavaCompletionProposalComputer {
private ResourceAuditVisitor csav;
private IResource resource;
@@ -52,206 +52,206 @@
@Override
public List<ICompletionProposal> computeCompletionProposals(
- ContentAssistInvocationContext context, IProgressMonitor monitor) {
+ ContentAssistInvocationContext context, IProgressMonitor monitor) {
- List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
+ List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
- if (!InternationalizationNature
- .hasNature(((JavaContentAssistInvocationContext) context)
- .getCompilationUnit().getResource().getProject())) {
- return completions;
- }
+ if (!InternationalizationNature
+ .hasNature(((JavaContentAssistInvocationContext) context)
+ .getCompilationUnit().getResource().getProject())) {
+ return completions;
+ }
- try {
- JavaContentAssistInvocationContext javaContext = ((JavaContentAssistInvocationContext) context);
- CompletionContext coreContext = javaContext.getCoreContext();
+ try {
+ JavaContentAssistInvocationContext javaContext = ((JavaContentAssistInvocationContext) context);
+ CompletionContext coreContext = javaContext.getCoreContext();
- int tokenStart = coreContext.getTokenStart();
- int tokenEnd = coreContext.getTokenEnd();
- int tokenOffset = coreContext.getOffset();
- boolean isStringLiteral = coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_STRING_LITERAL;
+ int tokenStart = coreContext.getTokenStart();
+ int tokenEnd = coreContext.getTokenEnd();
+ int tokenOffset = coreContext.getOffset();
+ boolean isStringLiteral = coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_STRING_LITERAL;
- if (coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_NAME
- && (tokenEnd + 1) - tokenStart > 0) {
- return completions;
- }
+ if (coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_NAME
+ && (tokenEnd + 1) - tokenStart > 0) {
+ return completions;
+ }
- if (cu == null) {
- manager = ResourceBundleManager.getManager(javaContext
- .getCompilationUnit().getResource().getProject());
+ if (cu == null) {
+ manager = ResourceBundleManager.getManager(javaContext
+ .getCompilationUnit().getResource().getProject());
- resource = javaContext.getCompilationUnit().getResource();
+ resource = javaContext.getCompilationUnit().getResource();
- csav = new ResourceAuditVisitor(null, manager.getProject()
- .getName());
+ csav = new ResourceAuditVisitor(null, manager.getProject()
+ .getName());
- cu = ASTutilsUI.getCompilationUnit(resource);
+ cu = ASTutilsUI.getCompilationUnit(resource);
- cu.accept(csav);
- }
+ cu.accept(csav);
+ }
- if (tokenStart < 0) {
- // is string literal in front of cursor?
- StringLiteral strLit = ASTutils.getStringLiteralAtPos(cu,
- tokenOffset - 1);
- if (strLit != null) {
- tokenStart = strLit.getStartPosition();
- tokenEnd = tokenStart + strLit.getLength() - 1;
- tokenOffset = tokenOffset - 1;
- isStringLiteral = true;
- } else {
- tokenStart = tokenOffset;
- tokenEnd = tokenOffset;
- }
- }
+ if (tokenStart < 0) {
+ // is string literal in front of cursor?
+ StringLiteral strLit = ASTutils.getStringLiteralAtPos(cu,
+ tokenOffset - 1);
+ if (strLit != null) {
+ tokenStart = strLit.getStartPosition();
+ tokenEnd = tokenStart + strLit.getLength() - 1;
+ tokenOffset = tokenOffset - 1;
+ isStringLiteral = true;
+ } else {
+ tokenStart = tokenOffset;
+ tokenEnd = tokenOffset;
+ }
+ }
- if (isStringLiteral) {
- tokenStart++;
- }
+ if (isStringLiteral) {
+ tokenStart++;
+ }
- tokenEnd = Math.max(tokenEnd, tokenStart);
+ tokenEnd = Math.max(tokenEnd, tokenStart);
- String fullToken = "";
+ String fullToken = "";
- if (tokenStart < tokenEnd) {
- fullToken = context.getDocument().get(tokenStart,
- tokenEnd - tokenStart);
- }
+ if (tokenStart < tokenEnd) {
+ fullToken = context.getDocument().get(tokenStart,
+ tokenEnd - tokenStart);
+ }
- // Check if the string literal is up to be written within the
- // context of a resource-bundle accessor method
- if (csav.getKeyAt(new Long(tokenOffset)) != null && isStringLiteral) {
- completions.addAll(getResourceBundleCompletionProposals(
- tokenStart, tokenEnd, tokenOffset, isStringLiteral,
- fullToken, manager, csav, resource));
- } else if (csav.getRBReferenceAt(new Long(tokenOffset)) != null
- && isStringLiteral) {
- completions.addAll(getRBReferenceCompletionProposals(
- tokenStart, tokenEnd, fullToken, isStringLiteral,
- manager, resource));
- } else {
- completions.addAll(getBasicJavaCompletionProposals(tokenStart,
- tokenEnd, tokenOffset, fullToken, isStringLiteral,
- manager, csav, resource));
- }
- if (completions.size() == 1) {
- completions.add(new NoActionProposal());
- }
+ // Check if the string literal is up to be written within the
+ // context of a resource-bundle accessor method
+ if (csav.getKeyAt(new Long(tokenOffset)) != null && isStringLiteral) {
+ completions.addAll(getResourceBundleCompletionProposals(
+ tokenStart, tokenEnd, tokenOffset, isStringLiteral,
+ fullToken, manager, csav, resource));
+ } else if (csav.getRBReferenceAt(new Long(tokenOffset)) != null
+ && isStringLiteral) {
+ completions.addAll(getRBReferenceCompletionProposals(
+ tokenStart, tokenEnd, fullToken, isStringLiteral,
+ manager, resource));
+ } else {
+ completions.addAll(getBasicJavaCompletionProposals(tokenStart,
+ tokenEnd, tokenOffset, fullToken, isStringLiteral,
+ manager, csav, resource));
+ }
+ if (completions.size() == 1) {
+ completions.add(new NoActionProposal());
+ }
- } catch (Exception e) {
- Logger.logError(e);
- }
- return completions;
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+ return completions;
}
private Collection<ICompletionProposal> getRBReferenceCompletionProposals(
- int tokenStart, int tokenEnd, String fullToken,
- boolean isStringLiteral, ResourceBundleManager manager,
- IResource resource) {
- List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
- boolean hit = false;
+ int tokenStart, int tokenEnd, String fullToken,
+ boolean isStringLiteral, ResourceBundleManager manager,
+ IResource resource) {
+ List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
+ boolean hit = false;
- // Show a list of available resource bundles
- List<String> resourceBundles = manager.getResourceBundleIdentifiers();
- for (String rbName : resourceBundles) {
- if (rbName.startsWith(fullToken)) {
- if (rbName.equals(fullToken)) {
- hit = true;
- } else {
- completions.add(new MessageCompletionProposal(tokenStart,
- tokenEnd - tokenStart, rbName, true));
- }
- }
- }
+ // Show a list of available resource bundles
+ List<String> resourceBundles = manager.getResourceBundleIdentifiers();
+ for (String rbName : resourceBundles) {
+ if (rbName.startsWith(fullToken)) {
+ if (rbName.equals(fullToken)) {
+ hit = true;
+ } else {
+ completions.add(new MessageCompletionProposal(tokenStart,
+ tokenEnd - tokenStart, rbName, true));
+ }
+ }
+ }
- if (!hit && fullToken.trim().length() > 0) {
- completions.add(new CreateResourceBundleProposal(fullToken,
- resource, tokenStart, tokenEnd));
- }
+ if (!hit && fullToken.trim().length() > 0) {
+ completions.add(new CreateResourceBundleProposal(fullToken,
+ resource, tokenStart, tokenEnd));
+ }
- return completions;
+ return completions;
}
protected List<ICompletionProposal> getBasicJavaCompletionProposals(
- int tokenStart, int tokenEnd, int tokenOffset, String fullToken,
- boolean isStringLiteral, ResourceBundleManager manager,
- ResourceAuditVisitor csav, IResource resource) {
- List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
+ int tokenStart, int tokenEnd, int tokenOffset, String fullToken,
+ boolean isStringLiteral, ResourceBundleManager manager,
+ ResourceAuditVisitor csav, IResource resource) {
+ List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
- if (fullToken.length() == 0) {
- // If nothing has been entered
- completions.add(new InsertResourceBundleReferenceProposal(
- tokenStart, tokenEnd - tokenStart, manager.getProject()
- .getName(), resource, csav
- .getDefinedResourceBundles(tokenOffset)));
- completions.add(new NewResourceBundleEntryProposal(resource,
- tokenStart, tokenEnd, fullToken, isStringLiteral, false,
- manager.getProject().getName(), null));
- } else {
- completions.add(new NewResourceBundleEntryProposal(resource,
- tokenStart, tokenEnd, fullToken, isStringLiteral, false,
- manager.getProject().getName(), null));
- }
- return completions;
+ if (fullToken.length() == 0) {
+ // If nothing has been entered
+ completions.add(new InsertResourceBundleReferenceProposal(
+ tokenStart, tokenEnd - tokenStart, manager.getProject()
+ .getName(), resource, csav
+ .getDefinedResourceBundles(tokenOffset)));
+ completions.add(new NewResourceBundleEntryProposal(resource,
+ tokenStart, tokenEnd, fullToken, isStringLiteral, false,
+ manager.getProject().getName(), null));
+ } else {
+ completions.add(new NewResourceBundleEntryProposal(resource,
+ tokenStart, tokenEnd, fullToken, isStringLiteral, false,
+ manager.getProject().getName(), null));
+ }
+ return completions;
}
protected List<ICompletionProposal> getResourceBundleCompletionProposals(
- int tokenStart, int tokenEnd, int tokenOffset,
- boolean isStringLiteral, String fullToken,
- ResourceBundleManager manager, ResourceAuditVisitor csav,
- IResource resource) {
+ int tokenStart, int tokenEnd, int tokenOffset,
+ boolean isStringLiteral, String fullToken,
+ ResourceBundleManager manager, ResourceAuditVisitor csav,
+ IResource resource) {
- List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
- IRegion region = csav.getKeyAt(new Long(tokenOffset));
- String bundleName = csav.getBundleReference(region);
- IMessagesBundleGroup bundleGroup = manager
- .getResourceBundle(bundleName);
+ List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
+ IRegion region = csav.getKeyAt(new Long(tokenOffset));
+ String bundleName = csav.getBundleReference(region);
+ IMessagesBundleGroup bundleGroup = manager
+ .getResourceBundle(bundleName);
- if (fullToken.length() > 0) {
- boolean hit = false;
- // If a part of a String has already been entered
- for (String key : bundleGroup.getMessageKeys()) {
- if (key.toLowerCase().startsWith(fullToken)) {
- if (!key.equals(fullToken)) {
- completions.add(new MessageCompletionProposal(
- tokenStart, tokenEnd - tokenStart, key, false));
- } else {
- hit = true;
- }
- }
- }
- if (!hit) {
- completions.add(new NewResourceBundleEntryProposal(resource,
- tokenStart, tokenEnd, fullToken, isStringLiteral, true,
- manager.getProject().getName(), bundleName));
+ if (fullToken.length() > 0) {
+ boolean hit = false;
+ // If a part of a String has already been entered
+ for (String key : bundleGroup.getMessageKeys()) {
+ if (key.toLowerCase().startsWith(fullToken)) {
+ if (!key.equals(fullToken)) {
+ completions.add(new MessageCompletionProposal(
+ tokenStart, tokenEnd - tokenStart, key, false));
+ } else {
+ hit = true;
+ }
+ }
+ }
+ if (!hit) {
+ completions.add(new NewResourceBundleEntryProposal(resource,
+ tokenStart, tokenEnd, fullToken, isStringLiteral, true,
+ manager.getProject().getName(), bundleName));
- // TODO: reference to existing resource
- }
- } else {
- for (String key : bundleGroup.getMessageKeys()) {
- completions.add(new MessageCompletionProposal(tokenStart,
- tokenEnd - tokenStart, key, false));
- }
- completions.add(new NewResourceBundleEntryProposal(resource,
- tokenStart, tokenEnd, fullToken, isStringLiteral, true,
- manager.getProject().getName(), bundleName));
+ // TODO: reference to existing resource
+ }
+ } else {
+ for (String key : bundleGroup.getMessageKeys()) {
+ completions.add(new MessageCompletionProposal(tokenStart,
+ tokenEnd - tokenStart, key, false));
+ }
+ completions.add(new NewResourceBundleEntryProposal(resource,
+ tokenStart, tokenEnd, fullToken, isStringLiteral, true,
+ manager.getProject().getName(), bundleName));
- }
- return completions;
+ }
+ return completions;
}
@Override
public String getErrorMessage() {
- // TODO Auto-generated method stub
- return "";
+ // TODO Auto-generated method stub
+ return "";
}
@Override
public void sessionEnded() {
- cu = null;
- csav = null;
- resource = null;
- manager = null;
+ cu = null;
+ csav = null;
+ resource = null;
+ manager = null;
}
@Override
@@ -261,9 +261,9 @@
@Override
public List<IContextInformation> computeContextInformation(
- ContentAssistInvocationContext arg0, IProgressMonitor arg1) {
- // TODO Auto-generated method stub
- return null;
+ ContentAssistInvocationContext arg0, IProgressMonitor arg1) {
+ // TODO Auto-generated method stub
+ return null;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java
index 72fe63e..c9b4162 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java
@@ -48,184 +48,184 @@
private final String newBunldeWizard = "org.eclipse.babel.editor.wizards.ResourceBundleWizard";
public CreateResourceBundleProposal(String key, IResource resource,
- int start, int end) {
- this.key = ResourceUtils.deriveNonExistingRBName(key,
- ResourceBundleManager.getManager(resource.getProject()));
- this.resource = resource;
- this.start = start;
- this.end = end;
+ int start, int end) {
+ this.key = ResourceUtils.deriveNonExistingRBName(key,
+ ResourceBundleManager.getManager(resource.getProject()));
+ this.resource = resource;
+ this.start = start;
+ this.end = end;
}
public String getDescription() {
- return "Creates a new Resource-Bundle with the id '" + key + "'";
+ return "Creates a new Resource-Bundle with the id '" + key + "'";
}
public String getLabel() {
- return "Create Resource-Bundle '" + key + "'";
+ return "Create Resource-Bundle '" + key + "'";
}
@SuppressWarnings("deprecation")
protected void runAction() {
- // First see if this is a "new wizard".
- IWizardDescriptor descriptor = PlatformUI.getWorkbench()
- .getNewWizardRegistry().findWizard(newBunldeWizard);
- // If not check if it is an "import wizard".
- if (descriptor == null) {
- descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
- .findWizard(newBunldeWizard);
- }
- // Or maybe an export wizard
- if (descriptor == null) {
- descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
- .findWizard(newBunldeWizard);
- }
- try {
- // Then if we have a wizard, open it.
- if (descriptor != null) {
- IWizard wizard = descriptor.createWizard();
+ // First see if this is a "new wizard".
+ IWizardDescriptor descriptor = PlatformUI.getWorkbench()
+ .getNewWizardRegistry().findWizard(newBunldeWizard);
+ // If not check if it is an "import wizard".
+ if (descriptor == null) {
+ descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
+ .findWizard(newBunldeWizard);
+ }
+ // Or maybe an export wizard
+ if (descriptor == null) {
+ descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
+ .findWizard(newBunldeWizard);
+ }
+ try {
+ // Then if we have a wizard, open it.
+ if (descriptor != null) {
+ IWizard wizard = descriptor.createWizard();
- if (!(wizard instanceof IResourceBundleWizard)) {
- return;
- }
+ if (!(wizard instanceof IResourceBundleWizard)) {
+ return;
+ }
- IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
- String[] keySilbings = key.split("\\.");
- String rbName = keySilbings[keySilbings.length - 1];
- String packageName = "";
+ IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
+ String[] keySilbings = key.split("\\.");
+ String rbName = keySilbings[keySilbings.length - 1];
+ String packageName = "";
- rbw.setBundleId(rbName);
+ rbw.setBundleId(rbName);
- // Set the default path according to the specified package name
- String pathName = "";
- if (keySilbings.length > 1) {
- try {
- IJavaProject jp = JavaCore
- .create(resource.getProject());
- packageName = key.substring(0, key.lastIndexOf("."));
+ // Set the default path according to the specified package name
+ String pathName = "";
+ if (keySilbings.length > 1) {
+ try {
+ IJavaProject jp = JavaCore
+ .create(resource.getProject());
+ packageName = key.substring(0, key.lastIndexOf("."));
- for (IPackageFragmentRoot fr : jp
- .getAllPackageFragmentRoots()) {
- IPackageFragment pf = fr
- .getPackageFragment(packageName);
- if (pf.exists()) {
- pathName = pf.getResource().getFullPath()
- .removeFirstSegments(0).toOSString();
- break;
- }
- }
- } catch (Exception e) {
- pathName = "";
- }
- }
+ for (IPackageFragmentRoot fr : jp
+ .getAllPackageFragmentRoots()) {
+ IPackageFragment pf = fr
+ .getPackageFragment(packageName);
+ if (pf.exists()) {
+ pathName = pf.getResource().getFullPath()
+ .removeFirstSegments(0).toOSString();
+ break;
+ }
+ }
+ } catch (Exception e) {
+ pathName = "";
+ }
+ }
- try {
- IJavaProject jp = JavaCore.create(resource.getProject());
- if (pathName.trim().equals("")) {
- for (IPackageFragmentRoot fr : jp
- .getAllPackageFragmentRoots()) {
- if (!fr.isReadOnly()) {
- pathName = fr.getResource().getFullPath()
- .removeFirstSegments(0).toOSString();
- break;
- }
- }
- }
- } catch (Exception e) {
- pathName = "";
- }
+ try {
+ IJavaProject jp = JavaCore.create(resource.getProject());
+ if (pathName.trim().equals("")) {
+ for (IPackageFragmentRoot fr : jp
+ .getAllPackageFragmentRoots()) {
+ if (!fr.isReadOnly()) {
+ pathName = fr.getResource().getFullPath()
+ .removeFirstSegments(0).toOSString();
+ break;
+ }
+ }
+ }
+ } catch (Exception e) {
+ pathName = "";
+ }
- rbw.setDefaultPath(pathName);
+ rbw.setDefaultPath(pathName);
- WizardDialog wd = new WizardDialog(Display.getDefault()
- .getActiveShell(), wizard);
+ WizardDialog wd = new WizardDialog(Display.getDefault()
+ .getActiveShell(), wizard);
- wd.setTitle(wizard.getWindowTitle());
- if (wd.open() == WizardDialog.OK) {
- try {
- resource.getProject().build(
- IncrementalProjectBuilder.FULL_BUILD,
- I18nBuilder.BUILDER_ID, null, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
+ wd.setTitle(wizard.getWindowTitle());
+ if (wd.open() == WizardDialog.OK) {
+ try {
+ resource.getProject().build(
+ IncrementalProjectBuilder.FULL_BUILD,
+ I18nBuilder.BUILDER_ID, null, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
- ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, LocationKind.NORMALIZE,
- null);
- ITextFileBuffer textFileBuffer = bufferManager
- .getTextFileBuffer(path, LocationKind.NORMALIZE);
- IDocument document = textFileBuffer.getDocument();
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, LocationKind.NORMALIZE,
+ null);
+ ITextFileBuffer textFileBuffer = bufferManager
+ .getTextFileBuffer(path, LocationKind.NORMALIZE);
+ IDocument document = textFileBuffer.getDocument();
- if (document.get().charAt(start - 1) == '"'
- && document.get().charAt(start) != '"') {
- start--;
- end++;
- }
- if (document.get().charAt(end + 1) == '"'
- && document.get().charAt(end) != '"') {
- end++;
- }
+ if (document.get().charAt(start - 1) == '"'
+ && document.get().charAt(start) != '"') {
+ start--;
+ end++;
+ }
+ if (document.get().charAt(end + 1) == '"'
+ && document.get().charAt(end) != '"') {
+ end++;
+ }
- document.replace(start, end - start, "\""
- + (packageName.equals("") ? "" : packageName
- + ".") + rbName + "\"");
+ document.replace(start, end - start, "\""
+ + (packageName.equals("") ? "" : packageName
+ + ".") + rbName + "\"");
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- }
- }
- }
- }
- } catch (CoreException e) {
- }
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ } finally {
+ try {
+ bufferManager.disconnect(path, null);
+ } catch (CoreException e) {
+ }
+ }
+ }
+ }
+ } catch (CoreException e) {
+ }
}
@Override
public void apply(IDocument document) {
- this.runAction();
+ this.runAction();
}
@Override
public String getAdditionalProposalInfo() {
- return getDescription();
+ return getDescription();
}
@Override
public IContextInformation getContextInformation() {
- return null;
+ return null;
}
@Override
public String getDisplayString() {
- return getLabel();
+ return getLabel();
}
@Override
public Point getSelection(IDocument document) {
- return null;
+ return null;
}
@Override
public Image getImage() {
- return PlatformUI.getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage();
+ return PlatformUI.getWorkbench().getSharedImages()
+ .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage();
}
@Override
public int getRelevance() {
- // TODO Auto-generated method stub
- if (end - start == 0) {
- return 99;
- } else {
- return 1099;
- }
+ // TODO Auto-generated method stub
+ if (end - start == 0) {
+ return 99;
+ } else {
+ return 1099;
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java
index 066271c..886847a 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java
@@ -27,7 +27,7 @@
import org.eclipse.ui.PlatformUI;
public class InsertResourceBundleReferenceProposal implements
- IJavaCompletionProposal {
+ IJavaCompletionProposal {
private int offset = 0;
private int length = 0;
@@ -36,69 +36,69 @@
private String projectName;
public InsertResourceBundleReferenceProposal(int offset, int length,
- String projectName, IResource resource,
- Collection<String> availableBundles) {
- this.offset = offset;
- this.length = length;
- this.resource = resource;
- this.projectName = projectName;
+ String projectName, IResource resource,
+ Collection<String> availableBundles) {
+ this.offset = offset;
+ this.length = length;
+ this.resource = resource;
+ this.projectName = projectName;
}
@Override
public void apply(IDocument document) {
- ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
- Display.getDefault().getActiveShell());
- dialog.setProjectName(projectName);
+ ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
+ Display.getDefault().getActiveShell());
+ dialog.setProjectName(projectName);
- if (dialog.open() != InputDialog.OK) {
- return;
- }
+ if (dialog.open() != InputDialog.OK) {
+ return;
+ }
- String resourceBundleId = dialog.getSelectedResourceBundle();
- String key = dialog.getSelectedResource();
- Locale locale = dialog.getSelectedLocale();
+ String resourceBundleId = dialog.getSelectedResourceBundle();
+ String key = dialog.getSelectedResource();
+ Locale locale = dialog.getSelectedLocale();
- reference = ASTutilsUI.insertExistingBundleRef(document, resource,
- offset, length, resourceBundleId, key, locale);
+ reference = ASTutilsUI.insertExistingBundleRef(document, resource,
+ offset, length, resourceBundleId, key, locale);
}
@Override
public String getAdditionalProposalInfo() {
- // TODO Auto-generated method stub
- return null;
+ // TODO Auto-generated method stub
+ return null;
}
@Override
public IContextInformation getContextInformation() {
- return null;
+ return null;
}
@Override
public String getDisplayString() {
- return "Insert reference to a localized string literal";
+ return "Insert reference to a localized string literal";
}
@Override
public Image getImage() {
- return PlatformUI.getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage();
+ return PlatformUI.getWorkbench().getSharedImages()
+ .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage();
}
@Override
public Point getSelection(IDocument document) {
- // TODO Auto-generated method stub
- int referenceLength = reference == null ? 0 : reference.length();
- return new Point(offset + referenceLength, 0);
+ // TODO Auto-generated method stub
+ int referenceLength = reference == null ? 0 : reference.length();
+ return new Point(offset + referenceLength, 0);
}
@Override
public int getRelevance() {
- // TODO Auto-generated method stub
- if (this.length == 0) {
- return 97;
- } else {
- return 1097;
- }
+ // TODO Auto-generated method stub
+ if (this.length == 0) {
+ return 97;
+ } else {
+ return 1097;
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java
index a56d19c..6d5d393 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java
@@ -26,52 +26,52 @@
private boolean messageAccessor = false;
public MessageCompletionProposal(int offset, int length, String content,
- boolean messageAccessor) {
- this.offset = offset;
- this.length = length;
- this.content = content;
- this.messageAccessor = messageAccessor;
+ boolean messageAccessor) {
+ this.offset = offset;
+ this.length = length;
+ this.content = content;
+ this.messageAccessor = messageAccessor;
}
@Override
public void apply(IDocument document) {
- try {
- document.replace(offset, length, content);
- } catch (Exception e) {
- Logger.logError(e);
- }
+ try {
+ document.replace(offset, length, content);
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
}
@Override
public String getAdditionalProposalInfo() {
- return "Inserts the resource key '" + this.content + "'";
+ return "Inserts the resource key '" + this.content + "'";
}
@Override
public IContextInformation getContextInformation() {
- return null;
+ return null;
}
@Override
public String getDisplayString() {
- return content;
+ return content;
}
@Override
public Image getImage() {
- if (messageAccessor)
- return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
- return ImageUtils.getImage(ImageUtils.IMAGE_PROPERTIES_FILE);
+ if (messageAccessor)
+ return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
+ return ImageUtils.getImage(ImageUtils.IMAGE_PROPERTIES_FILE);
}
@Override
public Point getSelection(IDocument document) {
- return new Point(offset + content.length() + 1, 0);
+ return new Point(offset + content.length() + 1, 0);
}
@Override
public int getRelevance() {
- return 99;
+ return 99;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java
index 6960fa3..8a68647 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java
@@ -38,104 +38,104 @@
private String reference;
public NewResourceBundleEntryProposal(IResource resource, int startPos,
- int endPos, String value, boolean isStringLiteral,
- boolean bundleContext, String projectName, String bundleName) {
+ int endPos, String value, boolean isStringLiteral,
+ boolean bundleContext, String projectName, String bundleName) {
- this.startPos = startPos;
- this.endPos = endPos;
- this.value = value;
- this.bundleContext = bundleContext;
- this.projectName = projectName;
- this.resource = resource;
- this.bundleName = bundleName;
+ this.startPos = startPos;
+ this.endPos = endPos;
+ this.value = value;
+ this.bundleContext = bundleContext;
+ this.projectName = projectName;
+ this.resource = resource;
+ this.bundleName = bundleName;
}
@Override
public void apply(IDocument document) {
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell());
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
- DialogConfiguration config = dialog.new DialogConfiguration();
- config.setPreselectedKey(bundleContext ? value : "");
- config.setPreselectedMessage(value);
- config.setPreselectedBundle(bundleName == null ? "" : bundleName);
- config.setPreselectedLocale("");
- config.setProjectName(projectName);
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey(bundleContext ? value : "");
+ config.setPreselectedMessage(value);
+ config.setPreselectedBundle(bundleName == null ? "" : bundleName);
+ config.setPreselectedLocale("");
+ config.setProjectName(projectName);
- dialog.setDialogConfiguration(config);
+ dialog.setDialogConfiguration(config);
- if (dialog.open() != InputDialog.OK) {
- return;
- }
+ if (dialog.open() != InputDialog.OK) {
+ return;
+ }
- String resourceBundleId = dialog.getSelectedResourceBundle();
- String key = dialog.getSelectedKey();
+ String resourceBundleId = dialog.getSelectedResourceBundle();
+ String key = dialog.getSelectedKey();
- try {
- if (!bundleContext) {
- reference = ASTutilsUI.insertNewBundleRef(document, resource,
- startPos, endPos - startPos, resourceBundleId, key);
- } else {
- document.replace(startPos, endPos - startPos, key);
- reference = key + "\"";
- }
- ResourceBundleManager.rebuildProject(resource);
- } catch (Exception e) {
- Logger.logError(e);
- }
+ try {
+ if (!bundleContext) {
+ reference = ASTutilsUI.insertNewBundleRef(document, resource,
+ startPos, endPos - startPos, resourceBundleId, key);
+ } else {
+ document.replace(startPos, endPos - startPos, key);
+ reference = key + "\"";
+ }
+ ResourceBundleManager.rebuildProject(resource);
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
}
@Override
public String getAdditionalProposalInfo() {
- if (value != null && value.length() > 0) {
- return "Exports the focused string literal into a Java Resource-Bundle. This action results "
- + "in a Resource-Bundle reference!";
- } else {
- return "";
- }
+ if (value != null && value.length() > 0) {
+ return "Exports the focused string literal into a Java Resource-Bundle. This action results "
+ + "in a Resource-Bundle reference!";
+ } else {
+ return "";
+ }
}
@Override
public IContextInformation getContextInformation() {
- return null;
+ return null;
}
@Override
public String getDisplayString() {
- String displayStr = "";
- if (bundleContext) {
- displayStr = "Create a new resource-bundle-entry";
- } else {
- displayStr = "Create a new localized string literal";
- }
+ String displayStr = "";
+ if (bundleContext) {
+ displayStr = "Create a new resource-bundle-entry";
+ } else {
+ displayStr = "Create a new localized string literal";
+ }
- if (value != null && value.length() > 0) {
- displayStr += " for '" + value + "'";
- }
+ if (value != null && value.length() > 0) {
+ displayStr += " for '" + value + "'";
+ }
- return displayStr;
+ return displayStr;
}
@Override
public Image getImage() {
- return PlatformUI.getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage();
+ return PlatformUI.getWorkbench().getSharedImages()
+ .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage();
}
@Override
public Point getSelection(IDocument document) {
- int refLength = reference == null ? 0 : reference.length() - 1;
- return new Point(startPos + refLength, 0);
+ int refLength = reference == null ? 0 : reference.length() - 1;
+ return new Point(startPos + refLength, 0);
}
@Override
public int getRelevance() {
- if (this.value.trim().length() == 0) {
- return 96;
- } else {
- return 1096;
- }
+ if (this.value.trim().length() == 0) {
+ return 96;
+ } else {
+ return 1096;
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java
index 1af9bca..f6a6ec5 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java
@@ -19,49 +19,49 @@
public class NoActionProposal implements IJavaCompletionProposal {
public NoActionProposal() {
- super();
+ super();
}
@Override
public void apply(IDocument document) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
}
@Override
public String getAdditionalProposalInfo() {
- // TODO Auto-generated method stub
- return null;
+ // TODO Auto-generated method stub
+ return null;
}
@Override
public IContextInformation getContextInformation() {
- // TODO Auto-generated method stub
- return null;
+ // TODO Auto-generated method stub
+ return null;
}
@Override
public String getDisplayString() {
- // TODO Auto-generated method stub
- return "No Default Proposals";
+ // TODO Auto-generated method stub
+ return "No Default Proposals";
}
@Override
public Image getImage() {
- // TODO Auto-generated method stub
- return null;
+ // TODO Auto-generated method stub
+ return null;
}
@Override
public Point getSelection(IDocument document) {
- // TODO Auto-generated method stub
- return null;
+ // TODO Auto-generated method stub
+ return null;
}
@Override
public int getRelevance() {
- // TODO Auto-generated method stub
- return 100;
+ // TODO Auto-generated method stub
+ return 100;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java
index 4c35d72..a49665f 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java
@@ -21,27 +21,27 @@
@Override
public void beginSorting(ContentAssistInvocationContext context) {
- // TODO Auto-generated method stub
- super.beginSorting(context);
+ // TODO Auto-generated method stub
+ super.beginSorting(context);
}
@Override
public int compare(ICompletionProposal prop1, ICompletionProposal prop2) {
- return getIndex(prop1) - getIndex(prop2);
+ return getIndex(prop1) - getIndex(prop2);
}
protected int getIndex(ICompletionProposal prop) {
- if (prop instanceof NoActionProposal) {
- return 1;
- } else if (prop instanceof MessageCompletionProposal) {
- return 2;
- } else if (prop instanceof InsertResourceBundleReferenceProposal) {
- return 3;
- } else if (prop instanceof NewResourceBundleEntryProposal) {
- return 4;
- } else {
- return 0;
- }
+ if (prop instanceof NoActionProposal) {
+ return 1;
+ } else if (prop instanceof MessageCompletionProposal) {
+ return 2;
+ } else if (prop instanceof InsertResourceBundleReferenceProposal) {
+ return 3;
+ } else if (prop instanceof NewResourceBundleEntryProposal) {
+ return 4;
+ } else {
+ return 0;
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/model/SLLocation.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/model/SLLocation.java
index 3e2ddc9..23d86fe 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/model/SLLocation.java
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/model/SLLocation.java
@@ -25,52 +25,52 @@
private Serializable data;
public SLLocation(IFile file, int startPos, int endPos, String literal) {
- super();
- this.file = file;
- this.startPos = startPos;
- this.endPos = endPos;
- this.literal = literal;
+ super();
+ this.file = file;
+ this.startPos = startPos;
+ this.endPos = endPos;
+ this.literal = literal;
}
@Override
public IFile getFile() {
- return file;
+ return file;
}
public void setFile(IFile file) {
- this.file = file;
+ this.file = file;
}
@Override
public int getStartPos() {
- return startPos;
+ return startPos;
}
public void setStartPos(int startPos) {
- this.startPos = startPos;
+ this.startPos = startPos;
}
@Override
public int getEndPos() {
- return endPos;
+ return endPos;
}
public void setEndPos(int endPos) {
- this.endPos = endPos;
+ this.endPos = endPos;
}
@Override
public String getLiteral() {
- return literal;
+ return literal;
}
@Override
public Serializable getData() {
- return data;
+ return data;
}
public void setData(Serializable data) {
- this.data = data;
+ this.data = data;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExcludeResourceFromInternationalization.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExcludeResourceFromInternationalization.java
index 75e71b8..54f8a00 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExcludeResourceFromInternationalization.java
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExcludeResourceFromInternationalization.java
@@ -22,48 +22,48 @@
import org.eclipse.ui.progress.IProgressService;
public class ExcludeResourceFromInternationalization implements
- IMarkerResolution2 {
+ IMarkerResolution2 {
@Override
public String getLabel() {
- return "Exclude Resource";
+ return "Exclude Resource";
}
@Override
public void run(IMarker marker) {
- final IResource resource = marker.getResource();
+ final IResource resource = marker.getResource();
- IWorkbench wb = PlatformUI.getWorkbench();
- IProgressService ps = wb.getProgressService();
- try {
- ps.busyCursorWhile(new IRunnableWithProgress() {
- public void run(IProgressMonitor pm) {
+ IWorkbench wb = PlatformUI.getWorkbench();
+ IProgressService ps = wb.getProgressService();
+ try {
+ ps.busyCursorWhile(new IRunnableWithProgress() {
+ public void run(IProgressMonitor pm) {
- ResourceBundleManager manager = null;
- pm.beginTask(
- "Excluding Resource from Internationalization", 1);
+ ResourceBundleManager manager = null;
+ pm.beginTask(
+ "Excluding Resource from Internationalization", 1);
- if (manager == null
- || (manager.getProject() != resource.getProject()))
- manager = ResourceBundleManager.getManager(resource
- .getProject());
- manager.excludeResource(resource, pm);
- pm.worked(1);
- pm.done();
- }
- });
- } catch (Exception e) {
- }
+ if (manager == null
+ || (manager.getProject() != resource.getProject()))
+ manager = ResourceBundleManager.getManager(resource
+ .getProject());
+ manager.excludeResource(resource, pm);
+ pm.worked(1);
+ pm.done();
+ }
+ });
+ } catch (Exception e) {
+ }
}
@Override
public String getDescription() {
- return "Exclude Resource from Internationalization";
+ return "Exclude Resource from Internationalization";
}
@Override
public Image getImage() {
- return null;
+ return null;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java
index fc3a130..bcceaed 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java
@@ -34,66 +34,66 @@
@Override
public String getDescription() {
- return "Export constant string literal to a resource bundle.";
+ return "Export constant string literal to a resource bundle.";
}
@Override
public Image getImage() {
- // TODO Auto-generated method stub
- return null;
+ // TODO Auto-generated method stub
+ return null;
}
@Override
public String getLabel() {
- return "Export to Resource-Bundle";
+ return "Export to Resource-Bundle";
}
@Override
public void run(IMarker marker) {
- int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
- int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
- IResource resource = marker.getResource();
+ int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
+ int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
+ IResource resource = marker.getResource();
- ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, LocationKind.NORMALIZE, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(
- path, LocationKind.NORMALIZE);
- IDocument document = textFileBuffer.getDocument();
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, LocationKind.NORMALIZE, null);
+ ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(
+ path, LocationKind.NORMALIZE);
+ IDocument document = textFileBuffer.getDocument();
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell());
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
- DialogConfiguration config = dialog.new DialogConfiguration();
- config.setPreselectedKey("");
- config.setPreselectedMessage("");
- config.setPreselectedMessage((startPos + 1 < document.getLength() && endPos > 1) ? document
- .get(startPos + 1, endPos - 2) : "");
- config.setPreselectedLocale("");
- config.setProjectName(resource.getProject().getName());
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey("");
+ config.setPreselectedMessage("");
+ config.setPreselectedMessage((startPos + 1 < document.getLength() && endPos > 1) ? document
+ .get(startPos + 1, endPos - 2) : "");
+ config.setPreselectedLocale("");
+ config.setProjectName(resource.getProject().getName());
- dialog.setDialogConfiguration(config);
+ dialog.setDialogConfiguration(config);
- if (dialog.open() != InputDialog.OK)
- return;
+ if (dialog.open() != InputDialog.OK)
+ return;
- ASTutilsUI
- .insertNewBundleRef(document, resource, startPos, endPos,
- dialog.getSelectedResourceBundle(),
- dialog.getSelectedKey());
+ ASTutilsUI
+ .insertNewBundleRef(document, resource, startPos, endPos,
+ dialog.getSelectedResourceBundle(),
+ dialog.getSelectedKey());
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ bufferManager.disconnect(path, null);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/IgnoreStringFromInternationalization.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/IgnoreStringFromInternationalization.java
index ce3b10b..67429aa 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/IgnoreStringFromInternationalization.java
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/IgnoreStringFromInternationalization.java
@@ -31,48 +31,48 @@
@Override
public String getLabel() {
- return "Ignore String";
+ return "Ignore String";
}
@Override
public void run(IMarker marker) {
- IResource resource = marker.getResource();
+ IResource resource = marker.getResource();
- CompilationUnit cu = ASTutilsUI.getCompilationUnit(resource);
+ CompilationUnit cu = ASTutilsUI.getCompilationUnit(resource);
- ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
- IPath path = resource.getRawLocation();
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, LocationKind.NORMALIZE, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(
- path, LocationKind.NORMALIZE);
- IDocument document = textFileBuffer.getDocument();
+ try {
+ bufferManager.connect(path, LocationKind.NORMALIZE, null);
+ ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(
+ path, LocationKind.NORMALIZE);
+ IDocument document = textFileBuffer.getDocument();
- int position = marker.getAttribute(IMarker.CHAR_START, 0);
+ int position = marker.getAttribute(IMarker.CHAR_START, 0);
- ASTutils.createReplaceNonInternationalisationComment(cu, document,
- position);
- textFileBuffer.commit(null, false);
+ ASTutils.createReplaceNonInternationalisationComment(cu, document,
+ position);
+ textFileBuffer.commit(null, false);
- } catch (JavaModelException e) {
- Logger.logError(e);
- } catch (CoreException e) {
- Logger.logError(e);
- }
+ } catch (JavaModelException e) {
+ Logger.logError(e);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
}
@Override
public String getDescription() {
- return "Ignore String from Internationalization";
+ return "Ignore String from Internationalization";
}
@Override
public Image getImage() {
- // TODO Auto-generated method stub
- return null;
+ // TODO Auto-generated method stub
+ return null;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java
index 2fa6cfc..162ad5c 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java
@@ -32,66 +32,66 @@
private int end;
public ReplaceResourceBundleDefReference(String key, int start, int end) {
- this.key = key;
- this.start = start;
- this.end = end;
+ this.key = key;
+ this.start = start;
+ this.end = end;
}
@Override
public String getDescription() {
- return "Replaces the non-existing Resource-Bundle reference '" + key
- + "' with a reference to an already existing Resource-Bundle.";
+ return "Replaces the non-existing Resource-Bundle reference '" + key
+ + "' with a reference to an already existing Resource-Bundle.";
}
@Override
public Image getImage() {
- // TODO Auto-generated method stub
- return null;
+ // TODO Auto-generated method stub
+ return null;
}
@Override
public String getLabel() {
- return "Select an alternative Resource-Bundle";
+ return "Select an alternative Resource-Bundle";
}
@Override
public void run(IMarker marker) {
- int startPos = start;
- int endPos = end - start;
- IResource resource = marker.getResource();
+ int startPos = start;
+ int endPos = end - start;
+ IResource resource = marker.getResource();
- ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, LocationKind.NORMALIZE, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(
- path, LocationKind.NORMALIZE);
- IDocument document = textFileBuffer.getDocument();
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, LocationKind.NORMALIZE, null);
+ ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(
+ path, LocationKind.NORMALIZE);
+ IDocument document = textFileBuffer.getDocument();
- ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog(
- Display.getDefault().getActiveShell(),
- resource.getProject());
+ ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog(
+ Display.getDefault().getActiveShell(),
+ resource.getProject());
- if (dialog.open() != InputDialog.OK)
- return;
+ if (dialog.open() != InputDialog.OK)
+ return;
- key = dialog.getSelectedBundleId();
- int iSep = key.lastIndexOf("/");
- key = iSep != -1 ? key.substring(iSep + 1) : key;
+ key = dialog.getSelectedBundleId();
+ int iSep = key.lastIndexOf("/");
+ key = iSep != -1 ? key.substring(iSep + 1) : key;
- document.replace(startPos, endPos, "\"" + key + "\"");
+ document.replace(startPos, endPos, "\"" + key + "\"");
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bufferManager.disconnect(path, LocationKind.NORMALIZE, null);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ bufferManager.disconnect(path, LocationKind.NORMALIZE, null);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java
index f0eaedc..a959b54 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java
@@ -33,66 +33,66 @@
private String bundleId;
public ReplaceResourceBundleReference(String key, String bundleId) {
- this.key = key;
- this.bundleId = bundleId;
+ this.key = key;
+ this.bundleId = bundleId;
}
@Override
public String getDescription() {
- return "Replaces the non-existing Resource-Bundle key '"
- + key
- + "' with a reference to an already existing localized string literal.";
+ return "Replaces the non-existing Resource-Bundle key '"
+ + key
+ + "' with a reference to an already existing localized string literal.";
}
@Override
public Image getImage() {
- return null;
+ return null;
}
@Override
public String getLabel() {
- return "Select alternative Resource-Bundle entry";
+ return "Select alternative Resource-Bundle entry";
}
@Override
public void run(IMarker marker) {
- int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
- int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
- IResource resource = marker.getResource();
+ int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
+ int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
+ IResource resource = marker.getResource();
- ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, LocationKind.NORMALIZE, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(
- path, LocationKind.NORMALIZE);
- IDocument document = textFileBuffer.getDocument();
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, LocationKind.NORMALIZE, null);
+ ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(
+ path, LocationKind.NORMALIZE);
+ IDocument document = textFileBuffer.getDocument();
- ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
- Display.getDefault().getActiveShell());
+ ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
+ Display.getDefault().getActiveShell());
- dialog.setProjectName(resource.getProject().getName());
- dialog.setBundleName(bundleId);
+ dialog.setProjectName(resource.getProject().getName());
+ dialog.setBundleName(bundleId);
- if (dialog.open() != InputDialog.OK)
- return;
+ if (dialog.open() != InputDialog.OK)
+ return;
- String key = dialog.getSelectedResource();
- Locale locale = dialog.getSelectedLocale();
+ String key = dialog.getSelectedResource();
+ Locale locale = dialog.getSelectedLocale();
- document.replace(startPos, endPos, "\"" + key + "\"");
+ document.replace(startPos, endPos, "\"" + key + "\"");
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bufferManager.disconnect(path, LocationKind.NORMALIZE, null);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ bufferManager.disconnect(path, LocationKind.NORMALIZE, null);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/util/ASTutilsUI.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/util/ASTutilsUI.java
index 0c1ad87..d7e96a3 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/util/ASTutilsUI.java
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/util/ASTutilsUI.java
@@ -28,125 +28,125 @@
public class ASTutilsUI {
public static CompilationUnit getCompilationUnit(IResource resource) {
- IJavaElement je = JavaCore.create(resource,
- JavaCore.create(resource.getProject()));
- // get the type of the currently loaded resource
- ITypeRoot typeRoot = ((ICompilationUnit) je);
+ IJavaElement je = JavaCore.create(resource,
+ JavaCore.create(resource.getProject()));
+ // get the type of the currently loaded resource
+ ITypeRoot typeRoot = ((ICompilationUnit) je);
- if (typeRoot == null) {
- return null;
- }
+ if (typeRoot == null) {
+ return null;
+ }
- return getCompilationUnit(typeRoot);
+ return getCompilationUnit(typeRoot);
}
public static CompilationUnit getCompilationUnit(ITypeRoot typeRoot) {
- // get a reference to the shared AST of the loaded CompilationUnit
- CompilationUnit cu = SharedASTProvider.getAST(typeRoot,
- // do not wait for AST creation
- SharedASTProvider.WAIT_YES, null);
+ // get a reference to the shared AST of the loaded CompilationUnit
+ CompilationUnit cu = SharedASTProvider.getAST(typeRoot,
+ // do not wait for AST creation
+ SharedASTProvider.WAIT_YES, null);
- return cu;
+ return cu;
}
public static String insertNewBundleRef(IDocument document,
- IResource resource, int startPos, int endPos,
- String resourceBundleId, String key) {
- String newName = null;
- String reference = "";
+ IResource resource, int startPos, int endPos,
+ String resourceBundleId, String key) {
+ String newName = null;
+ String reference = "";
- CompilationUnit cu = getCompilationUnit(resource);
+ CompilationUnit cu = getCompilationUnit(resource);
- if (cu == null) {
- return null;
- }
+ if (cu == null) {
+ return null;
+ }
- String variableName = ASTutils.resolveRBReferenceVar(document,
- resource, startPos, resourceBundleId, cu);
- if (variableName == null) {
- newName = ASTutils.getNonExistingRBRefName(resourceBundleId,
- document, cu);
- }
+ String variableName = ASTutils.resolveRBReferenceVar(document,
+ resource, startPos, resourceBundleId, cu);
+ if (variableName == null) {
+ newName = ASTutils.getNonExistingRBRefName(resourceBundleId,
+ document, cu);
+ }
- try {
- reference = ASTutils.createResourceReference(resourceBundleId, key,
- null, resource, startPos, variableName == null ? newName
- : variableName, document, cu);
+ try {
+ reference = ASTutils.createResourceReference(resourceBundleId, key,
+ null, resource, startPos, variableName == null ? newName
+ : variableName, document, cu);
- if (startPos > 0 && document.get().charAt(startPos - 1) == '\"') {
- startPos--;
- endPos++;
- }
+ if (startPos > 0 && document.get().charAt(startPos - 1) == '\"') {
+ startPos--;
+ endPos++;
+ }
- if ((startPos + endPos) < document.getLength()
- && document.get().charAt(startPos + endPos) == '\"') {
- endPos++;
- }
+ if ((startPos + endPos) < document.getLength()
+ && document.get().charAt(startPos + endPos) == '\"') {
+ endPos++;
+ }
- if ((startPos + endPos) < document.getLength()
- && document.get().charAt(startPos + endPos - 1) == ';') {
- endPos--;
- }
+ if ((startPos + endPos) < document.getLength()
+ && document.get().charAt(startPos + endPos - 1) == ';') {
+ endPos--;
+ }
- document.replace(startPos, endPos, reference);
+ document.replace(startPos, endPos, reference);
- // create non-internationalisation-comment
- ASTutils.createReplaceNonInternationalisationComment(cu, document,
- startPos);
- } catch (BadLocationException e) {
- e.printStackTrace();
- }
+ // create non-internationalisation-comment
+ ASTutils.createReplaceNonInternationalisationComment(cu, document,
+ startPos);
+ } catch (BadLocationException e) {
+ e.printStackTrace();
+ }
- if (variableName == null) {
- // refresh reference to the shared AST of the loaded CompilationUnit
- cu = getCompilationUnit(resource);
+ if (variableName == null) {
+ // refresh reference to the shared AST of the loaded CompilationUnit
+ cu = getCompilationUnit(resource);
- ASTutils.createResourceBundleReference(resource, startPos,
- document, resourceBundleId, null, true, newName, cu);
- // createReplaceNonInternationalisationComment(cu, document, pos);
- }
+ ASTutils.createResourceBundleReference(resource, startPos,
+ document, resourceBundleId, null, true, newName, cu);
+ // createReplaceNonInternationalisationComment(cu, document, pos);
+ }
- return reference;
+ return reference;
}
public static String insertExistingBundleRef(IDocument document,
- IResource resource, int offset, int length,
- String resourceBundleId, String key, Locale locale) {
- String reference = "";
- String newName = null;
+ IResource resource, int offset, int length,
+ String resourceBundleId, String key, Locale locale) {
+ String reference = "";
+ String newName = null;
- CompilationUnit cu = getCompilationUnit(resource);
+ CompilationUnit cu = getCompilationUnit(resource);
- String variableName = ASTutils.resolveRBReferenceVar(document,
- resource, offset, resourceBundleId, cu);
- if (variableName == null) {
- newName = ASTutils.getNonExistingRBRefName(resourceBundleId,
- document, cu);
- }
+ String variableName = ASTutils.resolveRBReferenceVar(document,
+ resource, offset, resourceBundleId, cu);
+ if (variableName == null) {
+ newName = ASTutils.getNonExistingRBRefName(resourceBundleId,
+ document, cu);
+ }
- try {
- reference = ASTutils.createResourceReference(resourceBundleId, key,
- locale, resource, offset, variableName == null ? newName
- : variableName, document, cu);
+ try {
+ reference = ASTutils.createResourceReference(resourceBundleId, key,
+ locale, resource, offset, variableName == null ? newName
+ : variableName, document, cu);
- document.replace(offset, length, reference);
+ document.replace(offset, length, reference);
- // create non-internationalisation-comment
- ASTutils.createReplaceNonInternationalisationComment(cu, document,
- offset);
- } catch (BadLocationException e) {
- e.printStackTrace();
- }
+ // create non-internationalisation-comment
+ ASTutils.createReplaceNonInternationalisationComment(cu, document,
+ offset);
+ } catch (BadLocationException e) {
+ e.printStackTrace();
+ }
- // TODO retrieve cu in the same way as in createResourceReference
- // the current version does not parse method bodies
+ // TODO retrieve cu in the same way as in createResourceReference
+ // the current version does not parse method bodies
- if (variableName == null) {
- ASTutils.createResourceBundleReference(resource, offset, document,
- resourceBundleId, locale, true, newName, cu);
- // createReplaceNonInternationalisationComment(cu, document, pos);
- }
- return reference;
+ if (variableName == null) {
+ ASTutils.createResourceBundleReference(resource, offset, document,
+ resourceBundleId, locale, true, newName, cu);
+ // createReplaceNonInternationalisationComment(cu, document, pos);
+ }
+ return reference;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java
index e89b5ca..5010e96 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java
@@ -58,887 +58,887 @@
private static MethodParameterDescriptor rbAccessor;
public static MethodParameterDescriptor getRBDefinitionDesc() {
- if (rbDefinition == null) {
- // Init descriptor for Resource-Bundle-Definition
- List<String> definition = new ArrayList<String>();
- definition.add("getBundle");
- rbDefinition = new MethodParameterDescriptor(definition,
- "java.util.ResourceBundle", true, 0);
- }
+ if (rbDefinition == null) {
+ // Init descriptor for Resource-Bundle-Definition
+ List<String> definition = new ArrayList<String>();
+ definition.add("getBundle");
+ rbDefinition = new MethodParameterDescriptor(definition,
+ "java.util.ResourceBundle", true, 0);
+ }
- return rbDefinition;
+ return rbDefinition;
}
public static MethodParameterDescriptor getRBAccessorDesc() {
- if (rbAccessor == null) {
- // Init descriptor for Resource-Bundle-Accessors
- List<String> accessors = new ArrayList<String>();
- accessors.add("getString");
- accessors.add("getStringArray");
- rbAccessor = new MethodParameterDescriptor(accessors,
- "java.util.ResourceBundle", true, 0);
- }
+ if (rbAccessor == null) {
+ // Init descriptor for Resource-Bundle-Accessors
+ List<String> accessors = new ArrayList<String>();
+ accessors.add("getString");
+ accessors.add("getStringArray");
+ rbAccessor = new MethodParameterDescriptor(accessors,
+ "java.util.ResourceBundle", true, 0);
+ }
- return rbAccessor;
+ return rbAccessor;
}
public static String resolveRBReferenceVar(IDocument document,
- IResource resource, int pos, final String bundleId,
- CompilationUnit cu) {
- String bundleVar;
+ IResource resource, int pos, final String bundleId,
+ CompilationUnit cu) {
+ String bundleVar;
- PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos);
- cu.accept(typeFinder);
- AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType();
- TypeDeclaration td = typeFinder.getEnclosingType();
- MethodDeclaration meth = typeFinder.getEnclosingMethod();
+ PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos);
+ cu.accept(typeFinder);
+ AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType();
+ TypeDeclaration td = typeFinder.getEnclosingType();
+ MethodDeclaration meth = typeFinder.getEnclosingMethod();
- if (atd == null) {
- BundleDeclarationFinder bdf = new BundleDeclarationFinder(
- bundleId,
- td,
- meth != null
- && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC);
- td.accept(bdf);
+ if (atd == null) {
+ BundleDeclarationFinder bdf = new BundleDeclarationFinder(
+ bundleId,
+ td,
+ meth != null
+ && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC);
+ td.accept(bdf);
- bundleVar = bdf.getVariableName();
- } else {
- BundleDeclarationFinder bdf = new BundleDeclarationFinder(
- bundleId,
- atd,
- meth != null
- && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC);
- atd.accept(bdf);
+ bundleVar = bdf.getVariableName();
+ } else {
+ BundleDeclarationFinder bdf = new BundleDeclarationFinder(
+ bundleId,
+ atd,
+ meth != null
+ && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC);
+ atd.accept(bdf);
- bundleVar = bdf.getVariableName();
- }
+ bundleVar = bdf.getVariableName();
+ }
- // Check also method body
- if (meth != null) {
- try {
- InMethodBundleDeclFinder imbdf = new InMethodBundleDeclFinder(
- bundleId, pos);
- typeFinder.getEnclosingMethod().accept(imbdf);
- bundleVar = imbdf.getVariableName() != null ? imbdf
- .getVariableName() : bundleVar;
- } catch (Exception e) {
- // ignore
- }
- }
+ // Check also method body
+ if (meth != null) {
+ try {
+ InMethodBundleDeclFinder imbdf = new InMethodBundleDeclFinder(
+ bundleId, pos);
+ typeFinder.getEnclosingMethod().accept(imbdf);
+ bundleVar = imbdf.getVariableName() != null ? imbdf
+ .getVariableName() : bundleVar;
+ } catch (Exception e) {
+ // ignore
+ }
+ }
- return bundleVar;
+ return bundleVar;
}
public static String getNonExistingRBRefName(String bundleId,
- IDocument document, CompilationUnit cu) {
- String referenceName = null;
- int i = 0;
+ IDocument document, CompilationUnit cu) {
+ String referenceName = null;
+ int i = 0;
- while (referenceName == null) {
- String actRef = bundleId.substring(bundleId.lastIndexOf(".") + 1)
- + "Ref" + (i == 0 ? "" : i);
- actRef = actRef.toLowerCase();
+ while (referenceName == null) {
+ String actRef = bundleId.substring(bundleId.lastIndexOf(".") + 1)
+ + "Ref" + (i == 0 ? "" : i);
+ actRef = actRef.toLowerCase();
- VariableFinder vf = new VariableFinder(actRef);
- cu.accept(vf);
+ VariableFinder vf = new VariableFinder(actRef);
+ cu.accept(vf);
- if (!vf.isVariableFound()) {
- referenceName = actRef;
- break;
- }
+ if (!vf.isVariableFound()) {
+ referenceName = actRef;
+ break;
+ }
- i++;
- }
+ i++;
+ }
- return referenceName;
+ return referenceName;
}
@Deprecated
public static String resolveResourceBundle(
- MethodInvocation methodInvocation,
- MethodParameterDescriptor rbDefinition,
- Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) {
- String bundleName = null;
+ MethodInvocation methodInvocation,
+ MethodParameterDescriptor rbDefinition,
+ Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) {
+ String bundleName = null;
- if (methodInvocation.getExpression() instanceof SimpleName) {
- SimpleName vName = (SimpleName) methodInvocation.getExpression();
- IVariableBinding vBinding = (IVariableBinding) vName
- .resolveBinding();
- VariableDeclarationFragment dec = variableBindingManagers
- .get(vBinding);
+ if (methodInvocation.getExpression() instanceof SimpleName) {
+ SimpleName vName = (SimpleName) methodInvocation.getExpression();
+ IVariableBinding vBinding = (IVariableBinding) vName
+ .resolveBinding();
+ VariableDeclarationFragment dec = variableBindingManagers
+ .get(vBinding);
- if (dec.getInitializer() instanceof MethodInvocation) {
- MethodInvocation init = (MethodInvocation) dec.getInitializer();
+ if (dec.getInitializer() instanceof MethodInvocation) {
+ MethodInvocation init = (MethodInvocation) dec.getInitializer();
- // Check declaring class
- boolean isValidClass = false;
- ITypeBinding type = init.resolveMethodBinding()
- .getDeclaringClass();
- while (type != null) {
- if (type.getQualifiedName().equals(
- rbDefinition.getDeclaringClass())) {
- isValidClass = true;
- break;
- } else {
- if (rbDefinition.isConsiderSuperclass()) {
- type = type.getSuperclass();
- } else {
- type = null;
- }
- }
+ // Check declaring class
+ boolean isValidClass = false;
+ ITypeBinding type = init.resolveMethodBinding()
+ .getDeclaringClass();
+ while (type != null) {
+ if (type.getQualifiedName().equals(
+ rbDefinition.getDeclaringClass())) {
+ isValidClass = true;
+ break;
+ } else {
+ if (rbDefinition.isConsiderSuperclass()) {
+ type = type.getSuperclass();
+ } else {
+ type = null;
+ }
+ }
- }
- if (!isValidClass) {
- return null;
- }
+ }
+ if (!isValidClass) {
+ return null;
+ }
- boolean isValidMethod = false;
- for (String mn : rbDefinition.getMethodName()) {
- if (init.getName().getFullyQualifiedName().equals(mn)) {
- isValidMethod = true;
- break;
- }
- }
- if (!isValidMethod) {
- return null;
- }
+ boolean isValidMethod = false;
+ for (String mn : rbDefinition.getMethodName()) {
+ if (init.getName().getFullyQualifiedName().equals(mn)) {
+ isValidMethod = true;
+ break;
+ }
+ }
+ if (!isValidMethod) {
+ return null;
+ }
- // retrieve bundlename
- if (init.arguments().size() < rbDefinition.getPosition() + 1) {
- return null;
- }
+ // retrieve bundlename
+ if (init.arguments().size() < rbDefinition.getPosition() + 1) {
+ return null;
+ }
- bundleName = ((StringLiteral) init.arguments().get(
- rbDefinition.getPosition())).getLiteralValue();
- }
- }
+ bundleName = ((StringLiteral) init.arguments().get(
+ rbDefinition.getPosition())).getLiteralValue();
+ }
+ }
- return bundleName;
+ return bundleName;
}
public static SLLocation resolveResourceBundleLocation(
- MethodInvocation methodInvocation,
- MethodParameterDescriptor rbDefinition,
- Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) {
- SLLocation bundleDesc = null;
+ MethodInvocation methodInvocation,
+ MethodParameterDescriptor rbDefinition,
+ Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) {
+ SLLocation bundleDesc = null;
- if (methodInvocation.getExpression() instanceof SimpleName) {
- SimpleName vName = (SimpleName) methodInvocation.getExpression();
- IVariableBinding vBinding = (IVariableBinding) vName
- .resolveBinding();
- VariableDeclarationFragment dec = variableBindingManagers
- .get(vBinding);
+ if (methodInvocation.getExpression() instanceof SimpleName) {
+ SimpleName vName = (SimpleName) methodInvocation.getExpression();
+ IVariableBinding vBinding = (IVariableBinding) vName
+ .resolveBinding();
+ VariableDeclarationFragment dec = variableBindingManagers
+ .get(vBinding);
- if (dec.getInitializer() instanceof MethodInvocation) {
- MethodInvocation init = (MethodInvocation) dec.getInitializer();
+ if (dec.getInitializer() instanceof MethodInvocation) {
+ MethodInvocation init = (MethodInvocation) dec.getInitializer();
- // Check declaring class
- boolean isValidClass = false;
- ITypeBinding type = init.resolveMethodBinding()
- .getDeclaringClass();
- while (type != null) {
- if (type.getQualifiedName().equals(
- rbDefinition.getDeclaringClass())) {
- isValidClass = true;
- break;
- } else {
- if (rbDefinition.isConsiderSuperclass()) {
- type = type.getSuperclass();
- } else {
- type = null;
- }
- }
+ // Check declaring class
+ boolean isValidClass = false;
+ ITypeBinding type = init.resolveMethodBinding()
+ .getDeclaringClass();
+ while (type != null) {
+ if (type.getQualifiedName().equals(
+ rbDefinition.getDeclaringClass())) {
+ isValidClass = true;
+ break;
+ } else {
+ if (rbDefinition.isConsiderSuperclass()) {
+ type = type.getSuperclass();
+ } else {
+ type = null;
+ }
+ }
- }
- if (!isValidClass) {
- return null;
- }
+ }
+ if (!isValidClass) {
+ return null;
+ }
- boolean isValidMethod = false;
- for (String mn : rbDefinition.getMethodName()) {
- if (init.getName().getFullyQualifiedName().equals(mn)) {
- isValidMethod = true;
- break;
- }
- }
- if (!isValidMethod) {
- return null;
- }
+ boolean isValidMethod = false;
+ for (String mn : rbDefinition.getMethodName()) {
+ if (init.getName().getFullyQualifiedName().equals(mn)) {
+ isValidMethod = true;
+ break;
+ }
+ }
+ if (!isValidMethod) {
+ return null;
+ }
- // retrieve bundlename
- if (init.arguments().size() < rbDefinition.getPosition() + 1) {
- return null;
- }
+ // retrieve bundlename
+ if (init.arguments().size() < rbDefinition.getPosition() + 1) {
+ return null;
+ }
- StringLiteral bundleLiteral = ((StringLiteral) init.arguments()
- .get(rbDefinition.getPosition()));
- bundleDesc = new SLLocation(null,
- bundleLiteral.getStartPosition(),
- bundleLiteral.getLength()
- + bundleLiteral.getStartPosition(),
- bundleLiteral.getLiteralValue());
- }
- }
+ StringLiteral bundleLiteral = ((StringLiteral) init.arguments()
+ .get(rbDefinition.getPosition()));
+ bundleDesc = new SLLocation(null,
+ bundleLiteral.getStartPosition(),
+ bundleLiteral.getLength()
+ + bundleLiteral.getStartPosition(),
+ bundleLiteral.getLiteralValue());
+ }
+ }
- return bundleDesc;
+ return bundleDesc;
}
private static boolean isMatchingMethodDescriptor(
- MethodInvocation methodInvocation, MethodParameterDescriptor desc) {
- boolean result = false;
+ MethodInvocation methodInvocation, MethodParameterDescriptor desc) {
+ boolean result = false;
- if (methodInvocation.resolveMethodBinding() == null) {
- return false;
- }
+ if (methodInvocation.resolveMethodBinding() == null) {
+ return false;
+ }
- String methodName = methodInvocation.resolveMethodBinding().getName();
+ String methodName = methodInvocation.resolveMethodBinding().getName();
- // Check declaring class
- ITypeBinding type = methodInvocation.resolveMethodBinding()
- .getDeclaringClass();
- while (type != null) {
- if (type.getQualifiedName().equals(desc.getDeclaringClass())) {
- result = true;
- break;
- } else {
- if (desc.isConsiderSuperclass()) {
- type = type.getSuperclass();
- } else {
- type = null;
- }
- }
+ // Check declaring class
+ ITypeBinding type = methodInvocation.resolveMethodBinding()
+ .getDeclaringClass();
+ while (type != null) {
+ if (type.getQualifiedName().equals(desc.getDeclaringClass())) {
+ result = true;
+ break;
+ } else {
+ if (desc.isConsiderSuperclass()) {
+ type = type.getSuperclass();
+ } else {
+ type = null;
+ }
+ }
- }
+ }
- if (!result) {
- return false;
- }
+ if (!result) {
+ return false;
+ }
- result = !result;
+ result = !result;
- // Check method name
- for (String method : desc.getMethodName()) {
- if (method.equals(methodName)) {
- result = true;
- break;
- }
- }
+ // Check method name
+ for (String method : desc.getMethodName()) {
+ if (method.equals(methodName)) {
+ result = true;
+ break;
+ }
+ }
- return result;
+ return result;
}
public static boolean isMatchingMethodParamDesc(
- MethodInvocation methodInvocation, String literal,
- MethodParameterDescriptor desc) {
- boolean result = isMatchingMethodDescriptor(methodInvocation, desc);
+ MethodInvocation methodInvocation, String literal,
+ MethodParameterDescriptor desc) {
+ boolean result = isMatchingMethodDescriptor(methodInvocation, desc);
- if (!result) {
- return false;
- } else {
- result = false;
- }
+ if (!result) {
+ return false;
+ } else {
+ result = false;
+ }
- if (methodInvocation.arguments().size() > desc.getPosition()) {
- if (methodInvocation.arguments().get(desc.getPosition()) instanceof StringLiteral) {
- StringLiteral sl = (StringLiteral) methodInvocation.arguments()
- .get(desc.getPosition());
- if (sl.getLiteralValue().trim().toLowerCase()
- .equals(literal.toLowerCase())) {
- result = true;
- }
- }
- }
+ if (methodInvocation.arguments().size() > desc.getPosition()) {
+ if (methodInvocation.arguments().get(desc.getPosition()) instanceof StringLiteral) {
+ StringLiteral sl = (StringLiteral) methodInvocation.arguments()
+ .get(desc.getPosition());
+ if (sl.getLiteralValue().trim().toLowerCase()
+ .equals(literal.toLowerCase())) {
+ result = true;
+ }
+ }
+ }
- return result;
+ return result;
}
public static boolean isMatchingMethodParamDesc(
- MethodInvocation methodInvocation, StringLiteral literal,
- MethodParameterDescriptor desc) {
- int keyParameter = desc.getPosition();
- boolean result = isMatchingMethodDescriptor(methodInvocation, desc);
+ MethodInvocation methodInvocation, StringLiteral literal,
+ MethodParameterDescriptor desc) {
+ int keyParameter = desc.getPosition();
+ boolean result = isMatchingMethodDescriptor(methodInvocation, desc);
- if (!result) {
- return false;
- }
+ if (!result) {
+ return false;
+ }
- // Check position within method call
- StructuralPropertyDescriptor spd = literal.getLocationInParent();
- if (spd.isChildListProperty()) {
- @SuppressWarnings("unchecked")
- List<ASTNode> arguments = (List<ASTNode>) methodInvocation
- .getStructuralProperty(spd);
- result = (arguments.size() > keyParameter && arguments
- .get(keyParameter) == literal);
- }
+ // Check position within method call
+ StructuralPropertyDescriptor spd = literal.getLocationInParent();
+ if (spd.isChildListProperty()) {
+ @SuppressWarnings("unchecked")
+ List<ASTNode> arguments = (List<ASTNode>) methodInvocation
+ .getStructuralProperty(spd);
+ result = (arguments.size() > keyParameter && arguments
+ .get(keyParameter) == literal);
+ }
- return result;
+ return result;
}
public static ICompilationUnit createCompilationUnit(IResource resource) {
- // Instantiate a new AST parser
- ASTParser parser = ASTParser.newParser(AST.JLS3);
- parser.setResolveBindings(true);
+ // Instantiate a new AST parser
+ ASTParser parser = ASTParser.newParser(AST.JLS3);
+ parser.setResolveBindings(true);
- ICompilationUnit cu = JavaCore.createCompilationUnitFrom(resource
- .getProject().getFile(resource.getRawLocation()));
+ ICompilationUnit cu = JavaCore.createCompilationUnitFrom(resource
+ .getProject().getFile(resource.getRawLocation()));
- return cu;
+ return cu;
}
public static CompilationUnit createCompilationUnit(IDocument document) {
- // Instantiate a new AST parser
- ASTParser parser = ASTParser.newParser(AST.JLS3);
- parser.setResolveBindings(true);
+ // Instantiate a new AST parser
+ ASTParser parser = ASTParser.newParser(AST.JLS3);
+ parser.setResolveBindings(true);
- parser.setSource(document.get().toCharArray());
- return (CompilationUnit) parser.createAST(null);
+ parser.setSource(document.get().toCharArray());
+ return (CompilationUnit) parser.createAST(null);
}
public static void createImport(IDocument doc, IResource resource,
- CompilationUnit cu, AST ast, ASTRewrite rewriter,
- String qualifiedClassName) throws CoreException,
- BadLocationException {
+ CompilationUnit cu, AST ast, ASTRewrite rewriter,
+ String qualifiedClassName) throws CoreException,
+ BadLocationException {
- ImportFinder impFinder = new ImportFinder(qualifiedClassName);
+ ImportFinder impFinder = new ImportFinder(qualifiedClassName);
- cu.accept(impFinder);
+ cu.accept(impFinder);
- if (!impFinder.isImportFound()) {
- // ITextFileBufferManager bufferManager =
- // FileBuffers.getTextFileBufferManager();
- // IPath path = resource.getFullPath();
- //
- // bufferManager.connect(path, LocationKind.IFILE, null);
- // ITextFileBuffer textFileBuffer =
- // bufferManager.getTextFileBuffer(doc);
+ if (!impFinder.isImportFound()) {
+ // ITextFileBufferManager bufferManager =
+ // FileBuffers.getTextFileBufferManager();
+ // IPath path = resource.getFullPath();
+ //
+ // bufferManager.connect(path, LocationKind.IFILE, null);
+ // ITextFileBuffer textFileBuffer =
+ // bufferManager.getTextFileBuffer(doc);
- // TODO create new import
- ImportDeclaration id = ast.newImportDeclaration();
- id.setName(ast.newName(qualifiedClassName.split("\\.")));
- id.setStatic(false);
+ // TODO create new import
+ ImportDeclaration id = ast.newImportDeclaration();
+ id.setName(ast.newName(qualifiedClassName.split("\\.")));
+ id.setStatic(false);
- ListRewrite lrw = rewriter.getListRewrite(cu,
- CompilationUnit.IMPORTS_PROPERTY);
- lrw.insertFirst(id, null);
+ ListRewrite lrw = rewriter.getListRewrite(cu,
+ CompilationUnit.IMPORTS_PROPERTY);
+ lrw.insertFirst(id, null);
- // TextEdit te = rewriter.rewriteAST(doc, null);
- // te.apply(doc);
- //
- // if (textFileBuffer != null)
- // textFileBuffer.commit(null, false);
- // else
- // FileUtils.saveTextFile(resource.getProject().getFile(resource.getProjectRelativePath()),
- // doc.get());
- // bufferManager.disconnect(path, LocationKind.IFILE, null);
- }
+ // TextEdit te = rewriter.rewriteAST(doc, null);
+ // te.apply(doc);
+ //
+ // if (textFileBuffer != null)
+ // textFileBuffer.commit(null, false);
+ // else
+ // FileUtils.saveTextFile(resource.getProject().getFile(resource.getProjectRelativePath()),
+ // doc.get());
+ // bufferManager.disconnect(path, LocationKind.IFILE, null);
+ }
}
public static void createReplaceNonInternationalisationComment(
- CompilationUnit cu, IDocument doc, int position) {
- int i = findNonInternationalisationPosition(cu, doc, position);
+ CompilationUnit cu, IDocument doc, int position) {
+ int i = findNonInternationalisationPosition(cu, doc, position);
- IRegion reg;
- try {
- reg = doc.getLineInformationOfOffset(position);
- doc.replace(reg.getOffset() + reg.getLength(), 0, " //$NON-NLS-"
- + i + "$");
- } catch (BadLocationException e) {
- Logger.logError(e);
- }
+ IRegion reg;
+ try {
+ reg = doc.getLineInformationOfOffset(position);
+ doc.replace(reg.getOffset() + reg.getLength(), 0, " //$NON-NLS-"
+ + i + "$");
+ } catch (BadLocationException e) {
+ Logger.logError(e);
+ }
}
// TODO export initializer specification into a methodinvocationdefinition
@SuppressWarnings("unchecked")
public static void createResourceBundleReference(IResource resource,
- int typePos, IDocument doc, String bundleId, Locale locale,
- boolean globalReference, String variableName, CompilationUnit cu) {
+ int typePos, IDocument doc, String bundleId, Locale locale,
+ boolean globalReference, String variableName, CompilationUnit cu) {
- try {
+ try {
- if (globalReference) {
+ if (globalReference) {
- // retrieve compilation unit from document
- PositionalTypeFinder typeFinder = new PositionalTypeFinder(
- typePos);
- cu.accept(typeFinder);
- ASTNode node = typeFinder.getEnclosingType();
- ASTNode anonymNode = typeFinder.getEnclosingAnonymType();
- if (anonymNode != null) {
- node = anonymNode;
- }
+ // retrieve compilation unit from document
+ PositionalTypeFinder typeFinder = new PositionalTypeFinder(
+ typePos);
+ cu.accept(typeFinder);
+ ASTNode node = typeFinder.getEnclosingType();
+ ASTNode anonymNode = typeFinder.getEnclosingAnonymType();
+ if (anonymNode != null) {
+ node = anonymNode;
+ }
- MethodDeclaration meth = typeFinder.getEnclosingMethod();
- AST ast = node.getAST();
+ MethodDeclaration meth = typeFinder.getEnclosingMethod();
+ AST ast = node.getAST();
- VariableDeclarationFragment vdf = ast
- .newVariableDeclarationFragment();
- vdf.setName(ast.newSimpleName(variableName));
+ VariableDeclarationFragment vdf = ast
+ .newVariableDeclarationFragment();
+ vdf.setName(ast.newSimpleName(variableName));
- // set initializer
- vdf.setInitializer(createResourceBundleGetter(ast, bundleId,
- locale));
+ // set initializer
+ vdf.setInitializer(createResourceBundleGetter(ast, bundleId,
+ locale));
- FieldDeclaration fd = ast.newFieldDeclaration(vdf);
- fd.setType(ast.newSimpleType(ast
- .newName(new String[] { "ResourceBundle" })));
+ FieldDeclaration fd = ast.newFieldDeclaration(vdf);
+ fd.setType(ast.newSimpleType(ast
+ .newName(new String[] { "ResourceBundle" })));
- if (meth != null
- && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC) {
- fd.modifiers().addAll(ast.newModifiers(Modifier.STATIC));
- }
+ if (meth != null
+ && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC) {
+ fd.modifiers().addAll(ast.newModifiers(Modifier.STATIC));
+ }
- // rewrite AST
- ASTRewrite rewriter = ASTRewrite.create(ast);
- ListRewrite lrw = rewriter
- .getListRewrite(
- node,
- node instanceof TypeDeclaration ? TypeDeclaration.BODY_DECLARATIONS_PROPERTY
- : AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
- lrw.insertAt(fd, /*
- * findIndexOfLastField(node.bodyDeclarations())
- * +1
- */
- 0, null);
+ // rewrite AST
+ ASTRewrite rewriter = ASTRewrite.create(ast);
+ ListRewrite lrw = rewriter
+ .getListRewrite(
+ node,
+ node instanceof TypeDeclaration ? TypeDeclaration.BODY_DECLARATIONS_PROPERTY
+ : AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
+ lrw.insertAt(fd, /*
+ * findIndexOfLastField(node.bodyDeclarations())
+ * +1
+ */
+ 0, null);
- // create import if required
- createImport(doc, resource, cu, ast, rewriter,
- getRBDefinitionDesc().getDeclaringClass());
+ // create import if required
+ createImport(doc, resource, cu, ast, rewriter,
+ getRBDefinitionDesc().getDeclaringClass());
- TextEdit te = rewriter.rewriteAST(doc, null);
- te.apply(doc);
- } else {
+ TextEdit te = rewriter.rewriteAST(doc, null);
+ te.apply(doc);
+ } else {
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
}
@SuppressWarnings("unchecked")
protected static MethodInvocation createResourceBundleGetter(AST ast,
- String bundleId, Locale locale) {
- MethodInvocation mi = ast.newMethodInvocation();
+ String bundleId, Locale locale) {
+ MethodInvocation mi = ast.newMethodInvocation();
- mi.setName(ast.newSimpleName("getBundle"));
- mi.setExpression(ast.newName(new String[] { "ResourceBundle" }));
+ mi.setName(ast.newSimpleName("getBundle"));
+ mi.setExpression(ast.newName(new String[] { "ResourceBundle" }));
- // Add bundle argument
- StringLiteral sl = ast.newStringLiteral();
- sl.setLiteralValue(bundleId);
- mi.arguments().add(sl);
+ // Add bundle argument
+ StringLiteral sl = ast.newStringLiteral();
+ sl.setLiteralValue(bundleId);
+ mi.arguments().add(sl);
- // TODO Add Locale argument
+ // TODO Add Locale argument
- return mi;
+ return mi;
}
public static ASTNode getEnclosingType(CompilationUnit cu, int pos) {
- PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos);
- cu.accept(typeFinder);
- return (typeFinder.getEnclosingAnonymType() != null) ? typeFinder
- .getEnclosingAnonymType() : typeFinder.getEnclosingType();
+ PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos);
+ cu.accept(typeFinder);
+ return (typeFinder.getEnclosingAnonymType() != null) ? typeFinder
+ .getEnclosingAnonymType() : typeFinder.getEnclosingType();
}
public static ASTNode getEnclosingType(ASTNode cu, int pos) {
- PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos);
- cu.accept(typeFinder);
- return (typeFinder.getEnclosingAnonymType() != null) ? typeFinder
- .getEnclosingAnonymType() : typeFinder.getEnclosingType();
+ PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos);
+ cu.accept(typeFinder);
+ return (typeFinder.getEnclosingAnonymType() != null) ? typeFinder
+ .getEnclosingAnonymType() : typeFinder.getEnclosingType();
}
@SuppressWarnings("unchecked")
protected static MethodInvocation referenceResource(AST ast,
- String accessorName, String key, Locale locale) {
- MethodParameterDescriptor accessorDesc = getRBAccessorDesc();
- MethodInvocation mi = ast.newMethodInvocation();
+ String accessorName, String key, Locale locale) {
+ MethodParameterDescriptor accessorDesc = getRBAccessorDesc();
+ MethodInvocation mi = ast.newMethodInvocation();
- mi.setName(ast.newSimpleName(accessorDesc.getMethodName().get(0)));
+ mi.setName(ast.newSimpleName(accessorDesc.getMethodName().get(0)));
- // Declare expression
- StringLiteral sl = ast.newStringLiteral();
- sl.setLiteralValue(key);
+ // Declare expression
+ StringLiteral sl = ast.newStringLiteral();
+ sl.setLiteralValue(key);
- // TODO define locale expression
- if (mi.arguments().size() == accessorDesc.getPosition()) {
- mi.arguments().add(sl);
- }
+ // TODO define locale expression
+ if (mi.arguments().size() == accessorDesc.getPosition()) {
+ mi.arguments().add(sl);
+ }
- SimpleName name = ast.newSimpleName(accessorName);
- mi.setExpression(name);
+ SimpleName name = ast.newSimpleName(accessorName);
+ mi.setExpression(name);
- return mi;
+ return mi;
}
public static String createResourceReference(String bundleId, String key,
- Locale locale, IResource resource, int typePos,
- String accessorName, IDocument doc, CompilationUnit cu) {
+ Locale locale, IResource resource, int typePos,
+ String accessorName, IDocument doc, CompilationUnit cu) {
- PositionalTypeFinder typeFinder = new PositionalTypeFinder(typePos);
- cu.accept(typeFinder);
- AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType();
- TypeDeclaration td = typeFinder.getEnclosingType();
+ PositionalTypeFinder typeFinder = new PositionalTypeFinder(typePos);
+ cu.accept(typeFinder);
+ AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType();
+ TypeDeclaration td = typeFinder.getEnclosingType();
- // retrieve compilation unit from document
- ASTNode node = atd == null ? td : atd;
- AST ast = node.getAST();
+ // retrieve compilation unit from document
+ ASTNode node = atd == null ? td : atd;
+ AST ast = node.getAST();
- ExpressionStatement expressionStatement = ast
- .newExpressionStatement(referenceResource(ast, accessorName,
- key, locale));
+ ExpressionStatement expressionStatement = ast
+ .newExpressionStatement(referenceResource(ast, accessorName,
+ key, locale));
- String exp = expressionStatement.toString();
+ String exp = expressionStatement.toString();
- // remove semicolon and line break at the end of this expression
- // statement
- if (exp.endsWith(";\n")) {
- exp = exp.substring(0, exp.length() - 2);
- }
+ // remove semicolon and line break at the end of this expression
+ // statement
+ if (exp.endsWith(";\n")) {
+ exp = exp.substring(0, exp.length() - 2);
+ }
- return exp;
+ return exp;
}
private static int findNonInternationalisationPosition(CompilationUnit cu,
- IDocument doc, int offset) {
- LinePreStringsFinder lsfinder = null;
- try {
- lsfinder = new LinePreStringsFinder(offset, doc);
- cu.accept(lsfinder);
- } catch (BadLocationException e) {
- Logger.logError(e);
- }
- if (lsfinder == null) {
- return 1;
- }
+ IDocument doc, int offset) {
+ LinePreStringsFinder lsfinder = null;
+ try {
+ lsfinder = new LinePreStringsFinder(offset, doc);
+ cu.accept(lsfinder);
+ } catch (BadLocationException e) {
+ Logger.logError(e);
+ }
+ if (lsfinder == null) {
+ return 1;
+ }
- List<StringLiteral> strings = lsfinder.getStrings();
+ List<StringLiteral> strings = lsfinder.getStrings();
- return strings.size() + 1;
+ return strings.size() + 1;
}
public static boolean existsNonInternationalisationComment(
- StringLiteral literal) throws BadLocationException {
- CompilationUnit cu = (CompilationUnit) literal.getRoot();
- ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement();
+ StringLiteral literal) throws BadLocationException {
+ CompilationUnit cu = (CompilationUnit) literal.getRoot();
+ ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement();
- IDocument doc = null;
- try {
- doc = new Document(icu.getSource());
- } catch (JavaModelException e) {
- Logger.logError(e);
- }
+ IDocument doc = null;
+ try {
+ doc = new Document(icu.getSource());
+ } catch (JavaModelException e) {
+ Logger.logError(e);
+ }
- // get whole line in which string literal
- int lineNo = doc.getLineOfOffset(literal.getStartPosition());
- int lineOffset = doc.getLineOffset(lineNo);
- int lineLength = doc.getLineLength(lineNo);
- String lineOfString = doc.get(lineOffset, lineLength);
+ // get whole line in which string literal
+ int lineNo = doc.getLineOfOffset(literal.getStartPosition());
+ int lineOffset = doc.getLineOffset(lineNo);
+ int lineLength = doc.getLineLength(lineNo);
+ String lineOfString = doc.get(lineOffset, lineLength);
- // search for a line comment in this line
- int indexComment = lineOfString.indexOf("//");
+ // search for a line comment in this line
+ int indexComment = lineOfString.indexOf("//");
- if (indexComment == -1) {
- return false;
- }
+ if (indexComment == -1) {
+ return false;
+ }
- String comment = lineOfString.substring(indexComment);
+ String comment = lineOfString.substring(indexComment);
- // remove first "//" of line comment
- comment = comment.substring(2).toLowerCase();
+ // remove first "//" of line comment
+ comment = comment.substring(2).toLowerCase();
- // split line comments, necessary if more NON-NLS comments exist in one line, eg.: $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3
- String[] comments = comment.split("//");
+ // split line comments, necessary if more NON-NLS comments exist in one line, eg.: $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3
+ String[] comments = comment.split("//");
- for (String commentFrag : comments) {
- commentFrag = commentFrag.trim();
+ for (String commentFrag : comments) {
+ commentFrag = commentFrag.trim();
- // if comment match format: "$non-nls$" then ignore whole line
- if (commentFrag.matches("^\\$non-nls\\$$")) {
- return true;
+ // if comment match format: "$non-nls$" then ignore whole line
+ if (commentFrag.matches("^\\$non-nls\\$$")) {
+ return true;
- // if comment match format: "$non-nls-{number}$" then only
- // ignore string which is on given position
- } else if (commentFrag.matches("^\\$non-nls-\\d+\\$$")) {
- int iString = findNonInternationalisationPosition(cu, doc,
- literal.getStartPosition());
- int iComment = new Integer(commentFrag.substring(9, 10));
- if (iString == iComment) {
- return true;
- }
- }
- }
- return false;
+ // if comment match format: "$non-nls-{number}$" then only
+ // ignore string which is on given position
+ } else if (commentFrag.matches("^\\$non-nls-\\d+\\$$")) {
+ int iString = findNonInternationalisationPosition(cu, doc,
+ literal.getStartPosition());
+ int iComment = new Integer(commentFrag.substring(9, 10));
+ if (iString == iComment) {
+ return true;
+ }
+ }
+ }
+ return false;
}
public static StringLiteral getStringLiteralAtPos(CompilationUnit cu,
- int position) {
- StringLiteralFinder strFinder = new StringLiteralFinder(position);
- cu.accept(strFinder);
- return strFinder.getStringLiteral();
+ int position) {
+ StringLiteralFinder strFinder = new StringLiteralFinder(position);
+ cu.accept(strFinder);
+ return strFinder.getStringLiteral();
}
static class PositionalTypeFinder extends ASTVisitor {
- private int position;
- private TypeDeclaration enclosingType;
- private AnonymousClassDeclaration enclosingAnonymType;
- private MethodDeclaration enclosingMethod;
+ private int position;
+ private TypeDeclaration enclosingType;
+ private AnonymousClassDeclaration enclosingAnonymType;
+ private MethodDeclaration enclosingMethod;
- public PositionalTypeFinder(int pos) {
- position = pos;
- }
+ public PositionalTypeFinder(int pos) {
+ position = pos;
+ }
- public TypeDeclaration getEnclosingType() {
- return enclosingType;
- }
+ public TypeDeclaration getEnclosingType() {
+ return enclosingType;
+ }
- public AnonymousClassDeclaration getEnclosingAnonymType() {
- return enclosingAnonymType;
- }
+ public AnonymousClassDeclaration getEnclosingAnonymType() {
+ return enclosingAnonymType;
+ }
- public MethodDeclaration getEnclosingMethod() {
- return enclosingMethod;
- }
+ public MethodDeclaration getEnclosingMethod() {
+ return enclosingMethod;
+ }
- @Override
- public boolean visit(MethodDeclaration node) {
- if (position >= node.getStartPosition()
- && position <= (node.getStartPosition() + node.getLength())) {
- enclosingMethod = node;
- return true;
- } else {
- return false;
- }
- }
+ @Override
+ public boolean visit(MethodDeclaration node) {
+ if (position >= node.getStartPosition()
+ && position <= (node.getStartPosition() + node.getLength())) {
+ enclosingMethod = node;
+ return true;
+ } else {
+ return false;
+ }
+ }
- @Override
- public boolean visit(TypeDeclaration node) {
- if (position >= node.getStartPosition()
- && position <= (node.getStartPosition() + node.getLength())) {
- enclosingType = node;
- return true;
- } else {
- return false;
- }
- }
+ @Override
+ public boolean visit(TypeDeclaration node) {
+ if (position >= node.getStartPosition()
+ && position <= (node.getStartPosition() + node.getLength())) {
+ enclosingType = node;
+ return true;
+ } else {
+ return false;
+ }
+ }
- @Override
- public boolean visit(AnonymousClassDeclaration node) {
- if (position >= node.getStartPosition()
- && position <= (node.getStartPosition() + node.getLength())) {
- enclosingAnonymType = node;
- return true;
- } else {
- return false;
- }
- }
+ @Override
+ public boolean visit(AnonymousClassDeclaration node) {
+ if (position >= node.getStartPosition()
+ && position <= (node.getStartPosition() + node.getLength())) {
+ enclosingAnonymType = node;
+ return true;
+ } else {
+ return false;
+ }
+ }
}
static class ImportFinder extends ASTVisitor {
- String qName;
- boolean importFound = false;
+ String qName;
+ boolean importFound = false;
- public ImportFinder(String qName) {
- this.qName = qName;
- }
+ public ImportFinder(String qName) {
+ this.qName = qName;
+ }
- public boolean isImportFound() {
- return importFound;
- }
+ public boolean isImportFound() {
+ return importFound;
+ }
- @Override
- public boolean visit(ImportDeclaration id) {
- if (id.getName().getFullyQualifiedName().equals(qName)) {
- importFound = true;
- }
+ @Override
+ public boolean visit(ImportDeclaration id) {
+ if (id.getName().getFullyQualifiedName().equals(qName)) {
+ importFound = true;
+ }
- return true;
- }
+ return true;
+ }
}
static class VariableFinder extends ASTVisitor {
- boolean found = false;
- String variableName;
+ boolean found = false;
+ String variableName;
- public boolean isVariableFound() {
- return found;
- }
+ public boolean isVariableFound() {
+ return found;
+ }
- public VariableFinder(String variableName) {
- this.variableName = variableName;
- }
+ public VariableFinder(String variableName) {
+ this.variableName = variableName;
+ }
- @Override
- public boolean visit(VariableDeclarationFragment vdf) {
- if (vdf.getName().getFullyQualifiedName().equals(variableName)) {
- found = true;
- return false;
- }
+ @Override
+ public boolean visit(VariableDeclarationFragment vdf) {
+ if (vdf.getName().getFullyQualifiedName().equals(variableName)) {
+ found = true;
+ return false;
+ }
- return true;
- }
+ return true;
+ }
}
static class InMethodBundleDeclFinder extends ASTVisitor {
- String varName;
- String bundleId;
- int pos;
+ String varName;
+ String bundleId;
+ int pos;
- public InMethodBundleDeclFinder(String bundleId, int pos) {
- this.bundleId = bundleId;
- this.pos = pos;
- }
+ public InMethodBundleDeclFinder(String bundleId, int pos) {
+ this.bundleId = bundleId;
+ this.pos = pos;
+ }
- public String getVariableName() {
- return varName;
- }
+ public String getVariableName() {
+ return varName;
+ }
- @Override
- public boolean visit(VariableDeclarationFragment fdvd) {
- if (fdvd.getStartPosition() > pos) {
- return false;
- }
+ @Override
+ public boolean visit(VariableDeclarationFragment fdvd) {
+ if (fdvd.getStartPosition() > pos) {
+ return false;
+ }
- // boolean bStatic = (fdvd.resolveBinding().getModifiers() &
- // Modifier.STATIC) == Modifier.STATIC;
- // if (!bStatic && isStatic)
- // return true;
+ // boolean bStatic = (fdvd.resolveBinding().getModifiers() &
+ // Modifier.STATIC) == Modifier.STATIC;
+ // if (!bStatic && isStatic)
+ // return true;
- String tmpVarName = fdvd.getName().getFullyQualifiedName();
+ String tmpVarName = fdvd.getName().getFullyQualifiedName();
- if (fdvd.getInitializer() instanceof MethodInvocation) {
- MethodInvocation fdi = (MethodInvocation) fdvd.getInitializer();
- if (isMatchingMethodParamDesc(fdi, bundleId,
- getRBDefinitionDesc())) {
- varName = tmpVarName;
- }
- }
- return true;
- }
+ if (fdvd.getInitializer() instanceof MethodInvocation) {
+ MethodInvocation fdi = (MethodInvocation) fdvd.getInitializer();
+ if (isMatchingMethodParamDesc(fdi, bundleId,
+ getRBDefinitionDesc())) {
+ varName = tmpVarName;
+ }
+ }
+ return true;
+ }
}
static class BundleDeclarationFinder extends ASTVisitor {
- String varName;
- String bundleId;
- ASTNode typeDef;
- boolean isStatic;
+ String varName;
+ String bundleId;
+ ASTNode typeDef;
+ boolean isStatic;
- public BundleDeclarationFinder(String bundleId, ASTNode td,
- boolean isStatic) {
- this.bundleId = bundleId;
- this.typeDef = td;
- this.isStatic = isStatic;
- }
+ public BundleDeclarationFinder(String bundleId, ASTNode td,
+ boolean isStatic) {
+ this.bundleId = bundleId;
+ this.typeDef = td;
+ this.isStatic = isStatic;
+ }
- public String getVariableName() {
- return varName;
- }
+ public String getVariableName() {
+ return varName;
+ }
- @Override
- public boolean visit(MethodDeclaration md) {
- return true;
- }
+ @Override
+ public boolean visit(MethodDeclaration md) {
+ return true;
+ }
- @Override
- public boolean visit(FieldDeclaration fd) {
- if (getEnclosingType(typeDef, fd.getStartPosition()) != typeDef) {
- return false;
- }
+ @Override
+ public boolean visit(FieldDeclaration fd) {
+ if (getEnclosingType(typeDef, fd.getStartPosition()) != typeDef) {
+ return false;
+ }
- boolean bStatic = (fd.getModifiers() & Modifier.STATIC) == Modifier.STATIC;
- if (!bStatic && isStatic) {
- return true;
- }
+ boolean bStatic = (fd.getModifiers() & Modifier.STATIC) == Modifier.STATIC;
+ if (!bStatic && isStatic) {
+ return true;
+ }
- if (fd.getType() instanceof SimpleType) {
- SimpleType fdType = (SimpleType) fd.getType();
- String typeName = fdType.getName().getFullyQualifiedName();
- String referenceName = getRBDefinitionDesc()
- .getDeclaringClass();
- if (typeName.equals(referenceName)
- || (referenceName.lastIndexOf(".") >= 0 && typeName
- .equals(referenceName.substring(referenceName
- .lastIndexOf(".") + 1)))) {
- // Check VariableDeclarationFragment
- if (fd.fragments().size() == 1) {
- if (fd.fragments().get(0) instanceof VariableDeclarationFragment) {
- VariableDeclarationFragment fdvd = (VariableDeclarationFragment) fd
- .fragments().get(0);
- String tmpVarName = fdvd.getName()
- .getFullyQualifiedName();
+ if (fd.getType() instanceof SimpleType) {
+ SimpleType fdType = (SimpleType) fd.getType();
+ String typeName = fdType.getName().getFullyQualifiedName();
+ String referenceName = getRBDefinitionDesc()
+ .getDeclaringClass();
+ if (typeName.equals(referenceName)
+ || (referenceName.lastIndexOf(".") >= 0 && typeName
+ .equals(referenceName.substring(referenceName
+ .lastIndexOf(".") + 1)))) {
+ // Check VariableDeclarationFragment
+ if (fd.fragments().size() == 1) {
+ if (fd.fragments().get(0) instanceof VariableDeclarationFragment) {
+ VariableDeclarationFragment fdvd = (VariableDeclarationFragment) fd
+ .fragments().get(0);
+ String tmpVarName = fdvd.getName()
+ .getFullyQualifiedName();
- if (fdvd.getInitializer() instanceof MethodInvocation) {
- MethodInvocation fdi = (MethodInvocation) fdvd
- .getInitializer();
- if (isMatchingMethodParamDesc(fdi, bundleId,
- getRBDefinitionDesc())) {
- varName = tmpVarName;
- }
- }
- }
- }
- }
- }
- return false;
- }
+ if (fdvd.getInitializer() instanceof MethodInvocation) {
+ MethodInvocation fdi = (MethodInvocation) fdvd
+ .getInitializer();
+ if (isMatchingMethodParamDesc(fdi, bundleId,
+ getRBDefinitionDesc())) {
+ varName = tmpVarName;
+ }
+ }
+ }
+ }
+ }
+ }
+ return false;
+ }
}
static class LinePreStringsFinder extends ASTVisitor {
- private int position;
- private int line;
- private List<StringLiteral> strings;
- private IDocument document;
+ private int position;
+ private int line;
+ private List<StringLiteral> strings;
+ private IDocument document;
- public LinePreStringsFinder(int position, IDocument document)
- throws BadLocationException {
- this.document = document;
- this.position = position;
- line = document.getLineOfOffset(position);
- strings = new ArrayList<StringLiteral>();
- }
+ public LinePreStringsFinder(int position, IDocument document)
+ throws BadLocationException {
+ this.document = document;
+ this.position = position;
+ line = document.getLineOfOffset(position);
+ strings = new ArrayList<StringLiteral>();
+ }
- public List<StringLiteral> getStrings() {
- return strings;
- }
+ public List<StringLiteral> getStrings() {
+ return strings;
+ }
- @Override
- public boolean visit(StringLiteral node) {
- try {
- if (line == document.getLineOfOffset(node.getStartPosition())
- && node.getStartPosition() < position) {
- strings.add(node);
- return true;
- }
- } catch (BadLocationException e) {
- }
- return true;
- }
+ @Override
+ public boolean visit(StringLiteral node) {
+ try {
+ if (line == document.getLineOfOffset(node.getStartPosition())
+ && node.getStartPosition() < position) {
+ strings.add(node);
+ return true;
+ }
+ } catch (BadLocationException e) {
+ }
+ return true;
+ }
}
static class StringLiteralFinder extends ASTVisitor {
- private int position;
- private StringLiteral string;
+ private int position;
+ private StringLiteral string;
- public StringLiteralFinder(int position) {
- this.position = position;
- }
+ public StringLiteralFinder(int position) {
+ this.position = position;
+ }
- public StringLiteral getStringLiteral() {
- return string;
- }
+ public StringLiteral getStringLiteral() {
+ return string;
+ }
- @Override
- public boolean visit(StringLiteral node) {
- if (position > node.getStartPosition()
- && position < (node.getStartPosition() + node.getLength())) {
- string = node;
- }
- return true;
- }
+ @Override
+ public boolean visit(StringLiteral node) {
+ if (position > node.getStartPosition()
+ && position < (node.getStartPosition() + node.getLength())) {
+ string = node;
+ }
+ return true;
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/MethodParameterDescriptor.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/MethodParameterDescriptor.java
index 5cb23c1..34db602 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/MethodParameterDescriptor.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/MethodParameterDescriptor.java
@@ -20,44 +20,44 @@
private int position;
public MethodParameterDescriptor(List<String> methodName,
- String declaringClass, boolean considerSuperclass, int position) {
- super();
- this.setMethodName(methodName);
- this.declaringClass = declaringClass;
- this.considerSuperclass = considerSuperclass;
- this.position = position;
+ String declaringClass, boolean considerSuperclass, int position) {
+ super();
+ this.setMethodName(methodName);
+ this.declaringClass = declaringClass;
+ this.considerSuperclass = considerSuperclass;
+ this.position = position;
}
public String getDeclaringClass() {
- return declaringClass;
+ return declaringClass;
}
public void setDeclaringClass(String declaringClass) {
- this.declaringClass = declaringClass;
+ this.declaringClass = declaringClass;
}
public boolean isConsiderSuperclass() {
- return considerSuperclass;
+ return considerSuperclass;
}
public void setConsiderSuperclass(boolean considerSuperclass) {
- this.considerSuperclass = considerSuperclass;
+ this.considerSuperclass = considerSuperclass;
}
public int getPosition() {
- return position;
+ return position;
}
public void setPosition(int position) {
- this.position = position;
+ this.position = position;
}
public void setMethodName(List<String> methodName) {
- this.methodName = methodName;
+ this.methodName = methodName;
}
public List<String> getMethodName() {
- return methodName;
+ return methodName;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java
index 36ac051..e431fc8 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java
@@ -43,7 +43,7 @@
*
*/
public class ResourceAuditVisitor extends ASTVisitor implements
- IResourceVisitor {
+ IResourceVisitor {
private List<SLLocation> constants;
private List<SLLocation> brokenStrings;
@@ -57,205 +57,205 @@
private String projectName;
public ResourceAuditVisitor(IFile file, String projectName) {
- constants = new ArrayList<SLLocation>();
- brokenStrings = new ArrayList<SLLocation>();
- brokenRBReferences = new ArrayList<SLLocation>();
- this.file = file;
- this.projectName = projectName;
+ constants = new ArrayList<SLLocation>();
+ brokenStrings = new ArrayList<SLLocation>();
+ brokenRBReferences = new ArrayList<SLLocation>();
+ this.file = file;
+ this.projectName = projectName;
}
@SuppressWarnings("unchecked")
@Override
public boolean visit(VariableDeclarationStatement varDeclaration) {
- for (Iterator<VariableDeclarationFragment> itFrag = varDeclaration
- .fragments().iterator(); itFrag.hasNext();) {
- VariableDeclarationFragment fragment = itFrag.next();
- parseVariableDeclarationFragment(fragment);
- }
- return true;
+ for (Iterator<VariableDeclarationFragment> itFrag = varDeclaration
+ .fragments().iterator(); itFrag.hasNext();) {
+ VariableDeclarationFragment fragment = itFrag.next();
+ parseVariableDeclarationFragment(fragment);
+ }
+ return true;
}
@SuppressWarnings("unchecked")
@Override
public boolean visit(FieldDeclaration fieldDeclaration) {
- for (Iterator<VariableDeclarationFragment> itFrag = fieldDeclaration
- .fragments().iterator(); itFrag.hasNext();) {
- VariableDeclarationFragment fragment = itFrag.next();
- parseVariableDeclarationFragment(fragment);
- }
- return true;
+ for (Iterator<VariableDeclarationFragment> itFrag = fieldDeclaration
+ .fragments().iterator(); itFrag.hasNext();) {
+ VariableDeclarationFragment fragment = itFrag.next();
+ parseVariableDeclarationFragment(fragment);
+ }
+ return true;
}
protected void parseVariableDeclarationFragment(
- VariableDeclarationFragment fragment) {
- IVariableBinding vBinding = fragment.resolveBinding();
- this.variableBindingManagers.put(vBinding, fragment);
+ VariableDeclarationFragment fragment) {
+ IVariableBinding vBinding = fragment.resolveBinding();
+ this.variableBindingManagers.put(vBinding, fragment);
}
@Override
public boolean visit(StringLiteral stringLiteral) {
- try {
- ASTNode parent = stringLiteral.getParent();
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(projectName);
+ try {
+ ASTNode parent = stringLiteral.getParent();
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
- if (manager == null) {
- return false;
- }
+ if (manager == null) {
+ return false;
+ }
- if (parent instanceof MethodInvocation) {
- MethodInvocation methodInvocation = (MethodInvocation) parent;
+ if (parent instanceof MethodInvocation) {
+ MethodInvocation methodInvocation = (MethodInvocation) parent;
- IRegion region = new Region(stringLiteral.getStartPosition(),
- stringLiteral.getLength());
+ IRegion region = new Region(stringLiteral.getStartPosition(),
+ stringLiteral.getLength());
- // Check if this method invokes the getString-Method on a
- // ResourceBundle Implementation
- if (ASTutils.isMatchingMethodParamDesc(methodInvocation,
- stringLiteral, ASTutils.getRBAccessorDesc())) {
- // Check if the given Resource-Bundle reference is broken
- SLLocation rbName = ASTutils.resolveResourceBundleLocation(
- methodInvocation, ASTutils.getRBDefinitionDesc(),
- variableBindingManagers);
- if (rbName == null
- || manager.isKeyBroken(rbName.getLiteral(),
- stringLiteral.getLiteralValue())) {
- // report new problem
- SLLocation desc = new SLLocation(file,
- stringLiteral.getStartPosition(),
- stringLiteral.getStartPosition()
- + stringLiteral.getLength(),
- stringLiteral.getLiteralValue());
- desc.setData(rbName);
- brokenStrings.add(desc);
- }
+ // Check if this method invokes the getString-Method on a
+ // ResourceBundle Implementation
+ if (ASTutils.isMatchingMethodParamDesc(methodInvocation,
+ stringLiteral, ASTutils.getRBAccessorDesc())) {
+ // Check if the given Resource-Bundle reference is broken
+ SLLocation rbName = ASTutils.resolveResourceBundleLocation(
+ methodInvocation, ASTutils.getRBDefinitionDesc(),
+ variableBindingManagers);
+ if (rbName == null
+ || manager.isKeyBroken(rbName.getLiteral(),
+ stringLiteral.getLiteralValue())) {
+ // report new problem
+ SLLocation desc = new SLLocation(file,
+ stringLiteral.getStartPosition(),
+ stringLiteral.getStartPosition()
+ + stringLiteral.getLength(),
+ stringLiteral.getLiteralValue());
+ desc.setData(rbName);
+ brokenStrings.add(desc);
+ }
- // store position of resource-bundle access
- keyPositions.put(
- Long.valueOf(stringLiteral.getStartPosition()),
- region);
- bundleKeys.put(region, stringLiteral.getLiteralValue());
- bundleReferences.put(region, rbName.getLiteral());
- return false;
- } else if (ASTutils.isMatchingMethodParamDesc(methodInvocation,
- stringLiteral, ASTutils.getRBDefinitionDesc())) {
- rbDefReferences.put(
- Long.valueOf(stringLiteral.getStartPosition()),
- region);
- boolean referenceBroken = true;
- for (String bundle : manager.getResourceBundleIdentifiers()) {
- if (bundle.trim().equals(
- stringLiteral.getLiteralValue())) {
- referenceBroken = false;
- }
- }
- if (referenceBroken) {
- this.brokenRBReferences.add(new SLLocation(file,
- stringLiteral.getStartPosition(), stringLiteral
- .getStartPosition()
- + stringLiteral.getLength(),
- stringLiteral.getLiteralValue()));
- }
+ // store position of resource-bundle access
+ keyPositions.put(
+ Long.valueOf(stringLiteral.getStartPosition()),
+ region);
+ bundleKeys.put(region, stringLiteral.getLiteralValue());
+ bundleReferences.put(region, rbName.getLiteral());
+ return false;
+ } else if (ASTutils.isMatchingMethodParamDesc(methodInvocation,
+ stringLiteral, ASTutils.getRBDefinitionDesc())) {
+ rbDefReferences.put(
+ Long.valueOf(stringLiteral.getStartPosition()),
+ region);
+ boolean referenceBroken = true;
+ for (String bundle : manager.getResourceBundleIdentifiers()) {
+ if (bundle.trim().equals(
+ stringLiteral.getLiteralValue())) {
+ referenceBroken = false;
+ }
+ }
+ if (referenceBroken) {
+ this.brokenRBReferences.add(new SLLocation(file,
+ stringLiteral.getStartPosition(), stringLiteral
+ .getStartPosition()
+ + stringLiteral.getLength(),
+ stringLiteral.getLiteralValue()));
+ }
- return false;
- }
- }
+ return false;
+ }
+ }
- // check if string is followed by a "$NON-NLS$" line comment
- if (ASTutils.existsNonInternationalisationComment(stringLiteral)) {
- return false;
- }
+ // check if string is followed by a "$NON-NLS$" line comment
+ if (ASTutils.existsNonInternationalisationComment(stringLiteral)) {
+ return false;
+ }
- // constant string literal found
- constants.add(new SLLocation(file,
- stringLiteral.getStartPosition(), stringLiteral
- .getStartPosition() + stringLiteral.getLength(),
- stringLiteral.getLiteralValue()));
- } catch (Exception e) {
- e.printStackTrace();
- }
- return false;
+ // constant string literal found
+ constants.add(new SLLocation(file,
+ stringLiteral.getStartPosition(), stringLiteral
+ .getStartPosition() + stringLiteral.getLength(),
+ stringLiteral.getLiteralValue()));
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return false;
}
public List<SLLocation> getConstantStringLiterals() {
- return constants;
+ return constants;
}
public List<SLLocation> getBrokenResourceReferences() {
- return brokenStrings;
+ return brokenStrings;
}
public List<SLLocation> getBrokenRBReferences() {
- return this.brokenRBReferences;
+ return this.brokenRBReferences;
}
public IRegion getKeyAt(Long position) {
- IRegion reg = null;
+ IRegion reg = null;
- Iterator<Long> keys = keyPositions.keySet().iterator();
- while (keys.hasNext()) {
- Long startPos = keys.next();
- if (startPos > position) {
- break;
- }
+ Iterator<Long> keys = keyPositions.keySet().iterator();
+ while (keys.hasNext()) {
+ Long startPos = keys.next();
+ if (startPos > position) {
+ break;
+ }
- IRegion region = keyPositions.get(startPos);
- if (region.getOffset() <= position
- && (region.getOffset() + region.getLength()) >= position) {
- reg = region;
- break;
- }
- }
+ IRegion region = keyPositions.get(startPos);
+ if (region.getOffset() <= position
+ && (region.getOffset() + region.getLength()) >= position) {
+ reg = region;
+ break;
+ }
+ }
- return reg;
+ return reg;
}
public String getKeyAt(IRegion region) {
- if (bundleKeys.containsKey(region)) {
- return bundleKeys.get(region);
- } else {
- return "";
- }
+ if (bundleKeys.containsKey(region)) {
+ return bundleKeys.get(region);
+ } else {
+ return "";
+ }
}
public String getBundleReference(IRegion region) {
- return bundleReferences.get(region);
+ return bundleReferences.get(region);
}
@Override
public boolean visit(IResource resource) throws CoreException {
- // TODO Auto-generated method stub
- return false;
+ // TODO Auto-generated method stub
+ return false;
}
public Collection<String> getDefinedResourceBundles(int offset) {
- Collection<String> result = new HashSet<String>();
- for (String s : bundleReferences.values()) {
- if (s != null) {
- result.add(s);
- }
- }
- return result;
+ Collection<String> result = new HashSet<String>();
+ for (String s : bundleReferences.values()) {
+ if (s != null) {
+ result.add(s);
+ }
+ }
+ return result;
}
public IRegion getRBReferenceAt(Long offset) {
- IRegion reg = null;
+ IRegion reg = null;
- Iterator<Long> keys = rbDefReferences.keySet().iterator();
- while (keys.hasNext()) {
- Long startPos = keys.next();
- if (startPos > offset) {
- break;
- }
+ Iterator<Long> keys = rbDefReferences.keySet().iterator();
+ while (keys.hasNext()) {
+ Long startPos = keys.next();
+ if (startPos > offset) {
+ break;
+ }
- IRegion region = rbDefReferences.get(startPos);
- if (region != null && region.getOffset() <= offset
- && (region.getOffset() + region.getLength()) >= offset) {
- reg = region;
- break;
- }
- }
+ IRegion region = rbDefReferences.get(startPos);
+ if (region != null && region.getOffset() <= offset
+ && (region.getOffset() + region.getLength()) >= offset) {
+ reg = region;
+ break;
+ }
+ }
- return reg;
+ return reg;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ImageUtils.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ImageUtils.java
index 8db317c..5669465 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ImageUtils.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ImageUtils.java
@@ -29,27 +29,27 @@
public static final String RESOURCEBUNDLE_IMAGE = "resourcebundle.gif"; //$NON-NLS-1$
public static final String EXPAND = "expand.gif"; //$NON-NLS-1$
public static final String DEFAULT_LOCALICON = File.separatorChar
- + "countries" + File.separatorChar + "_f.gif";
+ + "countries" + File.separatorChar + "_f.gif";
public static final String LOCATION_WITHOUT_ICON = File.separatorChar
- + "countries" + File.separatorChar + "un.gif";
+ + "countries" + File.separatorChar + "un.gif";
/**
* @return a Image from the folder 'icons'
* @throws URISyntaxException
*/
public static Image getBaseImage(String imageName) {
- Image image = imageRegistry.get(imageName);
- if (image == null) {
- ImageDescriptor descriptor = RBManagerActivator
- .getImageDescriptor(imageName);
+ Image image = imageRegistry.get(imageName);
+ if (image == null) {
+ ImageDescriptor descriptor = RBManagerActivator
+ .getImageDescriptor(imageName);
- if (descriptor.getImageData() != null) {
- image = descriptor.createImage(false);
- imageRegistry.put(imageName, image);
- }
- }
+ if (descriptor.getImageData() != null) {
+ image = descriptor.createImage(false);
+ imageRegistry.put(imageName, image);
+ }
+ }
- return image;
+ return image;
}
/**
@@ -57,17 +57,17 @@
* @return baseImage with a overlay warning-image
*/
public static Image getImageWithWarning(Image baseImage) {
- String imageWithWarningId = baseImage.toString() + ".w";
- Image imageWithWarning = imageRegistry.get(imageWithWarningId);
+ String imageWithWarningId = baseImage.toString() + ".w";
+ Image imageWithWarning = imageRegistry.get(imageWithWarningId);
- if (imageWithWarning == null) {
- Image warningImage = getBaseImage(WARNING_FLAG_IMAGE);
- imageWithWarning = new OverlayIcon(baseImage, warningImage,
- OverlayIcon.BOTTOM_LEFT).createImage();
- imageRegistry.put(imageWithWarningId, imageWithWarning);
- }
+ if (imageWithWarning == null) {
+ Image warningImage = getBaseImage(WARNING_FLAG_IMAGE);
+ imageWithWarning = new OverlayIcon(baseImage, warningImage,
+ OverlayIcon.BOTTOM_LEFT).createImage();
+ imageRegistry.put(imageWithWarningId, imageWithWarning);
+ }
- return imageWithWarning;
+ return imageWithWarning;
}
/**
@@ -76,46 +76,46 @@
* @return baseImage with a overlay fragment-image
*/
public static Image getImageWithFragment(Image baseImage) {
- String imageWithFragmentId = baseImage.toString() + ".f";
- Image imageWithFragment = imageRegistry.get(imageWithFragmentId);
+ String imageWithFragmentId = baseImage.toString() + ".f";
+ Image imageWithFragment = imageRegistry.get(imageWithFragmentId);
- if (imageWithFragment == null) {
- Image fragement = getBaseImage(FRAGMENT_FLAG_IMAGE);
- imageWithFragment = new OverlayIcon(baseImage, fragement,
- OverlayIcon.BOTTOM_RIGHT).createImage();
- imageRegistry.put(imageWithFragmentId, imageWithFragment);
- }
+ if (imageWithFragment == null) {
+ Image fragement = getBaseImage(FRAGMENT_FLAG_IMAGE);
+ imageWithFragment = new OverlayIcon(baseImage, fragement,
+ OverlayIcon.BOTTOM_RIGHT).createImage();
+ imageRegistry.put(imageWithFragmentId, imageWithFragment);
+ }
- return imageWithFragment;
+ return imageWithFragment;
}
/**
* @return a Image with a flag of the given country
*/
public static Image getLocalIcon(Locale locale) {
- String imageName;
- Image image = null;
+ String imageName;
+ Image image = null;
- if (locale != null && !locale.getCountry().equals("")) {
- imageName = File.separatorChar + "countries" + File.separatorChar
- + locale.getCountry().toLowerCase() + ".gif";
- image = getBaseImage(imageName);
- } else {
- if (locale != null) {
- imageName = File.separatorChar + "countries"
- + File.separatorChar + "l_"
- + locale.getLanguage().toLowerCase() + ".gif";
- image = getBaseImage(imageName);
- } else {
- imageName = DEFAULT_LOCALICON.toLowerCase(); // Default locale
- // icon
- image = getBaseImage(imageName);
- }
- }
+ if (locale != null && !locale.getCountry().equals("")) {
+ imageName = File.separatorChar + "countries" + File.separatorChar
+ + locale.getCountry().toLowerCase() + ".gif";
+ image = getBaseImage(imageName);
+ } else {
+ if (locale != null) {
+ imageName = File.separatorChar + "countries"
+ + File.separatorChar + "l_"
+ + locale.getLanguage().toLowerCase() + ".gif";
+ image = getBaseImage(imageName);
+ } else {
+ imageName = DEFAULT_LOCALICON.toLowerCase(); // Default locale
+ // icon
+ image = getBaseImage(imageName);
+ }
+ }
- if (image == null)
- image = getBaseImage(LOCATION_WITHOUT_ICON.toLowerCase());
- return image;
+ if (image == null)
+ image = getBaseImage(LOCATION_WITHOUT_ICON.toLowerCase());
+ return image;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java
index 68faf55..5ff9b3e 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java
@@ -37,8 +37,8 @@
* )
*/
public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
+ super.start(context);
+ plugin = this;
}
/*
@@ -49,8 +49,8 @@
* )
*/
public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
+ plugin = null;
+ super.stop(context);
}
/**
@@ -59,13 +59,13 @@
* @return the shared instance
*/
public static RBManagerActivator getDefault() {
- return plugin;
+ return plugin;
}
public static ImageDescriptor getImageDescriptor(String name) {
- String path = "icons/" + name;
+ String path = "icons/" + name;
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
+ return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java
index 4d7ed6f..522a992 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java
@@ -23,48 +23,48 @@
private ILocation sameValuePartner;
public RBLocation(IFile file, int startPos, int endPos, String language) {
- this.file = file;
- this.startPos = startPos;
- this.endPos = endPos;
- this.language = language;
+ this.file = file;
+ this.startPos = startPos;
+ this.endPos = endPos;
+ this.language = language;
}
public RBLocation(IFile file, int startPos, int endPos, String language,
- ILocation sameValuePartner) {
- this(file, startPos, endPos, language);
- this.sameValuePartner = sameValuePartner;
+ ILocation sameValuePartner) {
+ this(file, startPos, endPos, language);
+ this.sameValuePartner = sameValuePartner;
}
@Override
public IFile getFile() {
- return file;
+ return file;
}
@Override
public int getStartPos() {
- return startPos;
+ return startPos;
}
@Override
public int getEndPos() {
- return endPos;
+ return endPos;
}
@Override
public String getLiteral() {
- return language;
+ return language;
}
@Override
public Serializable getData() {
- return data;
+ return data;
}
public void setData(Serializable data) {
- this.data = data;
+ this.data = data;
}
public ILocation getSameValuePartner() {
- return sameValuePartner;
+ return sameValuePartner;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java
index a0a2e99..c75044e 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java
@@ -52,27 +52,27 @@
@Override
public String[] getFileEndings() {
- return new String[] { "properties" };
+ return new String[] { "properties" };
}
@Override
public String getContextId() {
- return "resourcebundle";
+ return "resourcebundle";
}
@Override
public List<ILocation> getUnspecifiedKeyReferences() {
- return unspecifiedKeys;
+ return unspecifiedKeys;
}
@Override
public Map<ILocation, ILocation> getSameValuesReferences() {
- return sameValues;
+ return sameValues;
}
@Override
public List<ILocation> getMissingLanguageReferences() {
- return missingLanguages;
+ return missingLanguages;
}
/*
@@ -80,10 +80,10 @@
*/
@Override
public void resetProblems() {
- unspecifiedKeys = new LinkedList<ILocation>();
- sameValues = new HashMap<ILocation, ILocation>();
- missingLanguages = new LinkedList<ILocation>();
- seenRBs = new LinkedList<String>();
+ unspecifiedKeys = new LinkedList<ILocation>();
+ sameValues = new HashMap<ILocation, ILocation>();
+ missingLanguages = new LinkedList<ILocation>();
+ seenRBs = new LinkedList<String>();
}
/*
@@ -93,62 +93,62 @@
*/
@Override
public void audit(IResource resource) {
- if (!RBFileUtils.isResourceBundleFile(resource)) {
- return;
- }
+ if (!RBFileUtils.isResourceBundleFile(resource)) {
+ return;
+ }
- IFile file = (IFile) resource;
- String rbId = RBFileUtils.getCorrespondingResourceBundleId(file);
+ IFile file = (IFile) resource;
+ String rbId = RBFileUtils.getCorrespondingResourceBundleId(file);
- if (!seenRBs.contains(rbId)) {
- ResourceBundleManager rbmanager = ResourceBundleManager
- .getManager(file.getProject());
- audit(rbId, rbmanager);
- seenRBs.add(rbId);
- } else {
- return;
- }
+ if (!seenRBs.contains(rbId)) {
+ ResourceBundleManager rbmanager = ResourceBundleManager
+ .getManager(file.getProject());
+ audit(rbId, rbmanager);
+ seenRBs.add(rbId);
+ } else {
+ return;
+ }
}
/*
* audits all files of a resourcebundle
*/
public void audit(String rbId, ResourceBundleManager rbmanager) {
- IConfiguration configuration = ConfigurationManager.getInstance()
- .getConfiguration();
- IMessagesBundleGroup bundlegroup = rbmanager.getResourceBundle(rbId);
- Collection<IResource> bundlefile = rbmanager.getResourceBundles(rbId);
- String[] keys = bundlegroup.getMessageKeys();
+ IConfiguration configuration = ConfigurationManager.getInstance()
+ .getConfiguration();
+ IMessagesBundleGroup bundlegroup = rbmanager.getResourceBundle(rbId);
+ Collection<IResource> bundlefile = rbmanager.getResourceBundles(rbId);
+ String[] keys = bundlegroup.getMessageKeys();
- for (IResource r : bundlefile) {
- IFile f1 = (IFile) r;
+ for (IResource r : bundlefile) {
+ IFile f1 = (IFile) r;
- for (String key : keys) {
- // check if all keys have a value
+ for (String key : keys) {
+ // check if all keys have a value
- if (auditUnspecifiedKey(f1, key, bundlegroup)) {
- /* do nothing - all just done */
- } else {
- // check if a key has the same value like a key of an other
- // properties-file
- if (configuration.getAuditSameValue()
- && bundlefile.size() > 1) {
- for (IResource r2 : bundlefile) {
- IFile f2 = (IFile) r2;
- auditSameValues(f1, f2, key, bundlegroup);
- }
- }
- }
- }
- }
+ if (auditUnspecifiedKey(f1, key, bundlegroup)) {
+ /* do nothing - all just done */
+ } else {
+ // check if a key has the same value like a key of an other
+ // properties-file
+ if (configuration.getAuditSameValue()
+ && bundlefile.size() > 1) {
+ for (IResource r2 : bundlefile) {
+ IFile f2 = (IFile) r2;
+ auditSameValues(f1, f2, key, bundlegroup);
+ }
+ }
+ }
+ }
+ }
- if (configuration.getAuditMissingLanguage()) {
- // checks if the resourcebundle supports all project-languages
- Set<Locale> rbLocales = rbmanager.getProvidedLocales(rbId);
- Set<Locale> projectLocales = rbmanager.getProjectProvidedLocales();
+ if (configuration.getAuditMissingLanguage()) {
+ // checks if the resourcebundle supports all project-languages
+ Set<Locale> rbLocales = rbmanager.getProvidedLocales(rbId);
+ Set<Locale> projectLocales = rbmanager.getProjectProvidedLocales();
- auditMissingLanguage(rbLocales, projectLocales, rbmanager, rbId);
- }
+ auditMissingLanguage(rbLocales, projectLocales, rbmanager, rbId);
+ }
}
/*
@@ -156,14 +156,14 @@
* a problem.
*/
private boolean auditUnspecifiedKey(IFile f1, String key,
- IMessagesBundleGroup bundlegroup) {
- if (bundlegroup.getMessage(key, RBFileUtils.getLocale(f1)) == null) {
- int pos = calculateKeyLine(key, f1);
- unspecifiedKeys.add(new RBLocation(f1, pos, pos + 1, key));
- return true;
- } else {
- return false;
- }
+ IMessagesBundleGroup bundlegroup) {
+ if (bundlegroup.getMessage(key, RBFileUtils.getLocale(f1)) == null) {
+ int pos = calculateKeyLine(key, f1);
+ unspecifiedKeys.add(new RBLocation(f1, pos, pos + 1, key));
+ return true;
+ } else {
+ return false;
+ }
}
/*
@@ -171,23 +171,23 @@
* are same. It doesn't compare the files if one file is the Default-file
*/
private void auditSameValues(IFile f1, IFile f2, String key,
- IMessagesBundleGroup bundlegroup) {
- Locale l1 = RBFileUtils.getLocale(f1);
- Locale l2 = RBFileUtils.getLocale(f2);
-
- if (l1 != null && l2 != null && !l2.equals(l1)) {
- IMessage message = bundlegroup.getMessage(key, l2);
+ IMessagesBundleGroup bundlegroup) {
+ Locale l1 = RBFileUtils.getLocale(f1);
+ Locale l2 = RBFileUtils.getLocale(f2);
- if (message != null) {
- if (bundlegroup.getMessage(key, l1).getValue()
- .equals(message.getValue())) {
- int pos1 = calculateKeyLine(key, f1);
- int pos2 = calculateKeyLine(key, f2);
- sameValues.put(new RBLocation(f1, pos1, pos1 + 1, key),
- new RBLocation(f2, pos2, pos2 + 1, key));
- }
- }
- }
+ if (l1 != null && l2 != null && !l2.equals(l1)) {
+ IMessage message = bundlegroup.getMessage(key, l2);
+
+ if (message != null) {
+ if (bundlegroup.getMessage(key, l1).getValue()
+ .equals(message.getValue())) {
+ int pos1 = calculateKeyLine(key, f1);
+ int pos2 = calculateKeyLine(key, f2);
+ sameValues.put(new RBLocation(f1, pos1, pos1 + 1, key),
+ new RBLocation(f2, pos2, pos2 + 1, key));
+ }
+ }
+ }
}
/*
@@ -195,68 +195,68 @@
* missing languages.
*/
private void auditMissingLanguage(Set<Locale> rbLocales,
- Set<Locale> projectLocales, ResourceBundleManager rbmanager,
- String rbId) {
- for (Locale pLocale : projectLocales) {
- if (!rbLocales.contains(pLocale)) {
- String language = pLocale != null ? pLocale.toString()
- : ResourceBundleManager.defaultLocaleTag;
+ Set<Locale> projectLocales, ResourceBundleManager rbmanager,
+ String rbId) {
+ for (Locale pLocale : projectLocales) {
+ if (!rbLocales.contains(pLocale)) {
+ String language = pLocale != null ? pLocale.toString()
+ : ResourceBundleManager.defaultLocaleTag;
- // Add Warning to default-file or a random chosen file
- IResource representative = rbmanager.getResourceBundleFile(
- rbId, null);
- if (representative == null) {
- representative = rbmanager.getRandomFile(rbId);
- }
- missingLanguages.add(new RBLocation((IFile) representative, 1,
- 2, language));
- }
- }
+ // Add Warning to default-file or a random chosen file
+ IResource representative = rbmanager.getResourceBundleFile(
+ rbId, null);
+ if (representative == null) {
+ representative = rbmanager.getRandomFile(rbId);
+ }
+ missingLanguages.add(new RBLocation((IFile) representative, 1,
+ 2, language));
+ }
+ }
}
/*
* Finds a position where the key is located or missing
*/
private int calculateKeyLine(String key, IFile file) {
- int linenumber = 1;
- try {
- // if (!Boolean.valueOf(System.getProperty("dirty"))) {
- // System.setProperty("dirty", "true");
- file.refreshLocal(IFile.DEPTH_ZERO, null);
- InputStream is = file.getContents();
- BufferedReader bf = new BufferedReader(new InputStreamReader(is));
- String line;
- while ((line = bf.readLine()) != null) {
- if ((!line.isEmpty()) && (!line.startsWith("#"))
- && (line.compareTo(key) > 0)) {
- return linenumber;
- }
- linenumber++;
- }
- // System.setProperty("dirty", "false");
- // }
- } catch (CoreException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return linenumber;
+ int linenumber = 1;
+ try {
+ // if (!Boolean.valueOf(System.getProperty("dirty"))) {
+ // System.setProperty("dirty", "true");
+ file.refreshLocal(IFile.DEPTH_ZERO, null);
+ InputStream is = file.getContents();
+ BufferedReader bf = new BufferedReader(new InputStreamReader(is));
+ String line;
+ while ((line = bf.readLine()) != null) {
+ if ((!line.isEmpty()) && (!line.startsWith("#"))
+ && (line.compareTo(key) > 0)) {
+ return linenumber;
+ }
+ linenumber++;
+ }
+ // System.setProperty("dirty", "false");
+ // }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return linenumber;
}
@Override
public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
- List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
+ List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
- switch (marker.getAttribute("cause", -1)) {
- case IMarkerConstants.CAUSE_MISSING_LANGUAGE:
- Locale l = new Locale(marker.getAttribute(LANGUAGE_ATTRIBUTE, "")); // TODO
- // change
- // Name
- resolutions.add(new MissingLanguageResolution(l));
- break;
- }
+ switch (marker.getAttribute("cause", -1)) {
+ case IMarkerConstants.CAUSE_MISSING_LANGUAGE:
+ Locale l = new Locale(marker.getAttribute(LANGUAGE_ATTRIBUTE, "")); // TODO
+ // change
+ // Name
+ resolutions.add(new MissingLanguageResolution(l));
+ break;
+ }
- return resolutions;
+ return resolutions;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java
index 912d27e..7671b1c 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java
@@ -24,30 +24,30 @@
private Locale language;
public MissingLanguageResolution(Locale language) {
- this.language = language;
+ this.language = language;
}
@Override
public String getLabel() {
- return "Add missing language '" + language + "'";
+ return "Add missing language '" + language + "'";
}
@Override
public void run(IMarker marker) {
- IResource res = marker.getResource();
- String rbId = ResourceBundleManager.getResourceBundleId(res);
- LanguageUtils.addLanguageToResourceBundle(res.getProject(), rbId,
- language);
+ IResource res = marker.getResource();
+ String rbId = ResourceBundleManager.getResourceBundleId(res);
+ LanguageUtils.addLanguageToResourceBundle(res.getProject(), rbId,
+ language);
}
@Override
public String getDescription() {
- return "Creates a new localized properties-file with the same basename as the resourcebundle";
+ return "Creates a new localized properties-file with the same basename as the resourcebundle";
}
@Override
public Image getImage() {
- return null;
+ return null;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java
index fedbd4f..2e47dac 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java
@@ -23,53 +23,53 @@
protected int rbCount;
public VirtualContainer(IContainer container1, boolean countResourceBundles) {
- this.container = container1;
- rbmanager = ResourceBundleManager.getManager(container.getProject());
- if (countResourceBundles) {
- rbCount = 1;
- new Job("count ResourceBundles") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- recount();
- return Status.OK_STATUS;
- }
- }.schedule();
- } else {
- rbCount = 0;
- }
+ this.container = container1;
+ rbmanager = ResourceBundleManager.getManager(container.getProject());
+ if (countResourceBundles) {
+ rbCount = 1;
+ new Job("count ResourceBundles") {
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ recount();
+ return Status.OK_STATUS;
+ }
+ }.schedule();
+ } else {
+ rbCount = 0;
+ }
}
protected VirtualContainer(IContainer container) {
- this.container = container;
+ this.container = container;
}
public VirtualContainer(IContainer container, int rbCount) {
- this(container, false);
- this.rbCount = rbCount;
+ this(container, false);
+ this.rbCount = rbCount;
}
public ResourceBundleManager getResourceBundleManager() {
- if (rbmanager == null) {
- rbmanager = ResourceBundleManager
- .getManager(container.getProject());
- }
- return rbmanager;
+ if (rbmanager == null) {
+ rbmanager = ResourceBundleManager
+ .getManager(container.getProject());
+ }
+ return rbmanager;
}
public IContainer getContainer() {
- return container;
+ return container;
}
public void setRbCounter(int rbCount) {
- this.rbCount = rbCount;
+ this.rbCount = rbCount;
}
public int getRbCount() {
- return rbCount;
+ return rbCount;
}
public void recount() {
- rbCount = org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils
- .countRecursiveResourceBundle(container);
+ rbCount = org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils
+ .countRecursiveResourceBundle(container);
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java
index a6c1447..fe589e9 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java
@@ -25,43 +25,43 @@
}
public static VirtualContentManager getVirtualContentManager() {
- if (singelton == null) {
- singelton = new VirtualContentManager();
- }
- return singelton;
+ if (singelton == null) {
+ singelton = new VirtualContentManager();
+ }
+ return singelton;
}
public VirtualContainer getContainer(IContainer container) {
- return containers.get(container);
+ return containers.get(container);
}
public void addVContainer(IContainer container, VirtualContainer vContainer) {
- containers.put(container, vContainer);
+ containers.put(container, vContainer);
}
public void removeVContainer(IContainer container) {
- vResourceBundles.remove(container);
+ vResourceBundles.remove(container);
}
public VirtualResourceBundle getVResourceBundles(String vRbId) {
- return vResourceBundles.get(vRbId);
+ return vResourceBundles.get(vRbId);
}
public void addVResourceBundle(String vRbId,
- VirtualResourceBundle vResourceBundle) {
- vResourceBundles.put(vRbId, vResourceBundle);
+ VirtualResourceBundle vResourceBundle) {
+ vResourceBundles.put(vRbId, vResourceBundle);
}
public void removeVResourceBundle(String vRbId) {
- vResourceBundles.remove(vRbId);
+ vResourceBundles.remove(vRbId);
}
public boolean containsVResourceBundles(String vRbId) {
- return vResourceBundles.containsKey(vRbId);
+ return vResourceBundles.containsKey(vRbId);
}
public void reset() {
- vResourceBundles.clear();
- containers.clear();
+ vResourceBundles.clear();
+ containers.clear();
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java
index 44cd4a7..70ab5b2 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java
@@ -29,46 +29,46 @@
// Slow
public VirtualProject(IProject project, boolean countResourceBundles) {
- super(project, countResourceBundles);
- isFragment = FragmentProjectUtils.isFragment(project);
- if (isFragment) {
- hostProject = FragmentProjectUtils.getFragmentHost(project);
- } else
- fragmentProjects = FragmentProjectUtils.getFragments(project);
+ super(project, countResourceBundles);
+ isFragment = FragmentProjectUtils.isFragment(project);
+ if (isFragment) {
+ hostProject = FragmentProjectUtils.getFragmentHost(project);
+ } else
+ fragmentProjects = FragmentProjectUtils.getFragments(project);
}
/*
* No fragment search
*/
public VirtualProject(final IProject project, boolean isFragment,
- boolean countResourceBundles) {
- super(project, countResourceBundles);
- this.isFragment = isFragment;
- // Display.getDefault().asyncExec(new Runnable() {
- // @Override
- // public void run() {
- // hostProject = FragmentProjectUtils.getFragmentHost(project);
- // }
- // });
+ boolean countResourceBundles) {
+ super(project, countResourceBundles);
+ this.isFragment = isFragment;
+ // Display.getDefault().asyncExec(new Runnable() {
+ // @Override
+ // public void run() {
+ // hostProject = FragmentProjectUtils.getFragmentHost(project);
+ // }
+ // });
}
public Set<Locale> getProvidedLocales() {
- return rbmanager.getProjectProvidedLocales();
+ return rbmanager.getProjectProvidedLocales();
}
public boolean isFragment() {
- return isFragment;
+ return isFragment;
}
public IProject getHostProject() {
- return hostProject;
+ return hostProject;
}
public boolean hasFragments() {
- return !fragmentProjects.isEmpty();
+ return !fragmentProjects.isEmpty();
}
public List<IProject> getFragmets() {
- return fragmentProjects;
+ return fragmentProjects;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualResourceBundle.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualResourceBundle.java
index ce0b96d..3cc8e55 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualResourceBundle.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualResourceBundle.java
@@ -23,38 +23,38 @@
private ResourceBundleManager rbmanager;
public VirtualResourceBundle(String rbname, String rbId,
- ResourceBundleManager rbmanager) {
- this.rbmanager = rbmanager;
- resourcebundlename = rbname;
- resourcebundleId = rbId;
+ ResourceBundleManager rbmanager) {
+ this.rbmanager = rbmanager;
+ resourcebundlename = rbname;
+ resourcebundleId = rbId;
}
public ResourceBundleManager getResourceBundleManager() {
- return rbmanager;
+ return rbmanager;
}
public String getResourceBundleId() {
- return resourcebundleId;
+ return resourcebundleId;
}
@Override
public String toString() {
- return resourcebundleId;
+ return resourcebundleId;
}
public IPath getFullPath() {
- return rbmanager.getRandomFile(resourcebundleId).getFullPath();
+ return rbmanager.getRandomFile(resourcebundleId).getFullPath();
}
public String getName() {
- return resourcebundlename;
+ return resourcebundlename;
}
public Collection<IResource> getFiles() {
- return rbmanager.getResourceBundles(resourcebundleId);
+ return rbmanager.getResourceBundles(resourcebundleId);
}
public IFile getRandomFile() {
- return rbmanager.getRandomFile(resourcebundleId);
+ return rbmanager.getRandomFile(resourcebundleId);
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/Hover.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/Hover.java
index 49d7290..7601c78 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/Hover.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/Hover.java
@@ -33,87 +33,87 @@
private List<HoverInformant> informant;
public Hover(Shell parent, List<HoverInformant> informant) {
- this.informant = informant;
- hoverShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL);
- Display display = hoverShell.getDisplay();
+ this.informant = informant;
+ hoverShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL);
+ Display display = hoverShell.getDisplay();
- GridLayout gridLayout = new GridLayout(1, false);
- gridLayout.verticalSpacing = 2;
- hoverShell.setLayout(gridLayout);
+ GridLayout gridLayout = new GridLayout(1, false);
+ gridLayout.verticalSpacing = 2;
+ hoverShell.setLayout(gridLayout);
- hoverShell.setBackground(display
- .getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- hoverShell.setForeground(display
- .getSystemColor(SWT.COLOR_INFO_FOREGROUND));
+ hoverShell.setBackground(display
+ .getSystemColor(SWT.COLOR_INFO_BACKGROUND));
+ hoverShell.setForeground(display
+ .getSystemColor(SWT.COLOR_INFO_FOREGROUND));
}
private void setHoverLocation(Shell shell, Point position) {
- Rectangle displayBounds = shell.getDisplay().getBounds();
- Rectangle shellBounds = shell.getBounds();
- shellBounds.x = Math.max(
- Math.min(position.x + 1, displayBounds.width
- - shellBounds.width), 0);
- shellBounds.y = Math.max(
- Math.min(position.y + 16, displayBounds.height
- - (shellBounds.height + 1)), 0);
- shell.setBounds(shellBounds);
+ Rectangle displayBounds = shell.getDisplay().getBounds();
+ Rectangle shellBounds = shell.getBounds();
+ shellBounds.x = Math.max(
+ Math.min(position.x + 1, displayBounds.width
+ - shellBounds.width), 0);
+ shellBounds.y = Math.max(
+ Math.min(position.y + 16, displayBounds.height
+ - (shellBounds.height + 1)), 0);
+ shell.setBounds(shellBounds);
}
public void activateHoverHelp(final Control control) {
- control.addMouseListener(new MouseAdapter() {
- public void mouseDown(MouseEvent e) {
- if (hoverShell != null && hoverShell.isVisible()) {
- hoverShell.setVisible(false);
- }
- }
- });
+ control.addMouseListener(new MouseAdapter() {
+ public void mouseDown(MouseEvent e) {
+ if (hoverShell != null && hoverShell.isVisible()) {
+ hoverShell.setVisible(false);
+ }
+ }
+ });
- control.addMouseTrackListener(new MouseTrackAdapter() {
- public void mouseExit(MouseEvent e) {
- if (hoverShell != null && hoverShell.isVisible())
- hoverShell.setVisible(false);
- }
+ control.addMouseTrackListener(new MouseTrackAdapter() {
+ public void mouseExit(MouseEvent e) {
+ if (hoverShell != null && hoverShell.isVisible())
+ hoverShell.setVisible(false);
+ }
- public void mouseHover(MouseEvent event) {
- Point pt = new Point(event.x, event.y);
- Widget widget = event.widget;
- if (widget instanceof ToolBar) {
- ToolBar w = (ToolBar) widget;
- widget = w.getItem(pt);
- }
- if (widget instanceof Table) {
- Table w = (Table) widget;
- widget = w.getItem(pt);
- }
- if (widget instanceof Tree) {
- Tree w = (Tree) widget;
- widget = w.getItem(pt);
- }
- if (widget == null) {
- hoverShell.setVisible(false);
- return;
- }
- hoverPosition = control.toDisplay(pt);
+ public void mouseHover(MouseEvent event) {
+ Point pt = new Point(event.x, event.y);
+ Widget widget = event.widget;
+ if (widget instanceof ToolBar) {
+ ToolBar w = (ToolBar) widget;
+ widget = w.getItem(pt);
+ }
+ if (widget instanceof Table) {
+ Table w = (Table) widget;
+ widget = w.getItem(pt);
+ }
+ if (widget instanceof Tree) {
+ Tree w = (Tree) widget;
+ widget = w.getItem(pt);
+ }
+ if (widget == null) {
+ hoverShell.setVisible(false);
+ return;
+ }
+ hoverPosition = control.toDisplay(pt);
- boolean show = false;
- Object data = widget.getData();
+ boolean show = false;
+ Object data = widget.getData();
- for (HoverInformant hi : informant) {
- hi.getInfoComposite(data, hoverShell);
- if (hi.show())
- show = true;
- }
+ for (HoverInformant hi : informant) {
+ hi.getInfoComposite(data, hoverShell);
+ if (hi.show())
+ show = true;
+ }
- if (show) {
- hoverShell.pack();
- hoverShell.layout();
- setHoverLocation(hoverShell, hoverPosition);
- hoverShell.setVisible(true);
- } else
- hoverShell.setVisible(false);
+ if (show) {
+ hoverShell.pack();
+ hoverShell.layout();
+ setHoverLocation(hoverShell, hoverPosition);
+ hoverShell.setVisible(true);
+ } else
+ hoverShell.setVisible(false);
- }
- });
+ }
+ });
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java
index 18b99ca..c415e21 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java
@@ -29,29 +29,29 @@
@Override
public void run(IAction action) {
- Object data = viewer.getControl().getData();
+ Object data = viewer.getControl().getData();
- for (final IProject p : ((IWorkspaceRoot) data).getProjects()) {
- UIJob job = new UIJob("expand Projects") {
- @Override
- public IStatus runInUIThread(IProgressMonitor monitor) {
- viewer.expandToLevel(p, AbstractTreeViewer.ALL_LEVELS);
- return Status.OK_STATUS;
- }
- };
+ for (final IProject p : ((IWorkspaceRoot) data).getProjects()) {
+ UIJob job = new UIJob("expand Projects") {
+ @Override
+ public IStatus runInUIThread(IProgressMonitor monitor) {
+ viewer.expandToLevel(p, AbstractTreeViewer.ALL_LEVELS);
+ return Status.OK_STATUS;
+ }
+ };
- job.schedule();
- }
+ job.schedule();
+ }
}
@Override
public void selectionChanged(IAction action, ISelection selection) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
}
@Override
public void init(IViewPart view) {
- viewer = ((CommonNavigator) view).getCommonViewer();
+ viewer = ((CommonNavigator) view).getCommonViewer();
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java
index b5f4093..5ca05a7 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java
@@ -24,44 +24,44 @@
private INavigatorFilterService filterService;
private boolean active;
private static final String[] FILTER = { RBManagerActivator.PLUGIN_ID
- + ".filter.ProblematicResourceBundleFiles" };
+ + ".filter.ProblematicResourceBundleFiles" };
@Override
public void run(IAction action) {
- if (active == true) {
- filterService.activateFilterIdsAndUpdateViewer(new String[0]);
- active = false;
- } else {
- filterService.activateFilterIdsAndUpdateViewer(FILTER);
- active = true;
- }
+ if (active == true) {
+ filterService.activateFilterIdsAndUpdateViewer(new String[0]);
+ active = false;
+ } else {
+ filterService.activateFilterIdsAndUpdateViewer(FILTER);
+ active = true;
+ }
}
@Override
public void selectionChanged(IAction action, ISelection selection) {
- // Active when content change
+ // Active when content change
}
@Override
public void init(IViewPart view) {
- INavigatorContentService contentService = ((CommonNavigator) view)
- .getCommonViewer().getNavigatorContentService();
+ INavigatorContentService contentService = ((CommonNavigator) view)
+ .getCommonViewer().getNavigatorContentService();
- filterService = contentService.getFilterService();
- filterService.activateFilterIdsAndUpdateViewer(new String[0]);
- active = false;
+ filterService = contentService.getFilterService();
+ filterService.activateFilterIdsAndUpdateViewer(new String[0]);
+ active = false;
}
@SuppressWarnings("unused")
private String[] getActiveFilterIds() {
- ICommonFilterDescriptor[] fds = filterService
- .getVisibleFilterDescriptors();
- String activeFilterIds[] = new String[fds.length];
+ ICommonFilterDescriptor[] fds = filterService
+ .getVisibleFilterDescriptors();
+ String activeFilterIds[] = new String[fds.length];
- for (int i = 0; i < fds.length; i++)
- activeFilterIds[i] = fds[i].getId();
+ for (int i = 0; i < fds.length; i++)
+ activeFilterIds[i] = fds[i].getId();
- return activeFilterIds;
+ return activeFilterIds;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java
index 1b98016..78e7de7 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java
@@ -29,21 +29,21 @@
@Override
public IStructuredSelection findSelection(IEditorInput anInput) {
- IFile file = ResourceUtil.getFile(anInput);
- if (file != null) {
- return new StructuredSelection(file);
- }
- return StructuredSelection.EMPTY;
+ IFile file = ResourceUtil.getFile(anInput);
+ if (file != null) {
+ return new StructuredSelection(file);
+ }
+ return StructuredSelection.EMPTY;
}
@Override
public void activateEditor(IWorkbenchPage aPage,
- IStructuredSelection aSelection) {
- if (aSelection.getFirstElement() instanceof IFile)
- try {
- IDE.openEditor(aPage, (IFile) aSelection.getFirstElement());
- } catch (PartInitException e) {/**/
- }
+ IStructuredSelection aSelection) {
+ if (aSelection.getFirstElement() instanceof IFile)
+ try {
+ IDE.openEditor(aPage, (IFile) aSelection.getFirstElement());
+ } catch (PartInitException e) {/**/
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java
index 50ae03a..a33d985 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java
@@ -57,8 +57,8 @@
*
*/
public class ResourceBundleContentProvider implements ITreeContentProvider,
- IResourceChangeListener, IPropertyChangeListener,
- IResourceBundleChangedListener {
+ IResourceChangeListener, IPropertyChangeListener,
+ IResourceBundleChangedListener {
private static final boolean FRAGMENT_PROJECTS_IN_CONTENT = false;
private static final boolean SHOW_ONLY_PROJECTS_WITH_RBS = true;
private StructuredViewer viewer;
@@ -72,96 +72,96 @@
*
*/
public ResourceBundleContentProvider() {
- ResourcesPlugin.getWorkspace().addResourceChangeListener(this,
- IResourceChangeEvent.POST_CHANGE);
- TapiJIPreferences.addPropertyChangeListener(this);
- vcManager = VirtualContentManager.getVirtualContentManager();
- listenedProjects = new LinkedList<IProject>();
+ ResourcesPlugin.getWorkspace().addResourceChangeListener(this,
+ IResourceChangeEvent.POST_CHANGE);
+ TapiJIPreferences.addPropertyChangeListener(this);
+ vcManager = VirtualContentManager.getVirtualContentManager();
+ listenedProjects = new LinkedList<IProject>();
}
@Override
public Object[] getElements(Object inputElement) {
- return getChildren(inputElement);
+ return getChildren(inputElement);
}
@Override
public Object[] getChildren(final Object parentElement) {
- Object[] children = null;
+ Object[] children = null;
- if (parentElement instanceof IWorkspaceRoot) {
- root = (IWorkspaceRoot) parentElement;
- try {
- IResource[] members = ((IWorkspaceRoot) parentElement)
- .members();
+ if (parentElement instanceof IWorkspaceRoot) {
+ root = (IWorkspaceRoot) parentElement;
+ try {
+ IResource[] members = ((IWorkspaceRoot) parentElement)
+ .members();
- List<Object> displayedProjects = new ArrayList<Object>();
- for (IResource r : members) {
- if (r instanceof IProject) {
- IProject p = (IProject) r;
- if (FragmentProjectUtils.isFragment(r.getProject())) {
- if (vcManager.getContainer(p) == null) {
- vcManager.addVContainer(p, new VirtualProject(
- p, true, false));
- }
- if (FRAGMENT_PROJECTS_IN_CONTENT) {
- displayedProjects.add(r);
- }
- } else {
- if (SHOW_ONLY_PROJECTS_WITH_RBS) {
- VirtualProject vP;
- if ((vP = (VirtualProject) vcManager
- .getContainer(p)) == null) {
- vP = new VirtualProject(p, false, true);
- vcManager.addVContainer(p, vP);
- registerResourceBundleListner(p);
- }
+ List<Object> displayedProjects = new ArrayList<Object>();
+ for (IResource r : members) {
+ if (r instanceof IProject) {
+ IProject p = (IProject) r;
+ if (FragmentProjectUtils.isFragment(r.getProject())) {
+ if (vcManager.getContainer(p) == null) {
+ vcManager.addVContainer(p, new VirtualProject(
+ p, true, false));
+ }
+ if (FRAGMENT_PROJECTS_IN_CONTENT) {
+ displayedProjects.add(r);
+ }
+ } else {
+ if (SHOW_ONLY_PROJECTS_WITH_RBS) {
+ VirtualProject vP;
+ if ((vP = (VirtualProject) vcManager
+ .getContainer(p)) == null) {
+ vP = new VirtualProject(p, false, true);
+ vcManager.addVContainer(p, vP);
+ registerResourceBundleListner(p);
+ }
- if (vP.getRbCount() > 0) {
- displayedProjects.add(p);
- }
- } else {
- displayedProjects.add(p);
- }
- }
- }
- }
+ if (vP.getRbCount() > 0) {
+ displayedProjects.add(p);
+ }
+ } else {
+ displayedProjects.add(p);
+ }
+ }
+ }
+ }
- children = displayedProjects.toArray();
- return children;
- } catch (CoreException e) {
- }
- }
+ children = displayedProjects.toArray();
+ return children;
+ } catch (CoreException e) {
+ }
+ }
- // if (parentElement instanceof IProject) {
- // final IProject iproject = (IProject) parentElement;
- // VirtualContainer vproject = vcManager.getContainer(iproject);
- // if (vproject == null){
- // vproject = new VirtualProject(iproject, true);
- // vcManager.addVContainer(iproject, vproject);
- // }
- // }
+ // if (parentElement instanceof IProject) {
+ // final IProject iproject = (IProject) parentElement;
+ // VirtualContainer vproject = vcManager.getContainer(iproject);
+ // if (vproject == null){
+ // vproject = new VirtualProject(iproject, true);
+ // vcManager.addVContainer(iproject, vproject);
+ // }
+ // }
- if (parentElement instanceof IContainer) {
- IContainer container = (IContainer) parentElement;
- if (!((VirtualProject) vcManager
- .getContainer(((IResource) parentElement).getProject()))
- .isFragment()) {
- try {
- children = addChildren(container);
- } catch (CoreException e) {/**/
- }
- }
- }
+ if (parentElement instanceof IContainer) {
+ IContainer container = (IContainer) parentElement;
+ if (!((VirtualProject) vcManager
+ .getContainer(((IResource) parentElement).getProject()))
+ .isFragment()) {
+ try {
+ children = addChildren(container);
+ } catch (CoreException e) {/**/
+ }
+ }
+ }
- if (parentElement instanceof VirtualResourceBundle) {
- VirtualResourceBundle virtualrb = (VirtualResourceBundle) parentElement;
- ResourceBundleManager rbmanager = virtualrb
- .getResourceBundleManager();
- children = rbmanager.getResourceBundles(
- virtualrb.getResourceBundleId()).toArray();
- }
+ if (parentElement instanceof VirtualResourceBundle) {
+ VirtualResourceBundle virtualrb = (VirtualResourceBundle) parentElement;
+ ResourceBundleManager rbmanager = virtualrb
+ .getResourceBundleManager();
+ children = rbmanager.getResourceBundles(
+ virtualrb.getResourceBundleId()).toArray();
+ }
- return children != null ? children : new Object[0];
+ return children != null ? children : new Object[0];
}
/*
@@ -169,298 +169,298 @@
* their subtree) of a Container
*/
private Object[] addChildren(IContainer container) throws CoreException {
- Map<String, Object> children = new HashMap<String, Object>();
+ Map<String, Object> children = new HashMap<String, Object>();
- VirtualProject p = (VirtualProject) vcManager.getContainer(container
- .getProject());
- List<IResource> members = new ArrayList<IResource>(
- Arrays.asList(container.members()));
+ VirtualProject p = (VirtualProject) vcManager.getContainer(container
+ .getProject());
+ List<IResource> members = new ArrayList<IResource>(
+ Arrays.asList(container.members()));
- // finds files in the corresponding fragment-projects folder
- if (p.hasFragments()) {
- List<IContainer> folders = ResourceUtils.getCorrespondingFolders(
- container, p.getFragmets());
- for (IContainer f : folders) {
- for (IResource r : f.members()) {
- if (r instanceof IFile) {
- members.add(r);
- }
- }
- }
- }
+ // finds files in the corresponding fragment-projects folder
+ if (p.hasFragments()) {
+ List<IContainer> folders = ResourceUtils.getCorrespondingFolders(
+ container, p.getFragmets());
+ for (IContainer f : folders) {
+ for (IResource r : f.members()) {
+ if (r instanceof IFile) {
+ members.add(r);
+ }
+ }
+ }
+ }
- for (IResource r : members) {
+ for (IResource r : members) {
- if (r instanceof IFile) {
- String resourcebundleId = RBFileUtils
- .getCorrespondingResourceBundleId((IFile) r);
- if (resourcebundleId != null
- && (!children.containsKey(resourcebundleId))) {
- VirtualResourceBundle vrb;
+ if (r instanceof IFile) {
+ String resourcebundleId = RBFileUtils
+ .getCorrespondingResourceBundleId((IFile) r);
+ if (resourcebundleId != null
+ && (!children.containsKey(resourcebundleId))) {
+ VirtualResourceBundle vrb;
- String vRBId;
+ String vRBId;
- if (!p.isFragment()) {
- vRBId = r.getProject() + "." + resourcebundleId;
- } else {
- vRBId = p.getHostProject() + "." + resourcebundleId;
- }
+ if (!p.isFragment()) {
+ vRBId = r.getProject() + "." + resourcebundleId;
+ } else {
+ vRBId = p.getHostProject() + "." + resourcebundleId;
+ }
- VirtualResourceBundle vResourceBundle = vcManager
- .getVResourceBundles(vRBId);
- if (vResourceBundle == null) {
- String resourcebundleName = ResourceBundleManager
- .getResourceBundleName(r);
- vrb = new VirtualResourceBundle(
- resourcebundleName,
- resourcebundleId,
- ResourceBundleManager.getManager(r.getProject()));
- vcManager.addVResourceBundle(vRBId, vrb);
+ VirtualResourceBundle vResourceBundle = vcManager
+ .getVResourceBundles(vRBId);
+ if (vResourceBundle == null) {
+ String resourcebundleName = ResourceBundleManager
+ .getResourceBundleName(r);
+ vrb = new VirtualResourceBundle(
+ resourcebundleName,
+ resourcebundleId,
+ ResourceBundleManager.getManager(r.getProject()));
+ vcManager.addVResourceBundle(vRBId, vrb);
- } else {
- vrb = vcManager.getVResourceBundles(vRBId);
- }
+ } else {
+ vrb = vcManager.getVResourceBundles(vRBId);
+ }
- children.put(resourcebundleId, vrb);
- }
- }
- if (r instanceof IContainer) {
- if (!r.isDerived()) { // Don't show the 'bin' folder
- VirtualContainer vContainer = vcManager
- .getContainer((IContainer) r);
+ children.put(resourcebundleId, vrb);
+ }
+ }
+ if (r instanceof IContainer) {
+ if (!r.isDerived()) { // Don't show the 'bin' folder
+ VirtualContainer vContainer = vcManager
+ .getContainer((IContainer) r);
- if (vContainer == null) {
- int count = RBFileUtils
- .countRecursiveResourceBundle((IContainer) r);
- vContainer = new VirtualContainer(container, count);
- vcManager.addVContainer((IContainer) r, vContainer);
- }
+ if (vContainer == null) {
+ int count = RBFileUtils
+ .countRecursiveResourceBundle((IContainer) r);
+ vContainer = new VirtualContainer(container, count);
+ vcManager.addVContainer((IContainer) r, vContainer);
+ }
- if (vContainer.getRbCount() != 0) {
- // without resourcebundles
- children.put("" + children.size(), r);
- }
- }
- }
- }
- return children.values().toArray();
+ if (vContainer.getRbCount() != 0) {
+ // without resourcebundles
+ children.put("" + children.size(), r);
+ }
+ }
+ }
+ }
+ return children.values().toArray();
}
@Override
public Object getParent(Object element) {
- if (element instanceof IContainer) {
- return ((IContainer) element).getParent();
- }
- if (element instanceof IFile) {
- String rbId = RBFileUtils
- .getCorrespondingResourceBundleId((IFile) element);
- return vcManager.getVResourceBundles(rbId);
- }
- if (element instanceof VirtualResourceBundle) {
- Iterator<IResource> i = new HashSet<IResource>(
- ((VirtualResourceBundle) element).getFiles()).iterator();
- if (i.hasNext()) {
- return i.next().getParent();
- }
- }
- return null;
+ if (element instanceof IContainer) {
+ return ((IContainer) element).getParent();
+ }
+ if (element instanceof IFile) {
+ String rbId = RBFileUtils
+ .getCorrespondingResourceBundleId((IFile) element);
+ return vcManager.getVResourceBundles(rbId);
+ }
+ if (element instanceof VirtualResourceBundle) {
+ Iterator<IResource> i = new HashSet<IResource>(
+ ((VirtualResourceBundle) element).getFiles()).iterator();
+ if (i.hasNext()) {
+ return i.next().getParent();
+ }
+ }
+ return null;
}
@Override
public boolean hasChildren(Object element) {
- if (element instanceof IWorkspaceRoot) {
- try {
- if (((IWorkspaceRoot) element).members().length > 0) {
- return true;
- }
- } catch (CoreException e) {
- }
- }
- if (element instanceof IProject) {
- VirtualProject vProject = (VirtualProject) vcManager
- .getContainer((IProject) element);
- if (vProject != null && vProject.isFragment()) {
- return false;
- }
- }
- if (element instanceof IContainer) {
- try {
- VirtualContainer vContainer = vcManager
- .getContainer((IContainer) element);
- if (vContainer != null) {
- return vContainer.getRbCount() > 0 ? true : false;
- } else if (((IContainer) element).members().length > 0) {
- return true;
- }
- } catch (CoreException e) {
- }
- }
- if (element instanceof VirtualResourceBundle) {
- return true;
- }
- return false;
+ if (element instanceof IWorkspaceRoot) {
+ try {
+ if (((IWorkspaceRoot) element).members().length > 0) {
+ return true;
+ }
+ } catch (CoreException e) {
+ }
+ }
+ if (element instanceof IProject) {
+ VirtualProject vProject = (VirtualProject) vcManager
+ .getContainer((IProject) element);
+ if (vProject != null && vProject.isFragment()) {
+ return false;
+ }
+ }
+ if (element instanceof IContainer) {
+ try {
+ VirtualContainer vContainer = vcManager
+ .getContainer((IContainer) element);
+ if (vContainer != null) {
+ return vContainer.getRbCount() > 0 ? true : false;
+ } else if (((IContainer) element).members().length > 0) {
+ return true;
+ }
+ } catch (CoreException e) {
+ }
+ }
+ if (element instanceof VirtualResourceBundle) {
+ return true;
+ }
+ return false;
}
@Override
public void dispose() {
- ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
- TapiJIPreferences.removePropertyChangeListener(this);
- vcManager.reset();
- unregisterAllResourceBundleListner();
+ ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
+ TapiJIPreferences.removePropertyChangeListener(this);
+ vcManager.reset();
+ unregisterAllResourceBundleListner();
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- this.viewer = (StructuredViewer) viewer;
+ this.viewer = (StructuredViewer) viewer;
}
@Override
// TODO remove ResourceChangelistner and add ResourceBundleChangelistner
public void resourceChanged(final IResourceChangeEvent event) {
- final IResourceDeltaVisitor visitor = new IResourceDeltaVisitor() {
- @Override
- public boolean visit(IResourceDelta delta) throws CoreException {
- final IResource res = delta.getResource();
+ final IResourceDeltaVisitor visitor = new IResourceDeltaVisitor() {
+ @Override
+ public boolean visit(IResourceDelta delta) throws CoreException {
+ final IResource res = delta.getResource();
- if (!RBFileUtils.isResourceBundleFile(res)) {
- return true;
- }
+ if (!RBFileUtils.isResourceBundleFile(res)) {
+ return true;
+ }
- switch (delta.getKind()) {
- case IResourceDelta.REMOVED:
- recountParenthierarchy(res.getParent());
- break;
- // TODO remove unused VirtualResourceBundles and
- // VirtualContainer from vcManager
- case IResourceDelta.ADDED:
- checkListner(res);
- break;
- case IResourceDelta.CHANGED:
- if (delta.getFlags() != IResourceDelta.MARKERS) {
- return true;
- }
- break;
- }
+ switch (delta.getKind()) {
+ case IResourceDelta.REMOVED:
+ recountParenthierarchy(res.getParent());
+ break;
+ // TODO remove unused VirtualResourceBundles and
+ // VirtualContainer from vcManager
+ case IResourceDelta.ADDED:
+ checkListner(res);
+ break;
+ case IResourceDelta.CHANGED:
+ if (delta.getFlags() != IResourceDelta.MARKERS) {
+ return true;
+ }
+ break;
+ }
- refresh(res);
+ refresh(res);
- return true;
- }
- };
+ return true;
+ }
+ };
- try {
- event.getDelta().accept(visitor);
- } catch (Exception e) {
- e.printStackTrace();
- }
+ try {
+ event.getDelta().accept(visitor);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
}
@Override
public void resourceBundleChanged(ResourceBundleChangedEvent event) {
- ResourceBundleManager rbmanager = ResourceBundleManager
- .getManager(event.getProject());
+ ResourceBundleManager rbmanager = ResourceBundleManager
+ .getManager(event.getProject());
- switch (event.getType()) {
- case ResourceBundleChangedEvent.ADDED:
- case ResourceBundleChangedEvent.DELETED:
- IResource res = rbmanager.getRandomFile(event.getBundle());
- IContainer hostContainer;
+ switch (event.getType()) {
+ case ResourceBundleChangedEvent.ADDED:
+ case ResourceBundleChangedEvent.DELETED:
+ IResource res = rbmanager.getRandomFile(event.getBundle());
+ IContainer hostContainer;
- if (res == null) {
- try {
- hostContainer = event.getProject()
- .getFile(event.getBundle()).getParent();
- } catch (Exception e) {
- refresh(null);
- return;
- }
- } else {
- VirtualProject vProject = (VirtualProject) vcManager
- .getContainer(res.getProject());
- if (vProject != null && vProject.isFragment()) {
- IProject hostProject = vProject.getHostProject();
- hostContainer = ResourceUtils.getCorrespondingFolders(
- res.getParent(), hostProject);
- } else {
- hostContainer = res.getParent();
- }
- }
+ if (res == null) {
+ try {
+ hostContainer = event.getProject()
+ .getFile(event.getBundle()).getParent();
+ } catch (Exception e) {
+ refresh(null);
+ return;
+ }
+ } else {
+ VirtualProject vProject = (VirtualProject) vcManager
+ .getContainer(res.getProject());
+ if (vProject != null && vProject.isFragment()) {
+ IProject hostProject = vProject.getHostProject();
+ hostContainer = ResourceUtils.getCorrespondingFolders(
+ res.getParent(), hostProject);
+ } else {
+ hostContainer = res.getParent();
+ }
+ }
- recountParenthierarchy(hostContainer);
- refresh(null);
- break;
- }
+ recountParenthierarchy(hostContainer);
+ refresh(null);
+ break;
+ }
}
@Override
public void propertyChange(PropertyChangeEvent event) {
- if (event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN)) {
- vcManager.reset();
+ if (event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN)) {
+ vcManager.reset();
- refresh(root);
- }
+ refresh(root);
+ }
}
// TODO problems with remove a hole ResourceBundle
private void recountParenthierarchy(IContainer parent) {
- if (parent.isDerived()) {
- return; // Don't recount the 'bin' folder
- }
+ if (parent.isDerived()) {
+ return; // Don't recount the 'bin' folder
+ }
- VirtualContainer vContainer = vcManager.getContainer(parent);
- if (vContainer != null) {
- vContainer.recount();
- }
+ VirtualContainer vContainer = vcManager.getContainer(parent);
+ if (vContainer != null) {
+ vContainer.recount();
+ }
- if ((parent instanceof IFolder)) {
- recountParenthierarchy(parent.getParent());
- }
+ if ((parent instanceof IFolder)) {
+ recountParenthierarchy(parent.getParent());
+ }
}
private void refresh(final IResource res) {
- if (refresh == null || refresh.getResult() != null) {
- refresh = new UIJob("refresh viewer") {
- @Override
- public IStatus runInUIThread(IProgressMonitor monitor) {
- if (viewer != null && !viewer.getControl().isDisposed()) {
- if (res != null) {
- viewer.refresh(res.getProject(), true); // refresh(res);
- } else {
- viewer.refresh();
- }
- }
- return Status.OK_STATUS;
- }
- };
- }
- refresh.schedule();
+ if (refresh == null || refresh.getResult() != null) {
+ refresh = new UIJob("refresh viewer") {
+ @Override
+ public IStatus runInUIThread(IProgressMonitor monitor) {
+ if (viewer != null && !viewer.getControl().isDisposed()) {
+ if (res != null) {
+ viewer.refresh(res.getProject(), true); // refresh(res);
+ } else {
+ viewer.refresh();
+ }
+ }
+ return Status.OK_STATUS;
+ }
+ };
+ }
+ refresh.schedule();
}
private void registerResourceBundleListner(IProject p) {
- listenedProjects.add(p);
+ listenedProjects.add(p);
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(p);
- for (String rbId : rbmanager.getResourceBundleIdentifiers()) {
- rbmanager.registerResourceBundleChangeListener(rbId, this);
- }
+ ResourceBundleManager rbmanager = ResourceBundleManager.getManager(p);
+ for (String rbId : rbmanager.getResourceBundleIdentifiers()) {
+ rbmanager.registerResourceBundleChangeListener(rbId, this);
+ }
}
private void unregisterAllResourceBundleListner() {
- for (IProject p : listenedProjects) {
- ResourceBundleManager rbmanager = ResourceBundleManager
- .getManager(p);
- for (String rbId : rbmanager.getResourceBundleIdentifiers()) {
- rbmanager.unregisterResourceBundleChangeListener(rbId, this);
- }
- }
+ for (IProject p : listenedProjects) {
+ ResourceBundleManager rbmanager = ResourceBundleManager
+ .getManager(p);
+ for (String rbId : rbmanager.getResourceBundleIdentifiers()) {
+ rbmanager.unregisterResourceBundleChangeListener(rbId, this);
+ }
+ }
}
private void checkListner(IResource res) {
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(res
- .getProject());
- String rbId = ResourceBundleManager.getResourceBundleId(res);
- rbmanager.registerResourceBundleChangeListener(rbId, this);
+ ResourceBundleManager rbmanager = ResourceBundleManager.getManager(res
+ .getProject());
+ String rbId = ResourceBundleManager.getResourceBundleId(res);
+ rbmanager.registerResourceBundleChangeListener(rbId, this);
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java
index fc14794..b883d06 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java
@@ -36,172 +36,172 @@
import org.eclipse.ui.navigator.IDescriptionProvider;
public class ResourceBundleLabelProvider extends LabelProvider implements
- ILabelProvider, IDescriptionProvider {
+ ILabelProvider, IDescriptionProvider {
VirtualContentManager vcManager;
public ResourceBundleLabelProvider() {
- super();
- vcManager = VirtualContentManager.getVirtualContentManager();
+ super();
+ vcManager = VirtualContentManager.getVirtualContentManager();
}
@Override
public Image getImage(Object element) {
- Image returnImage = null;
- if (element instanceof IProject) {
- VirtualProject p = (VirtualProject) vcManager
- .getContainer((IProject) element);
- if (p != null && p.isFragment()) {
- return returnImage = ImageUtils
- .getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE);
- } else {
- returnImage = PlatformUI.getWorkbench().getSharedImages()
- .getImage(ISharedImages.IMG_OBJ_PROJECT);
- }
- }
- if ((element instanceof IContainer) && (returnImage == null)) {
- returnImage = PlatformUI.getWorkbench().getSharedImages()
- .getImage(ISharedImages.IMG_OBJ_FOLDER);
- }
- if (element instanceof VirtualResourceBundle) {
- returnImage = ImageUtils
- .getBaseImage(ImageUtils.RESOURCEBUNDLE_IMAGE);
- }
- if (element instanceof IFile) {
- if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils
- .isResourceBundleFile((IFile) element)) {
- Locale l = org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils
- .getLocale((IFile) element);
- returnImage = ImageUtils.getLocalIcon(l);
+ Image returnImage = null;
+ if (element instanceof IProject) {
+ VirtualProject p = (VirtualProject) vcManager
+ .getContainer((IProject) element);
+ if (p != null && p.isFragment()) {
+ return returnImage = ImageUtils
+ .getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE);
+ } else {
+ returnImage = PlatformUI.getWorkbench().getSharedImages()
+ .getImage(ISharedImages.IMG_OBJ_PROJECT);
+ }
+ }
+ if ((element instanceof IContainer) && (returnImage == null)) {
+ returnImage = PlatformUI.getWorkbench().getSharedImages()
+ .getImage(ISharedImages.IMG_OBJ_FOLDER);
+ }
+ if (element instanceof VirtualResourceBundle) {
+ returnImage = ImageUtils
+ .getBaseImage(ImageUtils.RESOURCEBUNDLE_IMAGE);
+ }
+ if (element instanceof IFile) {
+ if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils
+ .isResourceBundleFile((IFile) element)) {
+ Locale l = org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils
+ .getLocale((IFile) element);
+ returnImage = ImageUtils.getLocalIcon(l);
- VirtualProject p = ((VirtualProject) vcManager
- .getContainer(((IFile) element).getProject()));
- if (p != null && p.isFragment()) {
- returnImage = ImageUtils.getImageWithFragment(returnImage);
- }
- }
- }
+ VirtualProject p = ((VirtualProject) vcManager
+ .getContainer(((IFile) element).getProject()));
+ if (p != null && p.isFragment()) {
+ returnImage = ImageUtils.getImageWithFragment(returnImage);
+ }
+ }
+ }
- if (returnImage != null) {
- if (checkMarkers(element)) {
- // Add a Warning Image
- returnImage = ImageUtils.getImageWithWarning(returnImage);
- }
- }
- return returnImage;
+ if (returnImage != null) {
+ if (checkMarkers(element)) {
+ // Add a Warning Image
+ returnImage = ImageUtils.getImageWithWarning(returnImage);
+ }
+ }
+ return returnImage;
}
@Override
public String getText(Object element) {
- StringBuilder text = new StringBuilder();
- if (element instanceof IContainer) {
- IContainer container = (IContainer) element;
- text.append(container.getName());
+ StringBuilder text = new StringBuilder();
+ if (element instanceof IContainer) {
+ IContainer container = (IContainer) element;
+ text.append(container.getName());
- if (element instanceof IProject) {
- VirtualContainer vproject = vcManager
- .getContainer((IProject) element);
- // if (vproject != null && vproject instanceof VirtualFragment)
- // text.append("�");
- }
+ if (element instanceof IProject) {
+ VirtualContainer vproject = vcManager
+ .getContainer((IProject) element);
+ // if (vproject != null && vproject instanceof VirtualFragment)
+ // text.append("�");
+ }
- VirtualContainer vContainer = vcManager.getContainer(container);
- if (vContainer != null && vContainer.getRbCount() != 0) {
- text.append(" [" + vContainer.getRbCount() + "]");
- }
+ VirtualContainer vContainer = vcManager.getContainer(container);
+ if (vContainer != null && vContainer.getRbCount() != 0) {
+ text.append(" [" + vContainer.getRbCount() + "]");
+ }
- }
- if (element instanceof VirtualResourceBundle) {
- text.append(((VirtualResourceBundle) element).getName());
- }
- if (element instanceof IFile) {
- if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils
- .isResourceBundleFile((IFile) element)) {
- Locale locale = org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils
- .getLocale((IFile) element);
- text.append(" ");
- if (locale != null) {
- text.append(locale);
- } else {
- text.append("default");
- }
+ }
+ if (element instanceof VirtualResourceBundle) {
+ text.append(((VirtualResourceBundle) element).getName());
+ }
+ if (element instanceof IFile) {
+ if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils
+ .isResourceBundleFile((IFile) element)) {
+ Locale locale = org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils
+ .getLocale((IFile) element);
+ text.append(" ");
+ if (locale != null) {
+ text.append(locale);
+ } else {
+ text.append("default");
+ }
- VirtualProject vproject = (VirtualProject) vcManager
- .getContainer(((IFile) element).getProject());
- if (vproject != null && vproject.isFragment()) {
- text.append("�");
- }
- }
- }
- if (element instanceof String) {
- text.append(element);
- }
- return text.toString();
+ VirtualProject vproject = (VirtualProject) vcManager
+ .getContainer(((IFile) element).getProject());
+ if (vproject != null && vproject.isFragment()) {
+ text.append("�");
+ }
+ }
+ }
+ if (element instanceof String) {
+ text.append(element);
+ }
+ return text.toString();
}
@Override
public String getDescription(Object anElement) {
- if (anElement instanceof IResource) {
- return ((IResource) anElement).getName();
- }
- if (anElement instanceof VirtualResourceBundle) {
- return ((VirtualResourceBundle) anElement).getName();
- }
- return null;
+ if (anElement instanceof IResource) {
+ return ((IResource) anElement).getName();
+ }
+ if (anElement instanceof VirtualResourceBundle) {
+ return ((VirtualResourceBundle) anElement).getName();
+ }
+ return null;
}
private boolean checkMarkers(Object element) {
- if (element instanceof IResource) {
- IMarker[] ms = null;
- try {
- if ((ms = ((IResource) element).findMarkers(
- EditorUtils.RB_MARKER_ID, true,
- IResource.DEPTH_INFINITE)).length > 0) {
- return true;
- }
+ if (element instanceof IResource) {
+ IMarker[] ms = null;
+ try {
+ if ((ms = ((IResource) element).findMarkers(
+ EditorUtils.RB_MARKER_ID, true,
+ IResource.DEPTH_INFINITE)).length > 0) {
+ return true;
+ }
- if (element instanceof IContainer) {
- List<IContainer> fragmentContainer = ResourceUtils
- .getCorrespondingFolders(
- (IContainer) element,
- FragmentProjectUtils
- .getFragments(((IContainer) element)
- .getProject()));
+ if (element instanceof IContainer) {
+ List<IContainer> fragmentContainer = ResourceUtils
+ .getCorrespondingFolders(
+ (IContainer) element,
+ FragmentProjectUtils
+ .getFragments(((IContainer) element)
+ .getProject()));
- IMarker[] fragment_ms;
- for (IContainer c : fragmentContainer) {
- try {
- if (c.exists()) {
- fragment_ms = c.findMarkers(
- EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
- ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils
- .concatMarkerArray(ms, fragment_ms);
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- if (ms.length > 0) {
- return true;
- }
- }
- } catch (CoreException e) {
- }
- }
- if (element instanceof VirtualResourceBundle) {
- ResourceBundleManager rbmanager = ((VirtualResourceBundle) element)
- .getResourceBundleManager();
- String id = ((VirtualResourceBundle) element).getResourceBundleId();
- for (IResource r : rbmanager.getResourceBundles(id)) {
- if (org.eclipse.babel.tapiji.tools.core.util.RBFileUtils
- .hasResourceBundleMarker(r)) {
- return true;
- }
- }
- }
+ IMarker[] fragment_ms;
+ for (IContainer c : fragmentContainer) {
+ try {
+ if (c.exists()) {
+ fragment_ms = c.findMarkers(
+ EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils
+ .concatMarkerArray(ms, fragment_ms);
+ }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ if (ms.length > 0) {
+ return true;
+ }
+ }
+ } catch (CoreException e) {
+ }
+ }
+ if (element instanceof VirtualResourceBundle) {
+ ResourceBundleManager rbmanager = ((VirtualResourceBundle) element)
+ .getResourceBundleManager();
+ String id = ((VirtualResourceBundle) element).getResourceBundleId();
+ for (IResource r : rbmanager.getResourceBundles(id)) {
+ if (org.eclipse.babel.tapiji.tools.core.util.RBFileUtils
+ .hasResourceBundleMarker(r)) {
+ return true;
+ }
+ }
+ }
- return false;
+ return false;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java
index b919658..6b22411 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java
@@ -24,31 +24,31 @@
private CommonViewer viewer;
public ExpandAction(CommonViewer viewer) {
- this.viewer = viewer;
- setText("Expand Node");
- setToolTipText("expand node");
- setImageDescriptor(RBManagerActivator
- .getImageDescriptor(ImageUtils.EXPAND));
+ this.viewer = viewer;
+ setText("Expand Node");
+ setToolTipText("expand node");
+ setImageDescriptor(RBManagerActivator
+ .getImageDescriptor(ImageUtils.EXPAND));
}
@Override
public boolean isEnabled() {
- IStructuredSelection sSelection = (IStructuredSelection) viewer
- .getSelection();
- if (sSelection.size() >= 1)
- return true;
- else
- return false;
+ IStructuredSelection sSelection = (IStructuredSelection) viewer
+ .getSelection();
+ if (sSelection.size() >= 1)
+ return true;
+ else
+ return false;
}
@Override
public void run() {
- IStructuredSelection sSelection = (IStructuredSelection) viewer
- .getSelection();
- Iterator<?> it = sSelection.iterator();
- while (it.hasNext()) {
- viewer.expandToLevel(it.next(), AbstractTreeViewer.ALL_LEVELS);
- }
+ IStructuredSelection sSelection = (IStructuredSelection) viewer
+ .getSelection();
+ Iterator<?> it = sSelection.iterator();
+ while (it.hasNext()) {
+ viewer.expandToLevel(it.next(), AbstractTreeViewer.ALL_LEVELS);
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java
index 4bb15f1..2553645 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java
@@ -28,29 +28,29 @@
private IAction expandAction;
public GeneralActionProvider() {
- // TODO Auto-generated constructor stub
+ // TODO Auto-generated constructor stub
}
@Override
public void init(ICommonActionExtensionSite aSite) {
- super.init(aSite);
- // init Expand-Action
- expandAction = new ExpandAction(
- (CommonViewer) aSite.getStructuredViewer());
+ super.init(aSite);
+ // init Expand-Action
+ expandAction = new ExpandAction(
+ (CommonViewer) aSite.getStructuredViewer());
- // activate View-Hover
- List<HoverInformant> informants = new ArrayList<HoverInformant>();
- informants.add(new I18NProjectInformant());
- informants.add(new RBMarkerInformant());
+ // activate View-Hover
+ List<HoverInformant> informants = new ArrayList<HoverInformant>();
+ informants.add(new I18NProjectInformant());
+ informants.add(new RBMarkerInformant());
- Hover hover = new Hover(Display.getCurrent().getActiveShell(),
- informants);
- hover.activateHoverHelp(((CommonViewer) aSite.getStructuredViewer())
- .getTree());
+ Hover hover = new Hover(Display.getCurrent().getActiveShell(),
+ informants);
+ hover.activateHoverHelp(((CommonViewer) aSite.getStructuredViewer())
+ .getTree());
}
@Override
public void fillContextMenu(IMenuManager menu) {
- menu.appendToGroup("expand", expandAction);
+ menu.appendToGroup("expand", expandAction);
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java
index 2b8b958..48a99ef 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java
@@ -22,32 +22,32 @@
private ISelectionProvider selectionProvider;
public OpenVRBAction(ISelectionProvider selectionProvider) {
- this.selectionProvider = selectionProvider;
+ this.selectionProvider = selectionProvider;
}
@Override
public boolean isEnabled() {
- IStructuredSelection sSelection = (IStructuredSelection) selectionProvider
- .getSelection();
- if (sSelection.size() == 1)
- return true;
- else
- return false;
+ IStructuredSelection sSelection = (IStructuredSelection) selectionProvider
+ .getSelection();
+ if (sSelection.size() == 1)
+ return true;
+ else
+ return false;
}
@Override
public void run() {
- IStructuredSelection sSelection = (IStructuredSelection) selectionProvider
- .getSelection();
- if (sSelection.size() == 1
- && sSelection.getFirstElement() instanceof VirtualResourceBundle) {
- VirtualResourceBundle vRB = (VirtualResourceBundle) sSelection
- .getFirstElement();
- IWorkbenchPage wp = RBManagerActivator.getDefault().getWorkbench()
- .getActiveWorkbenchWindow().getActivePage();
+ IStructuredSelection sSelection = (IStructuredSelection) selectionProvider
+ .getSelection();
+ if (sSelection.size() == 1
+ && sSelection.getFirstElement() instanceof VirtualResourceBundle) {
+ VirtualResourceBundle vRB = (VirtualResourceBundle) sSelection
+ .getFirstElement();
+ IWorkbenchPage wp = RBManagerActivator.getDefault().getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage();
- EditorUtils.openEditor(wp, vRB.getRandomFile(),
- EditorUtils.RESOURCE_BUNDLE_EDITOR);
- }
+ EditorUtils.openEditor(wp, vRB.getRandomFile(),
+ EditorUtils.RESOURCE_BUNDLE_EDITOR);
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java
index f1972fc..50a2dbc 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java
@@ -23,19 +23,19 @@
private IAction openAction;
public VirtualRBActionProvider() {
- // TODO Auto-generated constructor stub
+ // TODO Auto-generated constructor stub
}
@Override
public void init(ICommonActionExtensionSite aSite) {
- super.init(aSite);
- openAction = new OpenVRBAction(aSite.getViewSite()
- .getSelectionProvider());
+ super.init(aSite);
+ openAction = new OpenVRBAction(aSite.getViewSite()
+ .getSelectionProvider());
}
@Override
public void fillActionBars(IActionBars actionBars) {
- actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN,
- openAction);
+ actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN,
+ openAction);
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java
index ae330da..87edcf6 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java
@@ -44,189 +44,189 @@
@Override
public Composite getInfoComposite(Object data, Composite parent) {
- show = false;
+ show = false;
- if (infoComposite == null) {
- infoComposite = new Composite(parent, SWT.NONE);
- GridLayout layout = new GridLayout(1, false);
- layout.verticalSpacing = 1;
- layout.horizontalSpacing = 0;
- infoComposite.setLayout(layout);
+ if (infoComposite == null) {
+ infoComposite = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout(1, false);
+ layout.verticalSpacing = 1;
+ layout.horizontalSpacing = 0;
+ infoComposite.setLayout(layout);
- infoData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- infoComposite.setLayoutData(infoData);
- }
+ infoData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ infoComposite.setLayoutData(infoData);
+ }
- if (data instanceof IProject) {
- addLocale(infoComposite, data);
- addFragments(infoComposite, data);
- }
+ if (data instanceof IProject) {
+ addLocale(infoComposite, data);
+ addFragments(infoComposite, data);
+ }
- if (show) {
- infoData.heightHint = -1;
- infoData.widthHint = -1;
- } else {
- infoData.heightHint = 0;
- infoData.widthHint = 0;
- }
+ if (show) {
+ infoData.heightHint = -1;
+ infoData.widthHint = -1;
+ } else {
+ infoData.heightHint = 0;
+ infoData.widthHint = 0;
+ }
- infoComposite.layout();
- infoComposite.pack();
- sinkColor(infoComposite);
+ infoComposite.layout();
+ infoComposite.pack();
+ sinkColor(infoComposite);
- return infoComposite;
+ return infoComposite;
}
@Override
public boolean show() {
- return show;
+ return show;
}
private void setColor(Control control) {
- Display display = control.getParent().getDisplay();
+ Display display = control.getParent().getDisplay();
- control.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- control.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
+ control.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
+ control.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
}
private void sinkColor(Composite composite) {
- setColor(composite);
+ setColor(composite);
- for (Control c : composite.getChildren()) {
- setColor(c);
- if (c instanceof Composite) {
- sinkColor((Composite) c);
- }
- }
+ for (Control c : composite.getChildren()) {
+ setColor(c);
+ if (c instanceof Composite) {
+ sinkColor((Composite) c);
+ }
+ }
}
private void addLocale(Composite parent, Object data) {
- if (localeGroup == null) {
- localeGroup = new Composite(parent, SWT.NONE);
- localeLabel = new Label(localeGroup, SWT.SINGLE);
+ if (localeGroup == null) {
+ localeGroup = new Composite(parent, SWT.NONE);
+ localeLabel = new Label(localeGroup, SWT.SINGLE);
- showLocalesData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- localeGroup.setLayoutData(showLocalesData);
- }
+ showLocalesData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ localeGroup.setLayoutData(showLocalesData);
+ }
- locales = getProvidedLocales(data);
+ locales = getProvidedLocales(data);
- if (locales.length() != 0) {
- localeLabel.setText(locales);
- localeLabel.pack();
- show = true;
- // showLocalesData.heightHint = -1;
- // showLocalesData.widthHint=-1;
- } else {
- localeLabel.setText("No Language Provided");
- localeLabel.pack();
- show = true;
- // showLocalesData.heightHint = 0;
- // showLocalesData.widthHint = 0;
- }
+ if (locales.length() != 0) {
+ localeLabel.setText(locales);
+ localeLabel.pack();
+ show = true;
+ // showLocalesData.heightHint = -1;
+ // showLocalesData.widthHint=-1;
+ } else {
+ localeLabel.setText("No Language Provided");
+ localeLabel.pack();
+ show = true;
+ // showLocalesData.heightHint = 0;
+ // showLocalesData.widthHint = 0;
+ }
- // localeGroup.layout();
- localeGroup.pack();
+ // localeGroup.layout();
+ localeGroup.pack();
}
private void addFragments(Composite parent, Object data) {
- if (fragmentsGroup == null) {
- fragmentsGroup = new Composite(parent, SWT.NONE);
- GridLayout layout = new GridLayout(1, false);
- layout.verticalSpacing = 0;
- layout.horizontalSpacing = 0;
- fragmentsGroup.setLayout(layout);
+ if (fragmentsGroup == null) {
+ fragmentsGroup = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout(1, false);
+ layout.verticalSpacing = 0;
+ layout.horizontalSpacing = 0;
+ fragmentsGroup.setLayout(layout);
- showFragmentsData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- fragmentsGroup.setLayoutData(showFragmentsData);
+ showFragmentsData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ fragmentsGroup.setLayoutData(showFragmentsData);
- Composite fragmentTitleGroup = new Composite(fragmentsGroup,
- SWT.NONE);
- layout = new GridLayout(2, false);
- layout.verticalSpacing = 0;
- layout.horizontalSpacing = 5;
- fragmentTitleGroup.setLayout(layout);
+ Composite fragmentTitleGroup = new Composite(fragmentsGroup,
+ SWT.NONE);
+ layout = new GridLayout(2, false);
+ layout.verticalSpacing = 0;
+ layout.horizontalSpacing = 5;
+ fragmentTitleGroup.setLayout(layout);
- Label fragmentImageLabel = new Label(fragmentTitleGroup, SWT.NONE);
- fragmentImageLabel.setImage(ImageUtils
- .getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE));
- fragmentImageLabel.pack();
+ Label fragmentImageLabel = new Label(fragmentTitleGroup, SWT.NONE);
+ fragmentImageLabel.setImage(ImageUtils
+ .getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE));
+ fragmentImageLabel.pack();
- Label fragementTitleLabel = new Label(fragmentTitleGroup, SWT.NONE);
- fragementTitleLabel.setText("Project Fragments:");
- fragementTitleLabel.pack();
- fragmentsLabel = new Label(fragmentsGroup, SWT.SINGLE);
- }
+ Label fragementTitleLabel = new Label(fragmentTitleGroup, SWT.NONE);
+ fragementTitleLabel.setText("Project Fragments:");
+ fragementTitleLabel.pack();
+ fragmentsLabel = new Label(fragmentsGroup, SWT.SINGLE);
+ }
- fragments = getFragmentProjects(data);
+ fragments = getFragmentProjects(data);
- if (fragments.length() != 0) {
- fragmentsLabel.setText(fragments);
- show = true;
- showFragmentsData.heightHint = -1;
- showFragmentsData.widthHint = -1;
- fragmentsLabel.pack();
- } else {
- showFragmentsData.heightHint = 0;
- showFragmentsData.widthHint = 0;
- }
+ if (fragments.length() != 0) {
+ fragmentsLabel.setText(fragments);
+ show = true;
+ showFragmentsData.heightHint = -1;
+ showFragmentsData.widthHint = -1;
+ fragmentsLabel.pack();
+ } else {
+ showFragmentsData.heightHint = 0;
+ showFragmentsData.widthHint = 0;
+ }
- fragmentsGroup.layout();
- fragmentsGroup.pack();
+ fragmentsGroup.layout();
+ fragmentsGroup.pack();
}
private String getProvidedLocales(Object data) {
- if (data instanceof IProject) {
- ResourceBundleManager rbmanger = ResourceBundleManager
- .getManager((IProject) data);
- Set<Locale> ls = rbmanger.getProjectProvidedLocales();
+ if (data instanceof IProject) {
+ ResourceBundleManager rbmanger = ResourceBundleManager
+ .getManager((IProject) data);
+ Set<Locale> ls = rbmanger.getProjectProvidedLocales();
- if (ls.size() > 0) {
- StringBuilder sb = new StringBuilder();
- sb.append("Provided Languages:\n");
+ if (ls.size() > 0) {
+ StringBuilder sb = new StringBuilder();
+ sb.append("Provided Languages:\n");
- int i = 0;
- for (Locale l : ls) {
- if (l != null && !l.toString().equals("")) {
- sb.append(l.getDisplayName());
- } else {
- sb.append("[Default]");
- }
+ int i = 0;
+ for (Locale l : ls) {
+ if (l != null && !l.toString().equals("")) {
+ sb.append(l.getDisplayName());
+ } else {
+ sb.append("[Default]");
+ }
- if (++i != ls.size()) {
- sb.append(",");
- if (i % 5 == 0) {
- sb.append("\n");
- } else {
- sb.append(" ");
- }
- }
+ if (++i != ls.size()) {
+ sb.append(",");
+ if (i % 5 == 0) {
+ sb.append("\n");
+ } else {
+ sb.append(" ");
+ }
+ }
- }
- return sb.toString();
- }
- }
+ }
+ return sb.toString();
+ }
+ }
- return "";
+ return "";
}
private String getFragmentProjects(Object data) {
- if (data instanceof IProject) {
- List<IProject> fragments = FragmentProjectUtils
- .getFragments((IProject) data);
- if (fragments.size() > 0) {
- StringBuilder sb = new StringBuilder();
+ if (data instanceof IProject) {
+ List<IProject> fragments = FragmentProjectUtils
+ .getFragments((IProject) data);
+ if (fragments.size() > 0) {
+ StringBuilder sb = new StringBuilder();
- int i = 0;
- for (IProject f : fragments) {
- sb.append(f.getName());
- if (++i != fragments.size()) {
- sb.append("\n");
- }
- }
- return sb.toString();
- }
- }
- return "";
+ int i = 0;
+ for (IProject f : fragments) {
+ sb.append(f.getName());
+ if (++i != fragments.size()) {
+ sb.append("\n");
+ }
+ }
+ return sb.toString();
+ }
+ }
+ return "";
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java
index 3216984..8c06e72 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java
@@ -52,230 +52,230 @@
@Override
public Composite getInfoComposite(Object data, Composite parent) {
- show = false;
+ show = false;
- if (infoComposite == null) {
- infoComposite = new Composite(parent, SWT.NONE);
- GridLayout layout = new GridLayout(1, false);
- layout.verticalSpacing = 0;
- layout.horizontalSpacing = 0;
- infoComposite.setLayout(layout);
+ if (infoComposite == null) {
+ infoComposite = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout(1, false);
+ layout.verticalSpacing = 0;
+ layout.horizontalSpacing = 0;
+ infoComposite.setLayout(layout);
- infoData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- infoComposite.setLayoutData(infoData);
- }
+ infoData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ infoComposite.setLayoutData(infoData);
+ }
- if (data instanceof VirtualResourceBundle || data instanceof IResource) {
- addTitle(infoComposite, data);
- addProblems(infoComposite, data);
- }
+ if (data instanceof VirtualResourceBundle || data instanceof IResource) {
+ addTitle(infoComposite, data);
+ addProblems(infoComposite, data);
+ }
- if (show) {
- infoData.heightHint = -1;
- infoData.widthHint = -1;
- } else {
- infoData.heightHint = 0;
- infoData.widthHint = 0;
- }
+ if (show) {
+ infoData.heightHint = -1;
+ infoData.widthHint = -1;
+ } else {
+ infoData.heightHint = 0;
+ infoData.widthHint = 0;
+ }
- infoComposite.layout();
- sinkColor(infoComposite);
- infoComposite.pack();
+ infoComposite.layout();
+ sinkColor(infoComposite);
+ infoComposite.pack();
- return infoComposite;
+ return infoComposite;
}
@Override
public boolean show() {
- return show;
+ return show;
}
private void setColor(Control control) {
- Display display = control.getParent().getDisplay();
+ Display display = control.getParent().getDisplay();
- control.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- control.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
+ control.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
+ control.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
}
private void sinkColor(Composite composite) {
- setColor(composite);
+ setColor(composite);
- for (Control c : composite.getChildren()) {
- setColor(c);
- if (c instanceof Composite) {
- sinkColor((Composite) c);
- }
- }
+ for (Control c : composite.getChildren()) {
+ setColor(c);
+ if (c instanceof Composite) {
+ sinkColor((Composite) c);
+ }
+ }
}
private void addTitle(Composite parent, Object data) {
- if (titleGroup == null) {
- titleGroup = new Composite(parent, SWT.NONE);
- titleLabel = new Label(titleGroup, SWT.SINGLE);
+ if (titleGroup == null) {
+ titleGroup = new Composite(parent, SWT.NONE);
+ titleLabel = new Label(titleGroup, SWT.SINGLE);
- showTitleData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- titleGroup.setLayoutData(showTitleData);
- }
- title = getTitel(data);
+ showTitleData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ titleGroup.setLayoutData(showTitleData);
+ }
+ title = getTitel(data);
- if (title.length() != 0) {
- titleLabel.setText(title);
- show = true;
- showTitleData.heightHint = -1;
- showTitleData.widthHint = -1;
- titleLabel.pack();
- } else {
- showTitleData.heightHint = 0;
- showTitleData.widthHint = 0;
- }
+ if (title.length() != 0) {
+ titleLabel.setText(title);
+ show = true;
+ showTitleData.heightHint = -1;
+ showTitleData.widthHint = -1;
+ titleLabel.pack();
+ } else {
+ showTitleData.heightHint = 0;
+ showTitleData.widthHint = 0;
+ }
- titleGroup.layout();
- titleGroup.pack();
+ titleGroup.layout();
+ titleGroup.pack();
}
private void addProblems(Composite parent, Object data) {
- if (problemGroup == null) {
- problemGroup = new Composite(parent, SWT.NONE);
- GridLayout layout = new GridLayout(1, false);
- layout.verticalSpacing = 0;
- layout.horizontalSpacing = 0;
- problemGroup.setLayout(layout);
+ if (problemGroup == null) {
+ problemGroup = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout(1, false);
+ layout.verticalSpacing = 0;
+ layout.horizontalSpacing = 0;
+ problemGroup.setLayout(layout);
- showProblemsData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- problemGroup.setLayoutData(showProblemsData);
+ showProblemsData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ problemGroup.setLayoutData(showProblemsData);
- Composite problemTitleGroup = new Composite(problemGroup, SWT.NONE);
- layout = new GridLayout(2, false);
- layout.verticalSpacing = 0;
- layout.horizontalSpacing = 5;
- problemTitleGroup.setLayout(layout);
+ Composite problemTitleGroup = new Composite(problemGroup, SWT.NONE);
+ layout = new GridLayout(2, false);
+ layout.verticalSpacing = 0;
+ layout.horizontalSpacing = 5;
+ problemTitleGroup.setLayout(layout);
- Label warningImageLabel = new Label(problemTitleGroup, SWT.NONE);
- warningImageLabel.setImage(ImageUtils
- .getBaseImage(ImageUtils.WARNING_IMAGE));
- warningImageLabel.pack();
+ Label warningImageLabel = new Label(problemTitleGroup, SWT.NONE);
+ warningImageLabel.setImage(ImageUtils
+ .getBaseImage(ImageUtils.WARNING_IMAGE));
+ warningImageLabel.pack();
- Label waringTitleLabel = new Label(problemTitleGroup, SWT.NONE);
- waringTitleLabel.setText("ResourceBundle-Problems:");
- waringTitleLabel.pack();
+ Label waringTitleLabel = new Label(problemTitleGroup, SWT.NONE);
+ waringTitleLabel.setText("ResourceBundle-Problems:");
+ waringTitleLabel.pack();
- problemLabel = new Label(problemGroup, SWT.SINGLE);
- }
+ problemLabel = new Label(problemGroup, SWT.SINGLE);
+ }
- problems = getProblems(data);
+ problems = getProblems(data);
- if (problems.length() != 0) {
- problemLabel.setText(problems);
- show = true;
- showProblemsData.heightHint = -1;
- showProblemsData.widthHint = -1;
- problemLabel.pack();
- } else {
- showProblemsData.heightHint = 0;
- showProblemsData.widthHint = 0;
- }
+ if (problems.length() != 0) {
+ problemLabel.setText(problems);
+ show = true;
+ showProblemsData.heightHint = -1;
+ showProblemsData.widthHint = -1;
+ problemLabel.pack();
+ } else {
+ showProblemsData.heightHint = 0;
+ showProblemsData.widthHint = 0;
+ }
- problemGroup.layout();
- problemGroup.pack();
+ problemGroup.layout();
+ problemGroup.pack();
}
private String getTitel(Object data) {
- if (data instanceof IFile) {
- return ((IResource) data).getFullPath().toString();
- }
- if (data instanceof VirtualResourceBundle) {
- return ((VirtualResourceBundle) data).getResourceBundleId();
- }
+ if (data instanceof IFile) {
+ return ((IResource) data).getFullPath().toString();
+ }
+ if (data instanceof VirtualResourceBundle) {
+ return ((VirtualResourceBundle) data).getResourceBundleId();
+ }
- return "";
+ return "";
}
private String getProblems(Object data) {
- IMarker[] ms = null;
+ IMarker[] ms = null;
- if (data instanceof IResource) {
- IResource res = (IResource) data;
- try {
- if (res.exists()) {
- ms = res.findMarkers(EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
- } else {
- ms = new IMarker[0];
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
- if (data instanceof IContainer) {
- // add problem of same folder in the fragment-project
- List<IContainer> fragmentContainer = ResourceUtils
- .getCorrespondingFolders((IContainer) res,
- FragmentProjectUtils.getFragments(res
- .getProject()));
+ if (data instanceof IResource) {
+ IResource res = (IResource) data;
+ try {
+ if (res.exists()) {
+ ms = res.findMarkers(EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ } else {
+ ms = new IMarker[0];
+ }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ if (data instanceof IContainer) {
+ // add problem of same folder in the fragment-project
+ List<IContainer> fragmentContainer = ResourceUtils
+ .getCorrespondingFolders((IContainer) res,
+ FragmentProjectUtils.getFragments(res
+ .getProject()));
- IMarker[] fragment_ms;
- for (IContainer c : fragmentContainer) {
- try {
- if (c.exists()) {
- fragment_ms = c.findMarkers(
- EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
+ IMarker[] fragment_ms;
+ for (IContainer c : fragmentContainer) {
+ try {
+ if (c.exists()) {
+ fragment_ms = c.findMarkers(
+ EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
- ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils
- .concatMarkerArray(ms, fragment_ms);
- }
- } catch (CoreException e) {
- }
- }
- }
- }
+ ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils
+ .concatMarkerArray(ms, fragment_ms);
+ }
+ } catch (CoreException e) {
+ }
+ }
+ }
+ }
- if (data instanceof VirtualResourceBundle) {
- VirtualResourceBundle vRB = (VirtualResourceBundle) data;
+ if (data instanceof VirtualResourceBundle) {
+ VirtualResourceBundle vRB = (VirtualResourceBundle) data;
- ResourceBundleManager rbmanager = vRB.getResourceBundleManager();
- IMarker[] file_ms;
+ ResourceBundleManager rbmanager = vRB.getResourceBundleManager();
+ IMarker[] file_ms;
- Collection<IResource> rBundles = rbmanager.getResourceBundles(vRB
- .getResourceBundleId());
- if (!rBundles.isEmpty()) {
- for (IResource r : rBundles) {
- try {
- file_ms = r.findMarkers(EditorUtils.RB_MARKER_ID,
- false, IResource.DEPTH_INFINITE);
- if (ms != null) {
- ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils
- .concatMarkerArray(ms, file_ms);
- } else {
- ms = file_ms;
- }
- } catch (Exception e) {
- }
- }
- }
- }
+ Collection<IResource> rBundles = rbmanager.getResourceBundles(vRB
+ .getResourceBundleId());
+ if (!rBundles.isEmpty()) {
+ for (IResource r : rBundles) {
+ try {
+ file_ms = r.findMarkers(EditorUtils.RB_MARKER_ID,
+ false, IResource.DEPTH_INFINITE);
+ if (ms != null) {
+ ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils
+ .concatMarkerArray(ms, file_ms);
+ } else {
+ ms = file_ms;
+ }
+ } catch (Exception e) {
+ }
+ }
+ }
+ }
- StringBuilder sb = new StringBuilder();
- int count = 0;
+ StringBuilder sb = new StringBuilder();
+ int count = 0;
- if (ms != null && ms.length != 0) {
- for (IMarker m : ms) {
- try {
- sb.append(m.getAttribute(IMarker.MESSAGE));
- sb.append("\n");
- count++;
- if (count == MAX_PROBLEMS && ms.length - count != 0) {
- sb.append(" ... and ");
- sb.append(ms.length - count);
- sb.append(" other problems");
- break;
- }
- } catch (CoreException e) {
- }
- ;
- }
- return sb.toString();
- }
+ if (ms != null && ms.length != 0) {
+ for (IMarker m : ms) {
+ try {
+ sb.append(m.getAttribute(IMarker.MESSAGE));
+ sb.append("\n");
+ count++;
+ if (count == MAX_PROBLEMS && ms.length - count != 0) {
+ sb.append(" ... and ");
+ sb.append(ms.length - count);
+ sb.append(" other problems");
+ break;
+ }
+ } catch (CoreException e) {
+ }
+ ;
+ }
+ return sb.toString();
+ }
- return "";
+ return "";
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java
index fa7a44e..0f3fc34 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java
@@ -33,52 +33,52 @@
*/
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (element instanceof IFile) {
- return true;
- }
- if (element instanceof VirtualResourceBundle) {
- for (IResource f : ((VirtualResourceBundle) element).getFiles()) {
- if (RBFileUtils.hasResourceBundleMarker(f)) {
- return true;
- }
- }
- }
- if (element instanceof IContainer) {
- try {
- IMarker[] ms = null;
- if ((ms = ((IContainer) element).findMarkers(
- EditorUtils.RB_MARKER_ID, true,
- IResource.DEPTH_INFINITE)).length > 0) {
- return true;
- }
+ if (element instanceof IFile) {
+ return true;
+ }
+ if (element instanceof VirtualResourceBundle) {
+ for (IResource f : ((VirtualResourceBundle) element).getFiles()) {
+ if (RBFileUtils.hasResourceBundleMarker(f)) {
+ return true;
+ }
+ }
+ }
+ if (element instanceof IContainer) {
+ try {
+ IMarker[] ms = null;
+ if ((ms = ((IContainer) element).findMarkers(
+ EditorUtils.RB_MARKER_ID, true,
+ IResource.DEPTH_INFINITE)).length > 0) {
+ return true;
+ }
- List<IContainer> fragmentContainer = ResourceUtils
- .getCorrespondingFolders((IContainer) element,
- FragmentProjectUtils
- .getFragments(((IContainer) element)
- .getProject()));
+ List<IContainer> fragmentContainer = ResourceUtils
+ .getCorrespondingFolders((IContainer) element,
+ FragmentProjectUtils
+ .getFragments(((IContainer) element)
+ .getProject()));
- IMarker[] fragment_ms;
- for (IContainer c : fragmentContainer) {
- try {
- if (c.exists()) {
- fragment_ms = c.findMarkers(
- EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
- ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils
- .concatMarkerArray(ms, fragment_ms);
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- if (ms.length > 0) {
- return true;
- }
+ IMarker[] fragment_ms;
+ for (IContainer c : fragmentContainer) {
+ try {
+ if (c.exists()) {
+ fragment_ms = c.findMarkers(
+ EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils
+ .concatMarkerArray(ms, fragment_ms);
+ }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ if (ms.length > 0) {
+ return true;
+ }
- } catch (CoreException e) {
- }
- }
- return false;
+ } catch (CoreException e) {
+ }
+ }
+ return false;
}
}