JAL-3453
[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  * @author $author$
210  * @version $Revision$
211  */
212 public class Cache implements ApplicationSingletonI
213 {
214
215   private Cache()
216   {
217     // private singleton
218   }
219
220   /**
221    * In Java, this will be a static field instance, which will be
222    * application-specific; in JavaScript it will be an applet-specific instance
223    * tied to the applet's ThreadGroup.
224    * 
225    * @return
226    */
227   public static Cache getInstance()
228   {
229     return (Cache) ApplicationSingletonProvider.getInstance(Cache.class);
230   }
231
232   /**
233    * property giving log4j level for CASTOR loggers
234    */
235   public static final String CASTORLOGLEVEL = "logs.Castor.level";
236
237   /**
238    * property giving log4j level for AXIS loggers
239    */
240   public static final String AXISLOGLEVEL = "logs.Axis.level";
241
242   /**
243    * property giving log4j level for Jalview Log
244    */
245   public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
246
247   /**
248    * Sifts settings
249    */
250   public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = System
251           .getProperty("user.home") + File.separatorChar
252           + ".sifts_downloads" + File.separatorChar;
253
254   private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
255
256   private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
257
258   /**
259    * Identifiers.org download settings
260    */
261   private static final String ID_ORG_FILE = System.getProperty("user.home")
262           + File.separatorChar + ".identifiers.org.ids.json";
263
264   /**
265    * Allowed values are PDB or mmCIF
266    */
267   private final static String PDB_DOWNLOAD_FORMAT = PDBEntry.Type.MMCIF
268           .toString();
269
270   private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
271           .toString();
272
273   /*
274    * a date formatter using a fixed (rather than the user's) locale; 
275    * this ensures that date properties can be written and re-read successfully
276    * even if the user changes their locale setting
277    */
278   private static final DateFormat date_format = SimpleDateFormat
279           .getDateTimeInstance(SimpleDateFormat.MEDIUM,
280                   SimpleDateFormat.MEDIUM, Locale.UK);
281
282   /**
283    * Initialises the Jalview Application Log
284    */
285   public static Logger log;
286
287   /** Jalview Properties */
288   // BH 2019.05.08 was static
289   @SuppressWarnings("serial")
290   public Properties applicationProperties = new Properties()
291   {
292     // override results in properties output in alphabetical order
293     @Override
294     public synchronized Enumeration<Object> keys()
295     {
296       return Collections.enumeration(new TreeSet<>(super.keySet()));
297     }
298   };
299
300   /** Default file is ~/.jalview_properties */
301   private String propertiesFile;
302
303   /**
304    * flag to possibly allow properties to be written to a property file
305    */
306   private boolean propsAreReadOnly = Platform.isJS();
307
308   private final static String JS_PROPERTY_PREFIX = "jalview_";
309
310   public static void initLogger()
311   {
312     if (log != null)
313     {
314       return;
315     }
316     try
317     {
318       // TODO: redirect stdout and stderr here in order to grab the output of
319       // the log
320
321       ConsoleAppender ap = new ConsoleAppender(new SimpleLayout(),
322               "System.err");
323       ap.setName("JalviewLogger");
324       org.apache.log4j.Logger.getRootLogger().addAppender(ap); // catch all for
325       // log output
326       Logger laxis = Logger.getLogger("org.apache.axis");
327       Logger lcastor = Logger.getLogger("org.exolab.castor");
328       jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
329
330       laxis.setLevel(Level.toLevel(
331               getDefault("logs.Axis.Level", Level.INFO.toString())));
332       lcastor.setLevel(Level.toLevel(
333               getDefault("logs.Castor.Level", Level.INFO.toString())));
334       lcastor = Logger.getLogger("org.exolab.castor.xml");
335       lcastor.setLevel(Level.toLevel(
336               getDefault("logs.Castor.Level", Level.INFO.toString())));
337       // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
338       // lcastor.setLevel(Level.toLevel(getDefault("logs.Castor.Level",
339       // Level.INFO.toString())));
340       jalview.bin.Cache.log.setLevel(Level.toLevel(Cache
341               .getDefault("logs.Jalview.level", Level.INFO.toString())));
342       // laxis.addAppender(ap);
343       // lcastor.addAppender(ap);
344       // jalview.bin.Cache.log.addAppender(ap);
345       // Tell the user that debug is enabled
346       jalview.bin.Cache.log.debug("Jalview Debugging Output Follows.");
347     } catch (Exception ex)
348     {
349       System.err.println("Problems initializing the log4j system\n");
350       ex.printStackTrace(System.err);
351     }
352   }
353
354   /**
355    * Loads properties from the given properties file. Any existing properties
356    * are first cleared.
357    */
358   public static void loadProperties(String propsFile)
359   {
360     getInstance().loadPropertiesImpl(propsFile);
361   }
362
363   private void loadPropertiesImpl(String propsFile)
364   {
365     propertiesFile = propsFile;
366     if (!propsAreReadOnly)
367     {
368       // Java only
369       if (propsFile == null)
370       {
371         propertiesFile = System.getProperty("user.home")
372                 + File.separatorChar + ".jalview_properties";
373       }
374       else
375       {
376         // don't corrupt the file we've been given.
377         propsAreReadOnly = true;
378       }
379     }
380
381     if (propertiesFile == null)
382     { // BH 2019 read properties from the Info object associated with this
383       // applet
384       Platform.readInfoProperties(JS_PROPERTY_PREFIX,
385               applicationProperties);
386     }
387     else
388     {
389       try
390       {
391         InputStream fis;
392         try
393         {
394           fis = new java.net.URL(propertiesFile).openStream();
395           System.out.println(
396                   "Loading jalview properties from : " + propertiesFile);
397           System.out.println(
398                   "Disabling Jalview writing to user's local properties file.");
399           propsAreReadOnly = true;
400
401         } catch (Exception ex)
402         {
403           fis = null;
404         }
405         if (fis == null)
406         {
407           fis = new FileInputStream(propertiesFile);
408         }
409         applicationProperties.clear();
410         applicationProperties.load(fis);
411
412         // remove any old build properties
413
414         deleteBuildProperties();
415         fis.close();
416       } catch (Exception ex)
417       {
418         System.out.println("Error reading properties file: " + ex);
419       }
420     }
421     if (getDefault("USE_PROXY", false))
422     {
423       String proxyServer = getDefault("PROXY_SERVER", ""),
424               proxyPort = getDefault("PROXY_PORT", "8080");
425
426       System.out.println("Using proxyServer: " + proxyServer
427               + " proxyPort: " + proxyPort);
428
429       System.setProperty("http.proxyHost", proxyServer);
430       System.setProperty("http.proxyPort", proxyPort);
431     }
432
433     // LOAD THE AUTHORS FROM THE authors.props file
434     String authorDetails = (Platform.isJS() ? null
435             : "jar:".concat(Cache.class.getProtectionDomain()
436                     .getCodeSource().getLocation().toString()
437                     .concat("!/authors.props")));
438
439     try
440     {
441       if (authorDetails != null)
442       {
443         java.net.URL localJarFileURL = new java.net.URL(authorDetails);
444         InputStream in = localJarFileURL.openStream();
445         applicationProperties.load(in);
446         in.close();
447       }
448     } catch (Exception ex)
449     {
450       System.out.println("Error reading author details: " + ex);
451       authorDetails = null;
452     }
453     if (authorDetails == null)
454     {
455       applicationProperties.remove("AUTHORS");
456       applicationProperties.remove("AUTHORFNAMES");
457       applicationProperties.remove("YEAR");
458     }
459
460     // FIND THE VERSION NUMBER AND BUILD DATE FROM jalview.jar
461     // MUST FOLLOW READING OF LOCAL PROPERTIES FILE AS THE
462     // VERSION MAY HAVE CHANGED SINCE LAST USING JALVIEW
463     String buildDetails = (Platform.isJS() ? null
464             : "jar:".concat(Cache.class.getProtectionDomain()
465                     .getCodeSource().getLocation().toString()
466                     .concat("!/.build_properties")));
467     if (buildDetails != null)
468     {
469       try
470       {
471         java.net.URL localJarFileURL = new java.net.URL(buildDetails);
472         InputStream in = localJarFileURL.openStream();
473         applicationProperties.load(in);
474         in.close();
475       } catch (Exception ex)
476       {
477         System.out.println("Error reading build details: " + ex);
478         buildDetails = null;
479       }
480     }
481     if (buildDetails == null)
482     {
483       applicationProperties.remove("VERSION");
484     }
485     String jnlpVersion = System.getProperty("jalview.version");
486     String codeVersion = getProperty("VERSION");
487     String codeInstallation = getProperty("INSTALLATION");
488     if (codeVersion == null)
489     {
490       // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
491       codeVersion = "Test";
492       jnlpVersion = "Test";
493       codeInstallation = "";
494     }
495     else
496     {
497       codeInstallation = " (" + codeInstallation + ")";
498     }
499     new BuildDetails(codeVersion, null, codeInstallation);
500
501     SiftsSettings.setMapWithSifts(getDefault("MAP_WITH_SIFTS", false));
502
503     SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache
504             .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
505
506     SiftsSettings.setFailSafePIDThreshold(
507             getDefault("sifts_fail_safe_pid_threshold",
508                     DEFAULT_FAIL_SAFE_PID_THRESHOLD));
509
510     SiftsSettings.setCacheThresholdInDays(
511             getDefault("sifts_cache_threshold_in_days",
512                     DEFAULT_CACHE_THRESHOLD_IN_DAYS));
513
514     IdOrgSettings.setUrl(getDefault(Preferences.ID_ORG_HOSTURL,
515             "http://www.jalview.org/services/identifiers"));
516     IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
517
518     System.out
519             .println("Jalview Version: " + codeVersion + codeInstallation);
520
521     StructureImportSettings.setDefaultStructureFileFormat(jalview.bin.Cache
522             .getDefault(Preferences.PDB_DOWNLOAD_FORMAT, PDB_DOWNLOAD_FORMAT));
523     StructureImportSettings
524             .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
525     // StructureImportSettings
526     // .setDefaultPDBFileParser(jalview.bin.getDefault(
527     // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
528     // jnlpVersion will be null if we're using InstallAnywhere
529     // Dont do this check if running in headless mode
530     if (jnlpVersion == null && !Jalview.isHeadlessMode()
531             && getDefault("VERSION_CHECK", true))
532     {
533
534       class VersionChecker extends Thread
535       {
536         @Override
537         public void run()
538         {
539           String orgtimeout = System
540                   .getProperty("sun.net.client.defaultConnectTimeout");
541           if (orgtimeout == null)
542           {
543             orgtimeout = "30";
544             System.out.println("# INFO: Setting default net timeout to "
545                     + orgtimeout + " seconds.");
546           }
547           String remoteVersion = null;
548           try
549           {
550             System.setProperty("sun.net.client.defaultConnectTimeout",
551                     "5000");
552             java.net.URL url = new java.net.URL(Cache
553                     .getDefault("www.jalview.org", "http://www.jalview.org")
554                     + "/webstart/jalview.jnlp");
555             BufferedReader in = new BufferedReader(
556                     new InputStreamReader(url.openStream()));
557             String line = null;
558             while ((line = in.readLine()) != null)
559             {
560               if (line.indexOf("jalview.version") == -1)
561               {
562                 continue;
563               }
564
565               line = line.substring(line.indexOf("value=") + 7);
566               line = line.substring(0, line.lastIndexOf("\""));
567               remoteVersion = line;
568               break;
569             }
570           } catch (Exception ex)
571           {
572             System.out.println(
573                     "Non-fatal exception when checking version at www.jalview.org :");
574             System.out.println(ex);
575             remoteVersion = getProperty("VERSION");
576           }
577           System.setProperty("sun.net.client.defaultConnectTimeout",
578                   orgtimeout);
579
580           setProperty("LATEST_VERSION", remoteVersion);
581         }
582       }
583
584       VersionChecker vc = new VersionChecker();
585       vc.start();
586     }
587     else
588     {
589       if (jnlpVersion != null)
590       {
591         setProperty("LATEST_VERSION", jnlpVersion);
592       }
593       else
594       {
595         applicationProperties.remove("LATEST_VERSION");
596       }
597     }
598
599     setProperty("VERSION", codeVersion);
600
601     // LOAD USERDEFINED COLOURS
602     initUserColourSchemes(getProperty(Preferences.USER_DEFINED_COLOURS));
603   }
604
605   private void deleteBuildProperties()
606   {
607     applicationProperties.remove("LATEST_VERSION");
608     applicationProperties.remove("VERSION");
609     applicationProperties.remove("AUTHORS");
610     applicationProperties.remove("AUTHORFNAMES");
611     applicationProperties.remove("YEAR");
612     applicationProperties.remove("BUILD_DATE");
613     applicationProperties.remove("INSTALLATION");
614   }
615
616   /**
617    * Gets Jalview application property of given key. Returns null if key not
618    * found
619    * 
620    * @param key
621    *          Name of property
622    * 
623    * @return Property value
624    */
625   public static String getProperty(String key)
626   {
627     return getInstance().applicationProperties.getProperty(key);
628   }
629
630   /**
631    * These methods are used when checking if the saved preference is different
632    * to the default setting
633    */
634
635   public static boolean getDefault(String property, boolean def)
636   {
637     String string = getProperty(property);
638     if (string != null)
639     {
640       def = Boolean.valueOf(string).booleanValue();
641     }
642
643     return def;
644   }
645
646   public static int getDefault(String property, int def)
647   {
648     String string = getProperty(property);
649     if (string != null)
650     {
651       try
652       {
653         def = Integer.parseInt(string);
654       } catch (NumberFormatException e)
655       {
656         System.out.println("Error parsing int property '" + property
657                 + "' with value '" + string + "'");
658       }
659     }
660
661     return def;
662   }
663
664   /**
665    * retrieve a dimension, such as for Jmol
666    * 
667    * @param property
668    * @param def
669    * @return
670    */
671   public static Dimension getDefaultDim(String property, Dimension def)
672   {
673     String s = getProperty(property);
674     if (s != null)
675     {
676       if (s.indexOf(',') < 0)
677       {
678         s = s.trim().replace(' ', ',');
679         if (s.indexOf(',') < 0)
680         {
681           s += "," + s;
682         }
683       }
684       try
685       {
686         int pt = s.indexOf(",");
687         return new Dimension(Integer.parseInt(s.substring(0, pt)),
688                 Integer.parseInt(s.substring(pt + 1)));
689       } catch (NumberFormatException e)
690       {
691         System.out.println("Error parsing Dimension property '" + property
692                 + "' with value '" + s + "'");
693       }
694     }
695     return def;
696   }
697
698   /**
699    * Answers the value of the given property, or the supplied default value if
700    * the property is not set
701    */
702   public static String getDefault(String property, String def)
703   {
704     String value = getProperty(property);
705     return value == null ? def : value;
706   }
707
708   /**
709    * Stores property in the file "HOME_DIR/.jalview_properties"
710    * 
711    * @param key
712    *          Name of object
713    * @param obj
714    *          String value of property
715    * 
716    * @return previous value of property (or null)
717    */
718   public static Object setProperty(String key, String obj)
719   {
720     return getInstance().setPropertyImpl(key, obj, true);
721   }
722
723   public static void setPropertyNoSave(String key, String obj)
724   {
725     getInstance().setPropertyImpl(key, obj, false);
726   }
727
728   private Object setPropertyImpl(String key, String obj, boolean andSave)
729   {
730     Object oldValue = null;
731     try
732     {
733       oldValue = applicationProperties.setProperty(key, obj);
734       if (andSave && !propsAreReadOnly && propertiesFile != null)
735       {
736         FileOutputStream out = new FileOutputStream(propertiesFile);
737         applicationProperties.store(out, "---JalviewX Properties File---");
738         out.close();
739       }
740     } catch (Exception ex)
741     {
742       System.out.println(
743               "Error setting property: " + key + " " + obj + "\n" + ex);
744     }
745     return oldValue;
746   }
747
748   /**
749    * remove the specified property from the jalview properties file
750    * 
751    * @param key
752    */
753   public static void removeProperty(String key)
754   {
755     getInstance().removePropertyImpl(key, true);
756   }
757
758   public static void removePropertyNoSave(String key)
759   {
760     getInstance().removePropertyImpl(key, false);
761   }
762
763   private void removePropertyImpl(String key, boolean andSave)
764   {
765     applicationProperties.remove(key);
766     if (andSave)
767     {
768       savePropertiesImpl();
769     }
770   }
771
772   public static void saveProperties()
773   {
774     getInstance().savePropertiesImpl();
775   }
776
777   /**
778    * save the properties to the jalview properties path
779    */
780   private void savePropertiesImpl()
781   {
782     if (!propsAreReadOnly)
783     {
784       try
785       {
786         FileOutputStream out = new FileOutputStream(propertiesFile);
787         applicationProperties.store(out, "---JalviewX Properties File---");
788         out.close();
789       } catch (Exception ex)
790       {
791         System.out.println("Error saving properties: " + ex);
792       }
793     }
794   }
795
796   private final static int UNTESTED = -1;
797
798   private final static int TRUE = 1;
799
800   private final static int FALSE = 0;
801
802   /**
803    * internal vamsas class discovery state
804    */
805   private static int vamsasJarsArePresent = (Platform.isJS() ? FALSE
806           : UNTESTED);
807
808   /**
809    * Searches for vamsas client classes on class path.
810    * 
811    * @return true if vamsas client is present on classpath
812    */
813   public static boolean vamsasJarsPresent()
814   {
815     if (vamsasJarsArePresent == UNTESTED)
816     {
817       try
818       {
819         if (jalview.jbgui.GDesktop.class.getClassLoader()
820                 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
821         {
822           jalview.bin.Cache.log.debug(
823                   "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
824           vamsasJarsArePresent = TRUE;
825           Logger lvclient = Logger.getLogger("uk.ac.vamsas");
826           lvclient.setLevel(Level.toLevel(Cache
827                   .getDefault("logs.Vamsas.Level", Level.INFO.toString())));
828
829           lvclient.addAppender(log.getAppender("JalviewLogger"));
830           // Tell the user that debug is enabled
831           lvclient.debug("Jalview Vamsas Client Debugging Output Follows.");
832         }
833       } catch (Exception e)
834       {
835         vamsasJarsArePresent = FALSE;
836         jalview.bin.Cache.log.debug("Vamsas Classes are not present");
837       }
838     }
839     return (vamsasJarsArePresent == TRUE);
840   }
841
842   /**
843    * internal vamsas class discovery state
844    */
845   private static int groovyJarsArePresent = (Platform.isJS() ? FALSE
846           : UNTESTED);
847
848   /**
849    * Searches for vamsas client classes on class path.
850    * 
851    * @return true if vamsas client is present on classpath
852    */
853   public static boolean groovyJarsPresent()
854   {
855     if (groovyJarsArePresent == UNTESTED)
856     {
857       try
858       {
859         if (Cache.class.getClassLoader()
860                 .loadClass("groovy.lang.GroovyObject") != null)
861         {
862           jalview.bin.Cache.log.debug(
863                   "Found Groovy (groovy.lang.GroovyObject can be loaded)");
864           groovyJarsArePresent = TRUE;
865           Logger lgclient = Logger.getLogger("groovy");
866           lgclient.setLevel(Level.toLevel(Cache
867                   .getDefault("logs.Groovy.Level", Level.INFO.toString())));
868
869           lgclient.addAppender(log.getAppender("JalviewLogger"));
870           // Tell the user that debug is enabled
871           lgclient.debug("Jalview Groovy Client Debugging Output Follows.");
872         }
873       } catch (Error e)
874       {
875         groovyJarsArePresent = FALSE;
876         jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
877       } catch (Exception e)
878       {
879         groovyJarsArePresent = FALSE;
880         jalview.bin.Cache.log.debug("Groovy Classes are not present");
881       }
882     }
883     return (groovyJarsArePresent == TRUE);
884   }
885
886   /**
887    * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
888    * enabled.
889    */
890   protected static Object tracker = null;
891
892   protected static Class<?> trackerfocus = null;
893
894   protected static Class<?> jgoogleanalyticstracker = null;
895
896   /**
897    * Initialise the google tracker if it is not done already.
898    */
899   public static void initGoogleTracker()
900   {
901
902     // TODO: SwingJS JavaScript tracker?
903
904     if (tracker == null)
905     {
906       if (jgoogleanalyticstracker == null)
907       {
908         // try to get the tracker class
909         try
910         {
911           jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
912                   "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
913           trackerfocus = Cache.class.getClassLoader()
914                   .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
915         } catch (Exception e)
916         {
917           log.debug(
918                   "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
919           tracker = null;
920           jgoogleanalyticstracker = null;
921           trackerfocus = null;
922           return;
923         }
924       }
925       // now initialise tracker
926       Exception re = null, ex = null;
927       Error err = null;
928       String vrs = "No Version Accessible";
929       try
930       {
931         // Google analytics tracking code for Library Finder
932         tracker = jgoogleanalyticstracker
933                 .getConstructor(new Class[]
934                 { String.class, String.class, String.class })
935                 .newInstance(new Object[]
936                 { "Jalview Desktop",
937                     (vrs = jalview.bin.Cache.getProperty("VERSION") + "_"
938                             + getDefault("BUILD_DATE", "unknown")),
939                     "UA-9060947-1" });
940         jgoogleanalyticstracker
941                 .getMethod("trackAsynchronously", new Class[]
942                 { trackerfocus })
943                 .invoke(tracker, new Object[]
944                 { trackerfocus.getConstructor(new Class[] { String.class })
945                         .newInstance(new Object[]
946                         { "Application Started." }) });
947       } catch (RuntimeException e)
948       {
949         re = e;
950       } catch (Exception e)
951       {
952         ex = e;
953       } catch (Error e)
954       {
955         err = e;
956       }
957       if (re != null || ex != null || err != null)
958       {
959         if (log != null)
960         {
961           if (re != null)
962           {
963             log.debug("Caught runtime exception in googletracker init:",
964                     re);
965           }
966           if (ex != null)
967           {
968             log.warn(
969                     "Failed to initialise GoogleTracker for Jalview Desktop with version "
970                             + vrs,
971                     ex);
972           }
973           if (err != null)
974           {
975             log.error(
976                     "Whilst initing GoogleTracker for Jalview Desktop version "
977                             + vrs,
978                     err);
979           }
980         }
981         else
982         {
983           if (re != null)
984           {
985             System.err.println(
986                     "Debug: Caught runtime exception in googletracker init:"
987                             + vrs);
988             re.printStackTrace();
989           }
990           if (ex != null)
991           {
992             System.err.println(
993                     "Warning:  Failed to initialise GoogleTracker for Jalview Desktop with version "
994                             + vrs);
995             ex.printStackTrace();
996           }
997
998           if (err != null)
999           {
1000             System.err.println(
1001                     "ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
1002                             + vrs);
1003             err.printStackTrace();
1004           }
1005         }
1006       }
1007       else
1008       {
1009         log.debug("Successfully initialised tracker.");
1010       }
1011     }
1012   }
1013
1014   /**
1015    * get the user's default colour if available
1016    * 
1017    * @param property
1018    * @param defcolour
1019    * @return
1020    */
1021   public static Color getDefaultColour(String property, Color defcolour)
1022   {
1023     String colprop = getProperty(property);
1024     if (colprop == null)
1025     {
1026       return defcolour;
1027     }
1028     Color col = ColorUtils.parseColourString(colprop);
1029     if (col == null)
1030     {
1031       log.warn("Couldn't parse '" + colprop + "' as a colour for "
1032               + property);
1033     }
1034     return (col == null) ? defcolour : col;
1035   }
1036
1037   /**
1038    * store a colour as a Jalview user default property
1039    * 
1040    * @param property
1041    * @param colour
1042    */
1043   public static void setColourProperty(String property, Color colour)
1044   {
1045     setProperty(property, jalview.util.Format.getHexString(colour));
1046   }
1047
1048   /**
1049    * Stores a formatted date in a jalview property, using a fixed locale.
1050    * 
1051    * @param propertyName
1052    * @param date
1053    * @return the formatted date string
1054    */
1055   public static String setDateProperty(String propertyName, Date date)
1056   {
1057     String formatted = date_format.format(date);
1058     setProperty(propertyName, formatted);
1059     return formatted;
1060   }
1061
1062   /**
1063    * Reads a date stored in a Jalview property, parses it (using a fixed locale
1064    * format) and returns as a Date, or null if parsing fails
1065    * 
1066    * @param propertyName
1067    * @return
1068    * 
1069    */
1070   public static Date getDateProperty(String propertyName)
1071   {
1072     String val = getProperty(propertyName);
1073     if (val != null)
1074     {
1075       try
1076       {
1077         return date_format.parse(val);
1078       } catch (Exception ex)
1079       {
1080         System.err.println("Invalid or corrupt date in property '"
1081                 + propertyName + "' : value was '" + val + "'");
1082       }
1083     }
1084     return null;
1085   }
1086
1087   /**
1088    * get and parse a property as an integer. send any parsing problems to
1089    * System.err
1090    * 
1091    * @param property
1092    * @return null or Integer
1093    */
1094   public static Integer getIntegerProperty(String property)
1095   {
1096     String val = getProperty(property);
1097     if (val != null && (val = val.trim()).length() > 0)
1098     {
1099       try
1100       {
1101         return Integer.valueOf(val);
1102       } catch (NumberFormatException x)
1103       {
1104         System.err.println("Invalid integer in property '" + property
1105                 + "' (value was '" + val + "')");
1106       }
1107     }
1108     return null;
1109   }
1110
1111   /**
1112    * Set the specified value, or remove it if null or empty. Does not save the
1113    * properties file.
1114    * 
1115    * @param propName
1116    * @param value
1117    */
1118   public static void setOrRemove(String propName, String value)
1119   {
1120     if (propName == null)
1121     {
1122       return;
1123     }
1124     if (value == null || value.trim().length() < 1)
1125     {
1126       getInstance().applicationProperties.remove(propName);
1127     }
1128     else
1129     {
1130       getInstance().applicationProperties.setProperty(propName, value);
1131     }
1132   }
1133
1134   /**
1135    * Loads in user colour schemes from files.
1136    * 
1137    * @param files
1138    *          a '|'-delimited list of file paths
1139    */
1140   public static void initUserColourSchemes(String files)
1141   {
1142     if (files == null || files.length() == 0)
1143     {
1144       return;
1145     }
1146
1147     // In case colours can't be loaded, we'll remove them
1148     // from the default list here.
1149     StringBuffer coloursFound = new StringBuffer();
1150     StringTokenizer st = new StringTokenizer(files, "|");
1151     while (st.hasMoreElements())
1152     {
1153       String file = st.nextToken();
1154       try
1155       {
1156         UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1157         if (ucs != null)
1158         {
1159           if (coloursFound.length() > 0)
1160           {
1161             coloursFound.append("|");
1162           }
1163           coloursFound.append(file);
1164           ColourSchemes.getInstance().registerColourScheme(ucs);
1165         }
1166       } catch (Exception ex)
1167       {
1168         System.out.println("Error loading User ColourFile\n" + ex);
1169       }
1170     }
1171     if (!files.equals(coloursFound.toString()))
1172     {
1173       if (coloursFound.toString().length() > 1)
1174       {
1175         setProperty(Preferences.USER_DEFINED_COLOURS,
1176                 coloursFound.toString());
1177       }
1178       else
1179       {
1180         getInstance().applicationProperties
1181                 .remove(Preferences.USER_DEFINED_COLOURS);
1182       }
1183     }
1184   }
1185
1186 }