JAL-3261 no save in setColourPropertyNoSave !
[jalview.git] / src / jalview / bin / Cache.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.bin;
22
23 import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
24 import jalview.datamodel.PDBEntry;
25 import jalview.gui.Preferences;
26 import jalview.schemes.ColourSchemeLoader;
27 import jalview.schemes.ColourSchemes;
28 import jalview.schemes.UserColourScheme;
29 import jalview.structure.StructureImportSettings;
30 import jalview.urls.IdOrgSettings;
31 import jalview.util.ColorUtils;
32 import jalview.util.Platform;
33 import jalview.ws.sifts.SiftsSettings;
34
35 import java.awt.Color;
36 import java.awt.Dimension;
37 import java.io.BufferedReader;
38 import java.io.File;
39 import java.io.FileInputStream;
40 import java.io.FileOutputStream;
41 import java.io.InputStream;
42 import java.io.InputStreamReader;
43 import java.text.DateFormat;
44 import java.text.SimpleDateFormat;
45 import java.util.Collections;
46 import java.util.Date;
47 import java.util.Enumeration;
48 import java.util.Locale;
49 import java.util.Properties;
50 import java.util.StringTokenizer;
51 import java.util.TreeSet;
52
53 import org.apache.log4j.ConsoleAppender;
54 import org.apache.log4j.Level;
55 import org.apache.log4j.Logger;
56 import org.apache.log4j.SimpleLayout;
57
58 /**
59  * Stores and retrieves Jalview Application Properties Lists and fields within
60  * list entries are separated by '|' symbols unless otherwise stated (|) clauses
61  * are alternative values for a tag. <br>
62  * <br>
63  * Current properties include:
64  * <ul>
65  * <br>
66  * logs.Axis.Level - one of the stringified Levels for log4j controlling the
67  * logging level for axis (used for web services) <br>
68  * </li>
69  * <li>logs.Castor.Level - one of the stringified Levels for log4j controlling
70  * the logging level for castor (used for serialization) <br>
71  * </li>
72  * <li>logs.Jalview.Level - Cache.log stringified level. <br>
73  * </li>
74  * <li>SCREEN_WIDTH</li>
75  * <li>SCREEN_HEIGHT</li>
76  * <li>SCREEN_Y=285</li>
77  * <li>SCREEN_X=371</li>
78  * <li>SHOW_FULLSCREEN boolean</li>
79  * <li>FONT_NAME java font name for alignment text display</li>
80  * <li>FONT_SIZE size of displayed alignment text</li>
81  * <li>FONT_STYLE style of font displayed (sequence labels are always
82  * italic)</li>
83  * <li>GAP_SYMBOL character to treat as gap symbol (usually -,.,' ')</li>
84  * <li>LAST_DIRECTORY last directory for browsing alignment</li>
85  * <li>USER_DEFINED_COLOURS list of user defined colour scheme files</li>
86  * <li>SHOW_FULL_ID show id with '/start-end' numbers appended</li>
87  * <li>SHOW_IDENTITY show percentage identity annotation</li>
88  * <li>SHOW_QUALITY show alignment quality annotation</li>
89  * <li>SHOW_ANNOTATIONS show alignment annotation rows</li>
90  * <li>SHOW_CONSERVATION show alignment conservation annotation</li>
91  * <li>SORT_ANNOTATIONS currently either SEQUENCE_AND_LABEL or
92  * LABEL_AND_SEQUENCE</li>
93  * <li>SHOW_AUTOCALC_ABOVE true to show autocalculated annotations above
94  * sequence annotations</li>
95  * <li>CENTRE_COLUMN_LABELS centre the labels at each column in a displayed
96  * annotation row</li>
97  * <li>DEFAULT_COLOUR default colour scheme to apply for a new alignment</li>
98  * <li>DEFAULT_FILE_FORMAT file format used to save</li>
99  * <li>STARTUP_FILE file loaded on startup (may be a fully qualified url)</li>
100  * <li>SHOW_STARTUP_FILE flag to control loading of startup file</li>
101  * <li>VERSION the version of the jalview build</li>
102  * <li>BUILD_DATE date of this build</li>
103  * <li>LATEST_VERSION the latest jalview version advertised on the
104  * www.jalview.org</li>
105  * <li>PIR_MODELLER boolean indicating if PIR files are written with MODELLER
106  * descriptions</li>
107  * <li>(FASTA,MSF,PILEUP,CLUSTAL,BLC,PIR,PFAM)_JVSUFFIX boolean for adding jv
108  * suffix to file</li>
109  * <li>RECENT_URL list of recently retrieved URLs</li>
110  * <li>RECENT_FILE list of recently opened files</li>
111  * <li>USE_PROXY flag for whether a http proxy is to be used</li>
112  * <li>PROXY_SERVER the proxy</li>
113  * <li>PROXY_PORT</li>
114  * <li>NOQUESTIONNAIRES true to prevent jalview from checking the questionnaire
115  * service</li>
116  * <li>QUESTIONNAIRE last questionnaire:responder id string from questionnaire
117  * service</li>
118  * <li>USAGESTATS (false - user prompted) Enable google analytics tracker for
119  * collecting usage statistics</li>
120  * <li>SHOW_OVERVIEW boolean for overview window display</li>
121  * <li>ANTI_ALIAS boolean for smooth fonts</li>
122  * <li>RIGHT_ALIGN_IDS boolean</li>
123  * <li>AUTO_CALC_CONSENSUS boolean for automatic recalculation of consensus</li>
124  * <li>PAD_GAPS boolean</li>
125  * <li>ID_ITALICS boolean</li>
126  * <li>SHOW_JV_SUFFIX</li>
127  * <li>WRAP_ALIGNMENT</li>
128  * <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
129  * style check</li>
130  * <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
131  * <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
132  * $SEQUENCE_ID$</li>
133  * <li>STORED_LINKS list of name|url pairs which user has entered but are not
134  * currently used
135  * <li>DEFAULT_LINK name of single url to be used when user double clicks a
136  * sequence id (must be in SEQUENCE_LINKS or STORED_LINKS)
137  * <li>GROUP_LINKS list of name|URL[|&lt;separator&gt;] tuples - see
138  * jalview.utils.GroupURLLink for more info</li>
139  * <li>DEFAULT_BROWSER for unix</li>
140  * <li>SHOW_MEMUSAGE boolean show memory usage and warning indicator on desktop
141  * (false)</li>
142  * <li>VERSION_CHECK (true) check for the latest release version from
143  * www.jalview.org (or the alias given by the www.jalview.org property)</li>
144  * <li>SHOW_NPFEATS_TOOLTIP (true) show non-positional features in the Sequence
145  * ID tooltip</li>
146  * <li>SHOW_DBREFS_TOOLTIP (true) show Database Cross References in the Sequence
147  * ID tooltip</li>
148  * <li>SHOW_UNCONSERVED (false) only render unconserved residues - conserved
149  * displayed as '.'</li>
150  * <li>SORT_BY_TREE (false) sort the current alignment view according to the
151  * order of a newly displayed tree</li>
152  * <li>DBFETCH_USEPICR (false) use PICR to recover valid DB references from
153  * sequence ID strings before attempting retrieval from any datasource</li>
154  * <li>SHOW_GROUP_CONSENSUS (false) Show consensus annotation for groups in the
155  * alignment.</li>
156  * <li>SHOW_GROUP_CONSERVATION (false) Show conservation annotation for groups
157  * in the alignment.</li>
158  * <li>SHOW_CONSENSUS_HISTOGRAM (false) Show consensus annotation row's
159  * histogram.</li>
160  * <li>SHOW_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
161  * logo.</li>
162  * <li>NORMALISE_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
163  * logo normalised to row height rather than histogram height.</li>
164  * <li>FOLLOW_SELECTIONS (true) Controls whether a new alignment view should
165  * respond to selections made in other alignments containing the same sequences.
166  * </li>
167  * <li>JWS2HOSTURLS comma-separated list of URLs to try for JABAWS services</li>
168  * <li>SHOW_WSDISCOVERY_ERRORS (true) Controls if the web service URL discovery
169  * warning dialog box is displayed.</li>
170  * <li>ANNOTATIONCOLOUR_MIN (orange) Shade used for minimum value of annotation
171  * when shading by annotation</li>
172  * <li>ANNOTATIONCOLOUR_MAX (red) Shade used for maximum value of annotation
173  * when shading by annotation</li>
174  * <li>www.jalview.org (http://www.jalview.org) a property enabling all HTTP
175  * requests to be redirected to a mirror of http://www.jalview.org</li>
176  * <li>FIGURE_AUTOIDWIDTH (false) Expand the left hand column of an exported
177  * alignment figure to accommodate even the longest sequence ID or annotation
178  * label.</li>
179  * <li>FIGURE_FIXEDIDWIDTH Specifies the width to use for the left-hand column
180  * when exporting an alignment as a figure (setting FIGURE_AUTOIDWIDTH to true
181  * will override this).</li>
182  * <li>STRUCT_FROM_PDB (false) derive secondary structure annotation from PDB
183  * record</li>
184  * <li>USE_RNAVIEW (false) use RNAViewer to derive secondary structure</li>
185  * <li>ADD_SS_ANN (false) add secondary structure annotation to alignment
186  * display</li>
187  * <li>ADD_TEMPFACT_ANN (false) add Temperature Factor annotation to alignment
188  * display</li>
189  * <li>STRUCTURE_DISPLAY choose from JMOL (default) or CHIMERA for 3D structure
190  * display</li>
191  * <li>CHIMERA_PATH specify full path to Chimera program (if non-standard)</li>
192  * <li>ID_ORG_HOSTURL location of jalview service providing identifiers.org urls
193  * </li>
194  * 
195  * </ul>
196  * Deprecated settings:
197  * <ul>
198  * *
199  * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
200  * startup (JWS1 services only)</li>
201  * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints.
202  * (JWS1 services only)</li>
203  * <li>SHOW_JWS1_SERVICES (true) enable or disable the original Jalview 2
204  * services in the desktop GUI</li>
205  * <li>ENABLE_RSBS_EDITOR (false for 2.7 release) enable or disable RSBS editing
206  * panel in web service preferences</li>
207  * </ul>
208  * 
209  */
210 public class Cache implements ApplicationSingletonI
211 {
212
213   private Cache()
214   {
215     // private singleton
216   }
217
218   /**
219    * In Java, this will be a static field instance, which will be
220    * application-specific; in JavaScript it will be an applet-specific instance
221    * tied to the applet's ThreadGroup.
222    * 
223    * @return
224    */
225   public static Cache getInstance()
226   {
227     return (Cache) ApplicationSingletonProvider.getInstance(Cache.class);
228   }
229
230   /**
231    * property giving log4j level for CASTOR loggers
232    */
233   public static final String CASTORLOGLEVEL = "logs.Castor.level";
234
235   /**
236    * property giving log4j level for AXIS loggers
237    */
238   public static final String AXISLOGLEVEL = "logs.Axis.level";
239
240   /**
241    * property giving log4j level for Jalview Log
242    */
243   public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
244
245   /**
246    * Sifts settings
247    */
248   public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = System
249           .getProperty("user.home") + File.separatorChar
250           + ".sifts_downloads" + File.separatorChar;
251
252   private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
253
254   private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
255
256   /**
257    * Identifiers.org download settings
258    */
259   private static final String ID_ORG_FILE = System.getProperty("user.home")
260           + File.separatorChar + ".identifiers.org.ids.json";
261
262   /**
263    * Allowed values are PDB or mmCIF
264    */
265   private final static String PDB_DOWNLOAD_FORMAT = PDBEntry.Type.MMCIF
266           .toString();
267
268   private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
269           .toString();
270
271   /*
272    * a date formatter using a fixed (rather than the user's) locale; 
273    * this ensures that date properties can be written and re-read successfully
274    * even if the user changes their locale setting
275    */
276   private static final DateFormat date_format = SimpleDateFormat
277           .getDateTimeInstance(SimpleDateFormat.MEDIUM,
278                   SimpleDateFormat.MEDIUM, Locale.UK);
279
280   /**
281    * Initialises the Jalview Application Log
282    */
283   public static Logger log;
284
285   /** Jalview Properties */
286   // BH 2019.05.08 was static
287   @SuppressWarnings("serial")
288   public Properties applicationProperties = new Properties()
289   {
290     // override results in properties output in alphabetical order
291     @Override
292     public synchronized Enumeration<Object> keys()
293     {
294       return Collections.enumeration(new TreeSet<>(super.keySet()));
295     }
296   };
297
298   /** Default file is ~/.jalview_properties */
299   private String propertiesFile;
300
301   /**
302    * flag to possibly allow properties to be written to a property file
303    */
304   private boolean propsAreReadOnly = Platform.isJS();
305
306   private final static String JS_PROPERTY_PREFIX = "jalview_";
307
308   public static void initLogger()
309   {
310     if (log != null)
311     {
312       return;
313     }
314     try
315     {
316       // TODO: redirect stdout and stderr here in order to grab the output of
317       // the log
318
319       ConsoleAppender ap = new ConsoleAppender(new SimpleLayout(),
320               "System.err");
321       ap.setName("JalviewLogger");
322       org.apache.log4j.Logger.getRootLogger().addAppender(ap); // catch all for
323       // log output
324       Logger laxis = Logger.getLogger("org.apache.axis");
325       Logger lcastor = Logger.getLogger("org.exolab.castor");
326       jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
327
328       laxis.setLevel(Level.toLevel(
329               getDefault("logs.Axis.Level", Level.INFO.toString())));
330       lcastor.setLevel(Level.toLevel(
331               getDefault("logs.Castor.Level", Level.INFO.toString())));
332       lcastor = Logger.getLogger("org.exolab.castor.xml");
333       lcastor.setLevel(Level.toLevel(
334               getDefault("logs.Castor.Level", Level.INFO.toString())));
335       // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
336       // lcastor.setLevel(Level.toLevel(getDefault("logs.Castor.Level",
337       // Level.INFO.toString())));
338       jalview.bin.Cache.log.setLevel(Level.toLevel(Cache
339               .getDefault("logs.Jalview.level", Level.INFO.toString())));
340       // laxis.addAppender(ap);
341       // lcastor.addAppender(ap);
342       // jalview.bin.Cache.log.addAppender(ap);
343       // Tell the user that debug is enabled
344       jalview.bin.Cache.log.debug("Jalview Debugging Output Follows.");
345     } catch (Exception ex)
346     {
347       System.err.println("Problems initializing the log4j system\n");
348       ex.printStackTrace(System.err);
349     }
350   }
351
352   /**
353    * Loads properties from the given properties file. Any existing properties
354    * are first cleared.
355    */
356   public static void loadProperties(String propsFile)
357   {
358     getInstance().loadPropertiesImpl(propsFile);
359   }
360
361   private void loadPropertiesImpl(String propsFile)
362   {
363     propertiesFile = propsFile;
364     if (!propsAreReadOnly)
365     {
366       // Java only
367       if (propsFile == null)
368       {
369         propertiesFile = System.getProperty("user.home")
370                 + File.separatorChar + ".jalview_properties";
371       }
372       else
373       {
374         // don't corrupt the file we've been given.
375         propsAreReadOnly = true;
376       }
377     }
378
379     if (propertiesFile == null)
380     { // BH 2019 read properties from the Info object associated with this
381       // applet
382       Platform.readInfoProperties(JS_PROPERTY_PREFIX,
383               applicationProperties);
384     }
385     else
386     {
387       try
388       {
389         InputStream fis;
390         try
391         {
392           fis = new java.net.URL(propertiesFile).openStream();
393           System.out.println(
394                   "Loading jalview properties from : " + propertiesFile);
395           System.out.println(
396                   "Disabling Jalview writing to user's local properties file.");
397           propsAreReadOnly = true;
398
399         } catch (Exception ex)
400         {
401           fis = null;
402         }
403         if (fis == null)
404         {
405           fis = new FileInputStream(propertiesFile);
406         }
407         applicationProperties.clear();
408         applicationProperties.load(fis);
409
410         // remove any old build properties
411
412         deleteBuildProperties();
413         fis.close();
414       } catch (Exception ex)
415       {
416         System.out.println("Error reading properties file: " + ex);
417       }
418     }
419     if (getDefault("USE_PROXY", false))
420     {
421       String proxyServer = getDefault("PROXY_SERVER", ""),
422               proxyPort = getDefault("PROXY_PORT", "8080");
423
424       System.out.println("Using proxyServer: " + proxyServer
425               + " proxyPort: " + proxyPort);
426
427       System.setProperty("http.proxyHost", proxyServer);
428       System.setProperty("http.proxyPort", proxyPort);
429     }
430
431     // LOAD THE AUTHORS FROM THE authors.props file
432     String authorDetails = (Platform.isJS() ? null
433             : "jar:".concat(Cache.class.getProtectionDomain()
434                     .getCodeSource().getLocation().toString()
435                     .concat("!/authors.props")));
436
437     try
438     {
439       if (authorDetails != null)
440       {
441         java.net.URL localJarFileURL = new java.net.URL(authorDetails);
442         InputStream in = localJarFileURL.openStream();
443         applicationProperties.load(in);
444         in.close();
445       }
446     } catch (Exception ex)
447     {
448       System.out.println("Error reading author details: " + ex);
449       authorDetails = null;
450     }
451     if (authorDetails == null)
452     {
453       applicationProperties.remove("AUTHORS");
454       applicationProperties.remove("AUTHORFNAMES");
455       applicationProperties.remove("YEAR");
456     }
457
458     // FIND THE VERSION NUMBER AND BUILD DATE FROM jalview.jar
459     // MUST FOLLOW READING OF LOCAL PROPERTIES FILE AS THE
460     // VERSION MAY HAVE CHANGED SINCE LAST USING JALVIEW
461     String buildDetails = (Platform.isJS() ? null
462             : "jar:".concat(Cache.class.getProtectionDomain()
463                     .getCodeSource().getLocation().toString()
464                     .concat("!/.build_properties")));
465     if (buildDetails != null)
466     {
467       try
468       {
469         java.net.URL localJarFileURL = new java.net.URL(buildDetails);
470         InputStream in = localJarFileURL.openStream();
471         applicationProperties.load(in);
472         in.close();
473       } catch (Exception ex)
474       {
475         System.out.println("Error reading build details: " + ex);
476         buildDetails = null;
477       }
478     }
479     if (buildDetails == null)
480     {
481       applicationProperties.remove("VERSION");
482     }
483     String jnlpVersion = System.getProperty("jalview.version");
484     String codeVersion = getProperty("VERSION");
485     String codeInstallation = getProperty("INSTALLATION");
486     if (codeVersion == null)
487     {
488       // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
489       codeVersion = "Test";
490       jnlpVersion = "Test";
491       codeInstallation = "";
492     }
493     else
494     {
495       codeInstallation = " (" + codeInstallation + ")";
496     }
497     new BuildDetails(codeVersion, null, codeInstallation);
498
499     SiftsSettings.setMapWithSifts(getDefault("MAP_WITH_SIFTS", false));
500
501     SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache
502             .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
503
504     SiftsSettings.setFailSafePIDThreshold(
505             getDefault("sifts_fail_safe_pid_threshold",
506                     DEFAULT_FAIL_SAFE_PID_THRESHOLD));
507
508     SiftsSettings.setCacheThresholdInDays(
509             getDefault("sifts_cache_threshold_in_days",
510                     DEFAULT_CACHE_THRESHOLD_IN_DAYS));
511
512     IdOrgSettings.setUrl(getDefault(Preferences.ID_ORG_HOSTURL,
513             "http://www.jalview.org/services/identifiers"));
514     IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
515
516     System.out
517             .println("Jalview Version: " + codeVersion + codeInstallation);
518
519     StructureImportSettings.setDefaultStructureFileFormat(jalview.bin.Cache
520             .getDefault(Preferences.PDB_DOWNLOAD_FORMAT, PDB_DOWNLOAD_FORMAT));
521     StructureImportSettings
522             .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
523     // StructureImportSettings
524     // .setDefaultPDBFileParser(jalview.bin.getDefault(
525     // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
526     // jnlpVersion will be null if we're using InstallAnywhere
527     // Dont do this check if running in headless mode
528     if (jnlpVersion == null && !Jalview.isHeadlessMode()
529             && getDefault("VERSION_CHECK", true))
530     {
531
532       class VersionChecker extends Thread
533       {
534         @Override
535         public void run()
536         {
537           String orgtimeout = System
538                   .getProperty("sun.net.client.defaultConnectTimeout");
539           if (orgtimeout == null)
540           {
541             orgtimeout = "30";
542             System.out.println("# INFO: Setting default net timeout to "
543                     + orgtimeout + " seconds.");
544           }
545           String remoteVersion = null;
546           try
547           {
548             System.setProperty("sun.net.client.defaultConnectTimeout",
549                     "5000");
550             java.net.URL url = new java.net.URL(Cache
551                     .getDefault("www.jalview.org", "http://www.jalview.org")
552                     + "/webstart/jalview.jnlp");
553             BufferedReader in = new BufferedReader(
554                     new InputStreamReader(url.openStream()));
555             String line = null;
556             while ((line = in.readLine()) != null)
557             {
558               if (line.indexOf("jalview.version") == -1)
559               {
560                 continue;
561               }
562
563               line = line.substring(line.indexOf("value=") + 7);
564               line = line.substring(0, line.lastIndexOf("\""));
565               remoteVersion = line;
566               break;
567             }
568           } catch (Exception ex)
569           {
570             System.out.println(
571                     "Non-fatal exception when checking version at www.jalview.org :");
572             System.out.println(ex);
573             remoteVersion = getProperty("VERSION");
574           }
575           System.setProperty("sun.net.client.defaultConnectTimeout",
576                   orgtimeout);
577
578           setProperty("LATEST_VERSION", remoteVersion);
579         }
580       }
581
582       VersionChecker vc = new VersionChecker();
583       vc.start();
584     }
585     else
586     {
587       if (jnlpVersion != null)
588       {
589         setProperty("LATEST_VERSION", jnlpVersion);
590       }
591       else
592       {
593         applicationProperties.remove("LATEST_VERSION");
594       }
595     }
596
597     setProperty("VERSION", codeVersion);
598
599     // LOAD USERDEFINED COLOURS
600     initUserColourSchemes(getProperty(Preferences.USER_DEFINED_COLOURS));
601   }
602
603   private void deleteBuildProperties()
604   {
605     applicationProperties.remove("LATEST_VERSION");
606     applicationProperties.remove("VERSION");
607     applicationProperties.remove("AUTHORS");
608     applicationProperties.remove("AUTHORFNAMES");
609     applicationProperties.remove("YEAR");
610     applicationProperties.remove("BUILD_DATE");
611     applicationProperties.remove("INSTALLATION");
612   }
613
614   /**
615    * Gets Jalview application property of given key. Returns null if key not
616    * found
617    * 
618    * @param key
619    *          Name of property
620    * 
621    * @return Property value
622    */
623   public static String getProperty(String key)
624   {
625     return getInstance().applicationProperties.getProperty(key);
626   }
627
628   /**
629    * Returns the boolean property value for the given property name. If the
630    * value is absent then the default value is returned instead.
631    * 
632    * @param property
633    * @param def
634    * @return
635    */
636   public static boolean getDefault(String property, final boolean def)
637   {
638     String string = getProperty(property);
639     return string == null ? def : Boolean.parseBoolean(string);
640   }
641
642   /**
643    * Returns the integer property value for the given property name. If the
644    * value is absent, or malformed (not an integer), then the default value is
645    * returned instead.
646    * 
647    * @param property
648    * @param def
649    * @return
650    */
651   public static int getDefault(String property, final int def)
652   {
653     String string = getProperty(property);
654     if (string != null)
655     {
656       try
657       {
658         return Integer.parseInt(string);
659       } catch (NumberFormatException e)
660       {
661         System.out.println("Error parsing int property '" + property
662                 + "' with value '" + string + "'");
663       }
664     }
665
666     return def;
667   }
668
669   /**
670    * retrieve a dimension, such as for Jmol
671    * 
672    * @param property
673    * @param def
674    * @return
675    */
676   public static Dimension getDefaultDim(String property, Dimension def)
677   {
678     String s = getProperty(property);
679     if (s != null)
680     {
681       if (s.indexOf(',') < 0)
682       {
683         s = s.trim().replace(' ', ',');
684         if (s.indexOf(',') < 0)
685         {
686           s += "," + s;
687         }
688       }
689       try
690       {
691         int pt = s.indexOf(",");
692         return new Dimension(Integer.parseInt(s.substring(0, pt)),
693                 Integer.parseInt(s.substring(pt + 1)));
694       } catch (NumberFormatException e)
695       {
696         System.out.println("Error parsing Dimension property '" + property
697                 + "' with value '" + s + "'");
698       }
699     }
700     return def;
701   }
702
703   /**
704    * Returns the value of the given property, or the supplied default value if
705    * the property is not set
706    * 
707    * @param property
708    * @param def
709    * @return
710    */
711   public static String getDefault(String property, final String def)
712   {
713     String value = getProperty(property);
714     return value == null ? def : value;
715   }
716
717   /**
718    * Stores property in the file "HOME_DIR/.jalview_properties"
719    * 
720    * @param key
721    *          Name of object
722    * @param obj
723    *          String value of property
724    * 
725    * @return previous value of property (or null)
726    */
727   public static Object setProperty(String key, String obj)
728   {
729     return getInstance().setPropertyImpl(key, obj, true);
730   }
731
732   /**
733    * Sets a property value for the running application, without saving it to the
734    * properties file
735    * 
736    * @param key
737    * @param obj
738    */
739   public static void setPropertyNoSave(String key, String obj)
740   {
741     getInstance().setPropertyImpl(key, obj, false);
742   }
743
744   /**
745    * Sets a property value, and optionally also saves the current properties to
746    * file
747    * 
748    * @param key
749    * @param obj
750    * @param andSave
751    * @return
752    */
753   private Object setPropertyImpl(String key, String obj, boolean andSave)
754   {
755     Object oldValue = null;
756     try
757     {
758       oldValue = applicationProperties.setProperty(key, obj);
759       if (andSave && !propsAreReadOnly && propertiesFile != null)
760       {
761         FileOutputStream out = new FileOutputStream(propertiesFile);
762         applicationProperties.store(out, "---JalviewX Properties File---");
763         out.close();
764       }
765     } catch (Exception ex)
766     {
767       System.out.println(
768               "Error setting property: " + key + " " + obj + "\n" + ex);
769     }
770     return oldValue;
771   }
772
773   /**
774    * Removes the specified property from the jalview properties file
775    * 
776    * @param key
777    */
778   public static void removeProperty(String key)
779   {
780     getInstance().removePropertyImpl(key, true);
781   }
782
783   /**
784    * Removes the named property for the running application, without saving the
785    * properties file
786    * 
787    * @param key
788    */
789   public static void removePropertyNoSave(String key)
790   {
791     getInstance().removePropertyImpl(key, false);
792   }
793
794   /**
795    * Removes the named property, and optionally saves the current properties to
796    * file
797    * 
798    * @param key
799    * @param andSave
800    */
801   private void removePropertyImpl(String key, boolean andSave)
802   {
803     applicationProperties.remove(key);
804     if (andSave)
805     {
806       savePropertiesImpl();
807     }
808   }
809
810   /**
811    * Saves the current properties to file
812    */
813   public static void saveProperties()
814   {
815     getInstance().savePropertiesImpl();
816   }
817
818   /**
819    * save the properties to the jalview properties path
820    */
821   private void savePropertiesImpl()
822   {
823     if (!propsAreReadOnly)
824     {
825       try
826       {
827         FileOutputStream out = new FileOutputStream(propertiesFile);
828         applicationProperties.store(out, "---JalviewX Properties File---");
829         out.close();
830       } catch (Exception ex)
831       {
832         System.out.println("Error saving properties: " + ex);
833       }
834     }
835   }
836
837   private final static int UNTESTED = -1;
838
839   private final static int TRUE = 1;
840
841   private final static int FALSE = 0;
842
843   /**
844    * internal vamsas class discovery state
845    */
846   private static int vamsasJarsArePresent = (Platform.isJS() ? FALSE
847           : UNTESTED);
848
849   /**
850    * Searches for vamsas client classes on class path.
851    * 
852    * @return true if vamsas client is present on classpath
853    */
854   public static boolean vamsasJarsPresent()
855   {
856     if (vamsasJarsArePresent == UNTESTED)
857     {
858       try
859       {
860         if (jalview.jbgui.GDesktop.class.getClassLoader()
861                 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
862         {
863           jalview.bin.Cache.log.debug(
864                   "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
865           vamsasJarsArePresent = TRUE;
866           Logger lvclient = Logger.getLogger("uk.ac.vamsas");
867           lvclient.setLevel(Level.toLevel(Cache
868                   .getDefault("logs.Vamsas.Level", Level.INFO.toString())));
869
870           lvclient.addAppender(log.getAppender("JalviewLogger"));
871           // Tell the user that debug is enabled
872           lvclient.debug("Jalview Vamsas Client Debugging Output Follows.");
873         }
874       } catch (Exception e)
875       {
876         vamsasJarsArePresent = FALSE;
877         jalview.bin.Cache.log.debug("Vamsas Classes are not present");
878       }
879     }
880     return (vamsasJarsArePresent == TRUE);
881   }
882
883   /**
884    * internal vamsas class discovery state
885    */
886   private static int groovyJarsArePresent = (Platform.isJS() ? FALSE
887           : UNTESTED);
888
889   /**
890    * Searches for vamsas client classes on class path.
891    * 
892    * @return true if vamsas client is present on classpath
893    */
894   public static boolean groovyJarsPresent()
895   {
896     if (groovyJarsArePresent == UNTESTED)
897     {
898       try
899       {
900         if (Cache.class.getClassLoader()
901                 .loadClass("groovy.lang.GroovyObject") != null)
902         {
903           jalview.bin.Cache.log.debug(
904                   "Found Groovy (groovy.lang.GroovyObject can be loaded)");
905           groovyJarsArePresent = TRUE;
906           Logger lgclient = Logger.getLogger("groovy");
907           lgclient.setLevel(Level.toLevel(Cache
908                   .getDefault("logs.Groovy.Level", Level.INFO.toString())));
909
910           lgclient.addAppender(log.getAppender("JalviewLogger"));
911           // Tell the user that debug is enabled
912           lgclient.debug("Jalview Groovy Client Debugging Output Follows.");
913         }
914       } catch (Error e)
915       {
916         groovyJarsArePresent = FALSE;
917         jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
918       } catch (Exception e)
919       {
920         groovyJarsArePresent = FALSE;
921         jalview.bin.Cache.log.debug("Groovy Classes are not present");
922       }
923     }
924     return (groovyJarsArePresent == TRUE);
925   }
926
927   /**
928    * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
929    * enabled.
930    */
931   protected static Object tracker = null;
932
933   protected static Class<?> trackerfocus = null;
934
935   protected static Class<?> jgoogleanalyticstracker = null;
936
937   /**
938    * Initialise the google tracker if it is not done already.
939    */
940   public static void initGoogleTracker()
941   {
942
943     // TODO: SwingJS JavaScript tracker?
944
945     if (tracker == null)
946     {
947       if (jgoogleanalyticstracker == null)
948       {
949         // try to get the tracker class
950         try
951         {
952           jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
953                   "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
954           trackerfocus = Cache.class.getClassLoader()
955                   .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
956         } catch (Exception e)
957         {
958           log.debug(
959                   "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
960           tracker = null;
961           jgoogleanalyticstracker = null;
962           trackerfocus = null;
963           return;
964         }
965       }
966       // now initialise tracker
967       Exception re = null, ex = null;
968       Error err = null;
969       String vrs = "No Version Accessible";
970       try
971       {
972         // Google analytics tracking code for Library Finder
973         tracker = jgoogleanalyticstracker
974                 .getConstructor(new Class[]
975                 { String.class, String.class, String.class })
976                 .newInstance(new Object[]
977                 { "Jalview Desktop",
978                     (vrs = jalview.bin.Cache.getProperty("VERSION") + "_"
979                             + getDefault("BUILD_DATE", "unknown")),
980                     "UA-9060947-1" });
981         jgoogleanalyticstracker
982                 .getMethod("trackAsynchronously", new Class[]
983                 { trackerfocus })
984                 .invoke(tracker, new Object[]
985                 { trackerfocus.getConstructor(new Class[] { String.class })
986                         .newInstance(new Object[]
987                         { "Application Started." }) });
988       } catch (RuntimeException e)
989       {
990         re = e;
991       } catch (Exception e)
992       {
993         ex = e;
994       } catch (Error e)
995       {
996         err = e;
997       }
998       if (re != null || ex != null || err != null)
999       {
1000         if (log != null)
1001         {
1002           if (re != null)
1003           {
1004             log.debug("Caught runtime exception in googletracker init:",
1005                     re);
1006           }
1007           if (ex != null)
1008           {
1009             log.warn(
1010                     "Failed to initialise GoogleTracker for Jalview Desktop with version "
1011                             + vrs,
1012                     ex);
1013           }
1014           if (err != null)
1015           {
1016             log.error(
1017                     "Whilst initing GoogleTracker for Jalview Desktop version "
1018                             + vrs,
1019                     err);
1020           }
1021         }
1022         else
1023         {
1024           if (re != null)
1025           {
1026             System.err.println(
1027                     "Debug: Caught runtime exception in googletracker init:"
1028                             + vrs);
1029             re.printStackTrace();
1030           }
1031           if (ex != null)
1032           {
1033             System.err.println(
1034                     "Warning:  Failed to initialise GoogleTracker for Jalview Desktop with version "
1035                             + vrs);
1036             ex.printStackTrace();
1037           }
1038
1039           if (err != null)
1040           {
1041             System.err.println(
1042                     "ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
1043                             + vrs);
1044             err.printStackTrace();
1045           }
1046         }
1047       }
1048       else
1049       {
1050         log.debug("Successfully initialised tracker.");
1051       }
1052     }
1053   }
1054
1055   /**
1056    * Returns the Color value of the given property's value, or the supplied
1057    * default colour if no property is found, or it cannot be parsed to a colour.
1058    * Colours are normally saved as hex rgb values, though other formats may be
1059    * parseable.
1060    * 
1061    * @param property
1062    * @param defaultColour
1063    * @return
1064    * @see Cache#setColourPropertyNoSave(String, Color)
1065    * @see ColorUtils#parseColourString(String)
1066    */
1067   public static Color getDefaultColour(String property,
1068           final Color defaultColour)
1069   {
1070     String colprop = getProperty(property);
1071     if (colprop == null)
1072     {
1073       return defaultColour;
1074     }
1075     Color col = ColorUtils.parseColourString(colprop);
1076     if (col == null)
1077     {
1078       log.warn("Couldn't parse '" + colprop + "' as a colour for "
1079               + property);
1080     }
1081     return (col == null) ? defaultColour : col;
1082   }
1083
1084   /**
1085    * Stores a colour as a Jalview property, converted to hex values for rgb.
1086    * Properties are not saved to file.
1087    * 
1088    * @param property
1089    * @param colour
1090    */
1091   public static void setColourPropertyNoSave(String property, Color colour)
1092   {
1093     setPropertyNoSave(property, jalview.util.Format.getHexString(colour));
1094   }
1095
1096   /**
1097    * Stores a formatted date in a jalview property, using a fixed locale.
1098    * Updated properties are written out to the properties file.
1099    * 
1100    * @param propertyName
1101    * @param date
1102    * @return the formatted date string
1103    */
1104   public static String setDateProperty(String propertyName, Date date)
1105   {
1106     String formatted = date_format.format(date);
1107     setProperty(propertyName, formatted);
1108     return formatted;
1109   }
1110
1111   /**
1112    * Reads a date stored in a Jalview property, parses it (using a fixed locale
1113    * format) and returns as a Date, or null if parsing fails
1114    * 
1115    * @param propertyName
1116    * @return
1117    * 
1118    */
1119   public static Date getDateProperty(String propertyName)
1120   {
1121     String val = getProperty(propertyName);
1122     if (val != null)
1123     {
1124       try
1125       {
1126         return date_format.parse(val);
1127       } catch (Exception ex)
1128       {
1129         System.err.println("Invalid or corrupt date in property '"
1130                 + propertyName + "' : value was '" + val + "'");
1131       }
1132     }
1133     return null;
1134   }
1135
1136   /**
1137    * get and parse a property as an integer. send any parsing problems to
1138    * System.err
1139    * 
1140    * @param property
1141    * @return null or Integer
1142    */
1143   public static Integer getIntegerProperty(String property)
1144   {
1145     String val = getProperty(property);
1146     if (val != null && (val = val.trim()).length() > 0)
1147     {
1148       try
1149       {
1150         return Integer.valueOf(val);
1151       } catch (NumberFormatException x)
1152       {
1153         System.err.println("Invalid integer in property '" + property
1154                 + "' (value was '" + val + "')");
1155       }
1156     }
1157     return null;
1158   }
1159
1160   /**
1161    * Set the specified value, or remove it if null or empty. Does not save the
1162    * properties file.
1163    * 
1164    * @param propName
1165    * @param value
1166    */
1167   public static void setOrRemove(String propName, String value)
1168   {
1169     if (propName == null)
1170     {
1171       return;
1172     }
1173     if (value == null || value.trim().length() < 1)
1174     {
1175       getInstance().applicationProperties.remove(propName);
1176     }
1177     else
1178     {
1179       getInstance().applicationProperties.setProperty(propName, value);
1180     }
1181   }
1182
1183   /**
1184    * Loads in user colour schemes from files.
1185    * 
1186    * @param files
1187    *          a '|'-delimited list of file paths
1188    */
1189   public static void initUserColourSchemes(String files)
1190   {
1191     if (files == null || files.length() == 0)
1192     {
1193       return;
1194     }
1195
1196     // In case colours can't be loaded, we'll remove them
1197     // from the default list here.
1198     StringBuffer coloursFound = new StringBuffer();
1199     StringTokenizer st = new StringTokenizer(files, "|");
1200     while (st.hasMoreElements())
1201     {
1202       String file = st.nextToken();
1203       try
1204       {
1205         UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1206         if (ucs != null)
1207         {
1208           if (coloursFound.length() > 0)
1209           {
1210             coloursFound.append("|");
1211           }
1212           coloursFound.append(file);
1213           ColourSchemes.getInstance().registerColourScheme(ucs);
1214         }
1215       } catch (Exception ex)
1216       {
1217         System.out.println("Error loading User ColourFile\n" + ex);
1218       }
1219     }
1220     if (!files.equals(coloursFound.toString()))
1221     {
1222       if (coloursFound.toString().length() > 1)
1223       {
1224         setProperty(Preferences.USER_DEFINED_COLOURS,
1225                 coloursFound.toString());
1226       }
1227       else
1228       {
1229         getInstance().applicationProperties
1230                 .remove(Preferences.USER_DEFINED_COLOURS);
1231       }
1232     }
1233   }
1234
1235 }