reconciled with applet
[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    * 
745    * Sets a property value for the running application, without saving it to the
746    * properties file. 
747    * 
748    * Replaces direct call to Cache.applicationProperties.setProperty
749    * 
750    * Used extensively in AppletParams and Preferences.ok_actionPerformed
751    * 
752    * 
753    * @param key
754    * @param obj
755    */
756   public static void setPropertyNoSave(String key, String obj)
757   {
758     getInstance().setPropertyImpl(key, obj, false);
759   }
760
761
762   /**
763    * Sets a property value, and optionally also saves the current properties to
764    * file
765    * 
766    * @param key
767    * @param obj
768    * @param andSave
769    * @return
770    */
771   private Object setPropertyImpl(String key, String obj, boolean andSave)
772   {
773     Object oldValue = null;
774     try
775     {
776       oldValue = applicationProperties.setProperty(key, obj);
777       if (andSave && !propsAreReadOnly && propertiesFile != null)
778       {
779         FileOutputStream out = new FileOutputStream(propertiesFile);
780         applicationProperties.store(out, "---JalviewX Properties File---");
781         out.close();
782       }
783     } catch (Exception ex)
784     {
785       System.out.println(
786               "Error setting property: " + key + " " + obj + "\n" + ex);
787     }
788     return oldValue;
789   }
790
791   /**
792    * Removes the specified property from the jalview properties file
793    * 
794    * @param key
795    */
796   public static void removeProperty(String key)
797   {
798     getInstance().removePropertyImpl(key, true);
799   }
800
801   /**
802    * Removes the named property for the running application, without saving the
803    * properties file.
804    * 
805    * Called by Preferences.ok_actionPerformed specifically for SEQUENCE_LINKS and STORED_LINKS. 
806    * 
807    * 
808    * @param key
809    */
810   public static void removePropertyNoSave(String key)
811   {
812     getInstance().removePropertyImpl(key, false);
813   }
814
815   /**
816    * Removes the named property, and optionally saves the current properties to
817    * file
818    * 
819    * @param key
820    * @param andSave
821    */
822   private void removePropertyImpl(String key, boolean andSave)
823   {
824     applicationProperties.remove(key);
825     if (andSave)
826     {
827       savePropertiesImpl();
828     }
829   }
830
831   /**
832    * Saves the current properties to file
833    */
834   public static void saveProperties()
835   {
836     getInstance().savePropertiesImpl();
837   }
838
839   /**
840    * save the properties to the jalview properties path
841    */
842   private void savePropertiesImpl()
843   {
844     if (!propsAreReadOnly)
845     {
846       try
847       {
848         FileOutputStream out = new FileOutputStream(propertiesFile);
849         applicationProperties.store(out, "---JalviewX Properties File---");
850         out.close();
851       } catch (Exception ex)
852       {
853         System.out.println("Error saving properties: " + ex);
854       }
855     }
856   }
857
858   private final static int UNTESTED = -1;
859
860   private final static int TRUE = 1;
861
862   private final static int FALSE = 0;
863
864   /**
865    * internal vamsas class discovery state
866    */
867   private static int vamsasJarsArePresent = (Platform.isJS() ? FALSE
868           : UNTESTED);
869
870   /**
871    * Searches for vamsas client classes on class path.
872    * 
873    * @return true if vamsas client is present on classpath
874    */
875   public static boolean vamsasJarsPresent()
876   {
877     if (vamsasJarsArePresent == UNTESTED)
878     {
879       try
880       {
881         if (jalview.jbgui.GDesktop.class.getClassLoader()
882                 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
883         {
884           jalview.bin.Cache.log.debug(
885                   "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
886           vamsasJarsArePresent = TRUE;
887           Logger lvclient = Logger.getLogger("uk.ac.vamsas");
888           lvclient.setLevel(Level.toLevel(Cache
889                   .getDefault("logs.Vamsas.Level", Level.INFO.toString())));
890
891           lvclient.addAppender(log.getAppender("JalviewLogger"));
892           // Tell the user that debug is enabled
893           lvclient.debug("Jalview Vamsas Client Debugging Output Follows.");
894         }
895       } catch (Exception e)
896       {
897         vamsasJarsArePresent = FALSE;
898         jalview.bin.Cache.log.debug("Vamsas Classes are not present");
899       }
900     }
901     return (vamsasJarsArePresent == TRUE);
902   }
903
904   /**
905    * internal vamsas class discovery state
906    */
907   private static int groovyJarsArePresent = (Platform.isJS() ? FALSE
908           : UNTESTED);
909
910   /**
911    * Searches for vamsas client classes on class path.
912    * 
913    * @return true if vamsas client is present on classpath
914    */
915   public static boolean groovyJarsPresent()
916   {
917     if (groovyJarsArePresent == UNTESTED)
918     {
919       try
920       {
921         if (Cache.class.getClassLoader()
922                 .loadClass("groovy.lang.GroovyObject") != null)
923         {
924           jalview.bin.Cache.log.debug(
925                   "Found Groovy (groovy.lang.GroovyObject can be loaded)");
926           groovyJarsArePresent = TRUE;
927           Logger lgclient = Logger.getLogger("groovy");
928           lgclient.setLevel(Level.toLevel(Cache
929                   .getDefault("logs.Groovy.Level", Level.INFO.toString())));
930
931           lgclient.addAppender(log.getAppender("JalviewLogger"));
932           // Tell the user that debug is enabled
933           lgclient.debug("Jalview Groovy Client Debugging Output Follows.");
934         }
935       } catch (Error e)
936       {
937         groovyJarsArePresent = FALSE;
938         jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
939       } catch (Exception e)
940       {
941         groovyJarsArePresent = FALSE;
942         jalview.bin.Cache.log.debug("Groovy Classes are not present");
943       }
944     }
945     return (groovyJarsArePresent == TRUE);
946   }
947
948   /**
949    * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
950    * enabled.
951    */
952   protected static Object tracker = null;
953
954   protected static Class<?> trackerfocus = null;
955
956   protected static Class<?> jgoogleanalyticstracker = null;
957
958   /**
959    * Initialise the google tracker if it is not done already.
960    */
961   public static void initGoogleTracker()
962   {
963
964     // TODO: SwingJS JavaScript tracker?
965
966     if (tracker == null)
967     {
968       if (jgoogleanalyticstracker == null)
969       {
970         // try to get the tracker class
971         try
972         {
973           jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
974                   "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
975           trackerfocus = Cache.class.getClassLoader()
976                   .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
977         } catch (Exception e)
978         {
979           log.debug(
980                   "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
981           tracker = null;
982           jgoogleanalyticstracker = null;
983           trackerfocus = null;
984           return;
985         }
986       }
987       // now initialise tracker
988       Exception re = null, ex = null;
989       Error err = null;
990       String vrs = "No Version Accessible";
991       try
992       {
993         // Google analytics tracking code for Library Finder
994         tracker = jgoogleanalyticstracker
995                 .getConstructor(new Class[]
996                 { String.class, String.class, String.class })
997                 .newInstance(new Object[]
998                 { "Jalview Desktop",
999                     (vrs = jalview.bin.Cache.getProperty("VERSION") + "_"
1000                             + jalview.bin.Cache.getDefault("BUILD_DATE",
1001                                     "unknown")),
1002                     "UA-9060947-1" });
1003         jgoogleanalyticstracker
1004                 .getMethod("trackAsynchronously", new Class[]
1005                 { trackerfocus })
1006                 .invoke(tracker, new Object[]
1007                 { trackerfocus.getConstructor(new Class[] { String.class })
1008                         .newInstance(new Object[]
1009                         { "Application Started." }) });
1010       } catch (RuntimeException e)
1011       {
1012         re = e;
1013       } catch (Exception e)
1014       {
1015         ex = e;
1016       } catch (Error e)
1017       {
1018         err = e;
1019       }
1020       if (re != null || ex != null || err != null)
1021       {
1022         if (log != null)
1023         {
1024           if (re != null)
1025           {
1026             log.debug("Caught runtime exception in googletracker init:",
1027                     re);
1028           }
1029           if (ex != null)
1030           {
1031             log.warn(
1032                     "Failed to initialise GoogleTracker for Jalview Desktop with version "
1033                             + vrs,
1034                     ex);
1035           }
1036           if (err != null)
1037           {
1038             log.error(
1039                     "Whilst initing GoogleTracker for Jalview Desktop version "
1040                             + vrs,
1041                     err);
1042           }
1043         }
1044         else
1045         {
1046           if (re != null)
1047           {
1048             System.err.println(
1049                     "Debug: Caught runtime exception in googletracker init:"
1050                             + vrs);
1051             re.printStackTrace();
1052           }
1053           if (ex != null)
1054           {
1055             System.err.println(
1056                     "Warning:  Failed to initialise GoogleTracker for Jalview Desktop with version "
1057                             + vrs);
1058             ex.printStackTrace();
1059           }
1060
1061           if (err != null)
1062           {
1063             System.err.println(
1064                     "ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
1065                             + vrs);
1066             err.printStackTrace();
1067           }
1068         }
1069       }
1070       else
1071       {
1072         log.debug("Successfully initialised tracker.");
1073       }
1074     }
1075   }
1076
1077   /**
1078    * Returns the Color value of the given property's value, or the supplied
1079    * default colour if no property is found, or it cannot be parsed to a colour.
1080    * Colours are normally saved as hex rgb values, though other formats may be
1081    * parseable.
1082    * 
1083    * @param property
1084    * @param defcolour
1085    * @return
1086    */
1087   public static Color getDefaultColour(String property, Color defcolour)
1088   {
1089     String colprop = getProperty(property);
1090     if (colprop == null)
1091     {
1092       return defcolour;
1093     }
1094     Color col = ColorUtils.parseColourString(colprop);
1095     if (col == null)
1096     {
1097       log.warn("Couldn't parse '" + colprop + "' as a colour for "
1098               + property);
1099     }
1100     return (col == null) ? defcolour : col;
1101   }
1102
1103   /**
1104    * Stores a colour as a Jalview property, converted to hex values for rgb.
1105    * Properties are not saved to file.
1106    * 
1107    * 
1108    * 
1109    * Used extensively in Preferences.ok_actionPerformed
1110    * 
1111    * @param property
1112    * @param colour
1113    */
1114   public static void setColourPropertyNoSave(String property, Color colour)
1115   {
1116     setPropertyNoSave(property, jalview.util.Format.getHexString(colour));
1117   }
1118
1119   /**
1120    * store a colour as a Jalview user default property
1121    * 
1122    * @param property
1123    * @param colour
1124    */
1125   public static void setColourProperty(String property, Color colour)
1126   {
1127     setProperty(property, jalview.util.Format.getHexString(colour));
1128   }
1129
1130   /**
1131    * Stores a formatted date in a jalview property, using a fixed locale.
1132    * Updated properties are written out to the properties file.
1133    * 
1134    * @param propertyName
1135    * @param date
1136    * @return the formatted date string
1137    */
1138   public static String setDateProperty(String propertyName, Date date)
1139   {
1140     String formatted = date_format.format(date);
1141     setProperty(propertyName, formatted);
1142     return formatted;
1143   }
1144
1145   /**
1146    * Reads a date stored in a Jalview property, parses it (using a fixed locale
1147    * format) and returns as a Date, or null if parsing fails
1148    * 
1149    * @param propertyName
1150    * @return
1151    * 
1152    */
1153   public static Date getDateProperty(String propertyName)
1154   {
1155     String val = getProperty(propertyName);
1156     if (val != null)
1157     {
1158       try
1159       {
1160         return date_format.parse(val);
1161       } catch (Exception ex)
1162       {
1163         System.err.println("Invalid or corrupt date in property '"
1164                 + propertyName + "' : value was '" + val + "'");
1165       }
1166     }
1167     return null;
1168   }
1169
1170   /**
1171    * get and parse a property as an integer. send any parsing problems to
1172    * System.err
1173    * 
1174    * @param property
1175    * @return null or Integer
1176    */
1177   public static Integer getIntegerProperty(String property)
1178   {
1179     String val = getProperty(property);
1180     if (val != null && (val = val.trim()).length() > 0)
1181     {
1182       try
1183       {
1184         return Integer.valueOf(val);
1185       } catch (NumberFormatException x)
1186       {
1187         System.err.println("Invalid integer in property '" + property
1188                 + "' (value was '" + val + "')");
1189       }
1190     }
1191     return null;
1192   }
1193
1194   /**
1195    * Set the specified value, or remove it if null or empty. Does not save the
1196    * properties file.
1197    * 
1198    * @param propName
1199    * @param value
1200    */
1201   public static void setOrRemove(String propName, String value)
1202   {
1203     if (propName == null)
1204     {
1205       return;
1206     }
1207     if (value == null || value.trim().length() < 1)
1208     {
1209       getInstance().applicationProperties.remove(propName);
1210     }
1211     else
1212     {
1213       getInstance().applicationProperties.setProperty(propName, value);
1214     }
1215   }
1216
1217   /**
1218    * Loads in user colour schemes from files.
1219    * 
1220    * @param files
1221    *          a '|'-delimited list of file paths
1222    */
1223   public static void initUserColourSchemes(String files)
1224   {
1225     if (files == null || files.length() == 0)
1226     {
1227       return;
1228     }
1229
1230     // In case colours can't be loaded, we'll remove them
1231     // from the default list here.
1232     StringBuffer coloursFound = new StringBuffer();
1233     StringTokenizer st = new StringTokenizer(files, "|");
1234     while (st.hasMoreElements())
1235     {
1236       String file = st.nextToken();
1237       try
1238       {
1239         UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1240         if (ucs != null)
1241         {
1242           if (coloursFound.length() > 0)
1243           {
1244             coloursFound.append("|");
1245           }
1246           coloursFound.append(file);
1247           ColourSchemes.getInstance().registerColourScheme(ucs);
1248         }
1249       } catch (Exception ex)
1250       {
1251         System.out.println("Error loading User ColourFile\n" + ex);
1252       }
1253     }
1254     if (!files.equals(coloursFound.toString()))
1255     {
1256       if (coloursFound.toString().length() > 1)
1257       {
1258          // BH moved to Preferences for consistency
1259         setProperty(Preferences.USER_DEFINED_COLOURS,
1260                 coloursFound.toString());
1261       }
1262       else
1263       {
1264         // BH moved to Preferences for consistency
1265         getInstance().applicationProperties
1266                 .remove(Preferences.USER_DEFINED_COLOURS);
1267       }
1268     }
1269   }
1270
1271   /**
1272    * Initial logging information helper for various versions output
1273    * 
1274    * @param prefix
1275    * @param value
1276    * @param defaultValue
1277    */
1278   private static void appendIfNotNull(StringBuilder sb, String prefix,
1279           String value, String suffix, String defaultValue)
1280   {
1281     if (value == null && defaultValue == null)
1282     {
1283       return;
1284     }
1285     String line = prefix + (value != null ? value : defaultValue) + suffix;
1286     sb.append(line);
1287   }
1288
1289   /**
1290    * 
1291    * @return Jalview version, build details and JVM platform version for console
1292    */
1293   public static String getVersionDetailsForConsole()
1294   {
1295     StringBuilder sb = new StringBuilder();
1296     sb.append("Jalview Version: " + jalview.bin.Cache.getDefault("VERSION", "TEST"));
1297     sb.append("\n");
1298     sb.append("Jalview Installation: "
1299             + jalview.bin.Cache.getDefault("INSTALLATION", "unknown"));
1300     sb.append("\n");
1301     sb.append("Build Date: " + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
1302     sb.append("\n");
1303     sb.append("Java version: " + System.getProperty("java.version"));
1304     sb.append("\n");
1305     sb.append(System.getProperty("os.arch") + " " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
1306     sb.append("\n");
1307     appendIfNotNull(sb, "Install4j version: ",
1308             System.getProperty("sys.install4jVersion"), "\n", null);
1309     appendIfNotNull(sb, "Install4j template version: ",
1310             System.getProperty("installer_template_version"), "\n", null);
1311     appendIfNotNull(sb, "Launcher version: ",
1312             System.getProperty("launcher_version"), "\n", null);
1313     if (jalview.bin.Cache.getDefault("VERSION", "TEST").equals("DEVELOPMENT")) {
1314       appendIfNotNull(sb, "Getdown appdir: ",
1315               System.getProperty("getdownappdir"), "\n", null);
1316       appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1317               "\n", "unknown");
1318     }
1319     return sb.toString();
1320   }
1321
1322   /**
1323    * 
1324    * @return build details as reported in splashscreen
1325    */
1326   public static String getBuildDetailsForSplash()
1327   {
1328     // consider returning more human friendly info
1329     // eg 'built from Source' or update channel
1330     return jalview.bin.Cache.getDefault("INSTALLATION", "unknown");
1331   }
1332
1333   /**
1334    * retrieve a dimension, such as for Jmol
1335    * 
1336    * @param property
1337    * @param def
1338    * @return
1339    */
1340   public static Dimension getDefaultDim(String property, Dimension def)
1341   {
1342     String s = getProperty(property);
1343     if (s != null)
1344     {
1345       if (s.indexOf(',') < 0)
1346       {
1347         s = s.trim().replace(' ', ',');
1348         if (s.indexOf(',') < 0)
1349         {
1350           s += "," + s;
1351         }
1352       }
1353       try
1354       {
1355         int pt = s.indexOf(",");
1356         return new Dimension(Integer.parseInt(s.substring(0, pt)),
1357                 Integer.parseInt(s.substring(pt + 1)));
1358       } catch (NumberFormatException e)
1359       {
1360         System.out.println("Error parsing Dimension property '" + property
1361                 + "' with value '" + s + "'");
1362       }
1363     }
1364     return def;
1365   }
1366
1367
1368 }