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