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