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