JAL-2360 refactoring for JalviewColourScheme enum,
[jalview.git] / src / jalview / gui / Preferences.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.gui;
22
23 import static jalview.util.UrlConstants.DB_ACCESSION;
24 import static jalview.util.UrlConstants.EMBLEBI_STRING;
25 import static jalview.util.UrlConstants.SEQUENCE_ID;
26 import static jalview.util.UrlConstants.SRS_STRING;
27
28 import jalview.analysis.AnnotationSorter.SequenceAnnotationOrder;
29 import jalview.bin.Cache;
30 import jalview.gui.Help.HelpId;
31 import jalview.gui.StructureViewer.ViewerType;
32 import jalview.io.FileFormatI;
33 import jalview.io.JalviewFileChooser;
34 import jalview.io.JalviewFileView;
35 import jalview.jbgui.GPreferences;
36 import jalview.jbgui.GSequenceLink;
37 import jalview.schemes.JalviewColourScheme;
38 import jalview.schemes.ResidueColourScheme;
39 import jalview.util.MessageManager;
40 import jalview.util.Platform;
41 import jalview.ws.sifts.SiftsSettings;
42
43 import java.awt.BorderLayout;
44 import java.awt.Color;
45 import java.awt.Dimension;
46 import java.awt.Font;
47 import java.awt.event.ActionEvent;
48 import java.awt.event.ActionListener;
49 import java.awt.event.MouseEvent;
50 import java.io.File;
51 import java.util.ArrayList;
52 import java.util.List;
53 import java.util.StringTokenizer;
54 import java.util.Vector;
55
56 import javax.help.HelpSetException;
57 import javax.swing.JColorChooser;
58 import javax.swing.JFileChooser;
59 import javax.swing.JInternalFrame;
60 import javax.swing.JPanel;
61
62 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
63
64 /**
65  * DOCUMENT ME!
66  * 
67  * @author $author$
68  * @version $Revision$
69  */
70 public class Preferences extends GPreferences
71 {
72   public static final String ENABLE_SPLIT_FRAME = "ENABLE_SPLIT_FRAME";
73
74   public static final String SCALE_PROTEIN_TO_CDNA = "SCALE_PROTEIN_TO_CDNA";
75
76   public static final String DEFAULT_COLOUR = "DEFAULT_COLOUR";
77
78   public static final String DEFAULT_COLOUR_PROT = "DEFAULT_COLOUR_PROT";
79
80   public static final String DEFAULT_COLOUR_NUC = "DEFAULT_COLOUR_NUC";
81
82   public static final String ADD_TEMPFACT_ANN = "ADD_TEMPFACT_ANN";
83
84   public static final String ADD_SS_ANN = "ADD_SS_ANN";
85
86   public static final String USE_RNAVIEW = "USE_RNAVIEW";
87
88   public static final String STRUCT_FROM_PDB = "STRUCT_FROM_PDB";
89
90   public static final String STRUCTURE_DISPLAY = "STRUCTURE_DISPLAY";
91
92   public static final String CHIMERA_PATH = "CHIMERA_PATH";
93
94   public static final String SORT_ANNOTATIONS = "SORT_ANNOTATIONS";
95
96   public static final String SHOW_AUTOCALC_ABOVE = "SHOW_AUTOCALC_ABOVE";
97
98   private static final int MIN_FONT_SIZE = 1;
99
100   private static final int MAX_FONT_SIZE = 30;
101
102   /**
103    * Holds name and link separated with | character. Sequence ID must be
104    * $SEQUENCE_ID$ or $SEQUENCE_ID=/.possible | chars ./=$
105    */
106   public static Vector<String> sequenceURLLinks;
107
108   /**
109    * Holds name and link separated with | character. Sequence IDS and Sequences
110    * must be $SEQUENCEIDS$ or $SEQUENCEIDS=/.possible | chars ./=$ and
111    * $SEQUENCES$ or $SEQUENCES=/.possible | chars ./=$ and separation character
112    * for first and second token specified after a pipe character at end |,|.
113    * (TODO: proper escape for using | to separate ids or sequences
114    */
115
116   public static List<String> groupURLLinks;
117   static
118   {
119     String string = Cache.getDefault("SEQUENCE_LINKS", EMBLEBI_STRING);
120     sequenceURLLinks = new Vector<String>();
121
122     try
123     {
124       StringTokenizer st = new StringTokenizer(string, "|");
125       while (st.hasMoreElements())
126       {
127         String name = st.nextToken();
128         String url = st.nextToken();
129         // check for '|' within a regex
130         int rxstart = url.indexOf("$" + DB_ACCESSION + "$");
131         if (rxstart == -1)
132         {
133           rxstart = url.indexOf("$" + SEQUENCE_ID + "$");
134         }
135         while (rxstart == -1 && url.indexOf("/=$") == -1)
136         {
137           url = url + "|" + st.nextToken();
138         }
139         sequenceURLLinks.addElement(name + "|" + url);
140       }
141     } catch (Exception ex)
142     {
143       System.out.println(ex + "\nError parsing sequence links");
144     }
145     {
146       // upgrade old SRS link
147       int srsPos = sequenceURLLinks.indexOf(SRS_STRING);
148       if (srsPos > -1)
149       {
150         sequenceURLLinks.setElementAt(EMBLEBI_STRING, srsPos);
151       }
152     }
153
154     /**
155      * TODO: reformulate groupURL encoding so two or more can be stored in the
156      * .properties file as '|' separated strings
157      */
158
159     groupURLLinks = new ArrayList<String>();
160   }
161
162   Vector<String> nameLinks, urlLinks;
163
164   JInternalFrame frame;
165
166   DasSourceBrowser dasSource;
167
168   private WsPreferences wsPrefs;
169
170   private OptionsParam promptEachTimeOpt = new OptionsParam(
171           MessageManager.getString("label.prompt_each_time"),
172           "Prompt each time");
173
174   private OptionsParam lineArtOpt = new OptionsParam(
175           MessageManager.getString("label.lineart"), "Lineart");
176
177   private OptionsParam textOpt = new OptionsParam(
178           MessageManager.getString("action.text"), "Text");
179
180   /**
181    * Creates a new Preferences object.
182    */
183   public Preferences()
184   {
185     super();
186     frame = new JInternalFrame();
187     frame.setContentPane(this);
188     dasSource = new DasSourceBrowser();
189     dasTab.add(dasSource, BorderLayout.CENTER);
190     wsPrefs = new WsPreferences();
191     wsTab.add(wsPrefs, BorderLayout.CENTER);
192     int width = 500, height = 450;
193     new jalview.util.Platform();
194     if (Platform.isAMac())
195     {
196       width = 570;
197       height = 480;
198     }
199
200     Desktop.addInternalFrame(frame,
201             MessageManager.getString("label.preferences"), width, height);
202     frame.setMinimumSize(new Dimension(width, height));
203
204     /*
205      * Set Visual tab defaults
206      */
207     seqLimit.setSelected(Cache.getDefault("SHOW_JVSUFFIX", true));
208     rightAlign.setSelected(Cache.getDefault("RIGHT_ALIGN_IDS", false));
209     fullScreen.setSelected(Cache.getDefault("SHOW_FULLSCREEN", false));
210     annotations.setSelected(Cache.getDefault("SHOW_ANNOTATIONS", true));
211
212     conservation.setSelected(Cache.getDefault("SHOW_CONSERVATION", true));
213     quality.setSelected(Cache.getDefault("SHOW_QUALITY", true));
214     identity.setSelected(Cache.getDefault("SHOW_IDENTITY", true));
215     openoverv.setSelected(Cache.getDefault("SHOW_OVERVIEW", false));
216     showUnconserved
217             .setSelected(Cache.getDefault("SHOW_UNCONSERVED", false));
218     showGroupConsensus.setSelected(Cache.getDefault("SHOW_GROUP_CONSENSUS",
219             false));
220     showGroupConservation.setSelected(Cache.getDefault(
221             "SHOW_GROUP_CONSERVATION", false));
222     showConsensHistogram.setSelected(Cache.getDefault(
223             "SHOW_CONSENSUS_HISTOGRAM", true));
224     showConsensLogo.setSelected(Cache.getDefault("SHOW_CONSENSUS_LOGO",
225             false));
226     showNpTooltip.setSelected(Cache
227             .getDefault("SHOW_NPFEATS_TOOLTIP", true));
228     showDbRefTooltip.setSelected(Cache.getDefault("SHOW_DBREFS_TOOLTIP",
229             true));
230
231     String[] fonts = java.awt.GraphicsEnvironment
232             .getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
233     for (int i = 0; i < fonts.length; i++)
234     {
235       fontNameCB.addItem(fonts[i]);
236     }
237
238     for (int i = MIN_FONT_SIZE; i <= MAX_FONT_SIZE; i++)
239     {
240       fontSizeCB.addItem(i + "");
241     }
242
243     fontStyleCB.addItem("plain");
244     fontStyleCB.addItem("bold");
245     fontStyleCB.addItem("italic");
246
247     fontNameCB.setSelectedItem(Cache.getDefault("FONT_NAME", "SansSerif"));
248     fontSizeCB.setSelectedItem(Cache.getDefault("FONT_SIZE", "10"));
249     fontStyleCB.setSelectedItem(Cache.getDefault("FONT_STYLE", Font.PLAIN
250             + ""));
251
252     smoothFont.setSelected(Cache.getDefault("ANTI_ALIAS", false));
253     scaleProteinToCdna.setSelected(Cache.getDefault(SCALE_PROTEIN_TO_CDNA,
254             false));
255
256     idItalics.setSelected(Cache.getDefault("ID_ITALICS", true));
257
258     wrap.setSelected(Cache.getDefault("WRAP_ALIGNMENT", false));
259
260     gapSymbolCB.addItem("-");
261     gapSymbolCB.addItem(".");
262
263     gapSymbolCB.setSelectedItem(Cache.getDefault("GAP_SYMBOL", "-"));
264
265     sortby.addItem("No sort");
266     sortby.addItem("Id");
267     sortby.addItem("Pairwise Identity");
268     sortby.setSelectedItem(Cache.getDefault("SORT_ALIGNMENT", "No sort"));
269
270     sortAnnBy.addItem(SequenceAnnotationOrder.NONE.toString());
271     sortAnnBy
272             .addItem(SequenceAnnotationOrder.SEQUENCE_AND_LABEL.toString());
273     sortAnnBy
274             .addItem(SequenceAnnotationOrder.LABEL_AND_SEQUENCE.toString());
275     SequenceAnnotationOrder savedSort = SequenceAnnotationOrder
276             .valueOf(Cache.getDefault(SORT_ANNOTATIONS,
277                     SequenceAnnotationOrder.NONE.name()));
278     sortAnnBy.setSelectedItem(savedSort.toString());
279
280     sortAutocalc.addItem("Autocalculated first");
281     sortAutocalc.addItem("Autocalculated last");
282     final boolean showAbove = Cache.getDefault(SHOW_AUTOCALC_ABOVE, true);
283     sortAutocalc.setSelectedItem(showAbove ? sortAutocalc.getItemAt(0)
284             : sortAutocalc.getItemAt(1));
285     startupCheckbox
286             .setSelected(Cache.getDefault("SHOW_STARTUP_FILE", true));
287     startupFileTextfield.setText(Cache.getDefault("STARTUP_FILE",
288             Cache.getDefault("www.jalview.org", "http://www.jalview.org")
289                     + "/examples/exampleFile_2_3.jar"));
290
291     /*
292      * Set Colours tab defaults
293      */
294     protColour.addItem(ResidueColourScheme.NONE);
295     nucColour.addItem(ResidueColourScheme.NONE);
296     for (JalviewColourScheme cs : JalviewColourScheme.values())
297     {
298       if (cs != JalviewColourScheme.UserDefined)
299       {
300         protColour.addItem(cs.toString());
301         nucColour.addItem(cs.toString());
302       }
303     }
304     String oldProp = Cache.getDefault(DEFAULT_COLOUR,
305             ResidueColourScheme.NONE);
306     String newProp = Cache.getDefault(DEFAULT_COLOUR_PROT, null);
307     protColour.setSelectedItem(newProp != null ? newProp : oldProp);
308     newProp = Cache.getDefault(DEFAULT_COLOUR_NUC, null);
309     nucColour.setSelectedItem(newProp != null ? newProp : oldProp);
310     minColour.setBackground(Cache.getDefaultColour("ANNOTATIONCOLOUR_MIN",
311             Color.orange));
312     maxColour.setBackground(Cache.getDefaultColour("ANNOTATIONCOLOUR_MAX",
313             Color.red));
314
315     /*
316      * Set Structure tab defaults.
317      */
318     final boolean structSelected = Cache.getDefault(STRUCT_FROM_PDB, false);
319     structFromPdb.setSelected(structSelected);
320     useRnaView.setSelected(Cache.getDefault(USE_RNAVIEW, false));
321     useRnaView.setEnabled(structSelected);
322     addSecondaryStructure.setSelected(Cache.getDefault(ADD_SS_ANN, false));
323     addSecondaryStructure.setEnabled(structSelected);
324     addTempFactor.setSelected(Cache.getDefault(ADD_TEMPFACT_ANN, false));
325     addTempFactor.setEnabled(structSelected);
326     structViewer.setSelectedItem(Cache.getDefault(STRUCTURE_DISPLAY,
327             ViewerType.JMOL.name()));
328     chimeraPath.setText(Cache.getDefault(CHIMERA_PATH, ""));
329     chimeraPath.addActionListener(new ActionListener()
330     {
331       @Override
332       public void actionPerformed(ActionEvent e)
333       {
334         validateChimeraPath();
335       }
336     });
337
338     if (Cache.getDefault("MAP_WITH_SIFTS", false))
339     {
340       siftsMapping.setSelected(true);
341     }
342     else
343     {
344       nwMapping.setSelected(true);
345     }
346
347     SiftsSettings
348             .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
349
350     /*
351      * Set Connections tab defaults
352      */
353     nameLinks = new Vector<String>();
354     urlLinks = new Vector<String>();
355     for (int i = 0; i < sequenceURLLinks.size(); i++)
356     {
357       String link = sequenceURLLinks.elementAt(i).toString();
358       nameLinks.addElement(link.substring(0, link.indexOf("|")));
359       urlLinks.addElement(link.substring(link.indexOf("|") + 1));
360     }
361
362     updateLinkData();
363
364     useProxy.setSelected(Cache.getDefault("USE_PROXY", false));
365     proxyServerTB.setEnabled(useProxy.isSelected());
366     proxyPortTB.setEnabled(useProxy.isSelected());
367     proxyServerTB.setText(Cache.getDefault("PROXY_SERVER", ""));
368     proxyPortTB.setText(Cache.getDefault("PROXY_PORT", ""));
369
370     defaultBrowser.setText(Cache.getDefault("DEFAULT_BROWSER", ""));
371
372     usagestats.setSelected(Cache.getDefault("USAGESTATS", false));
373     // note antisense here: default is true
374     questionnaire
375             .setSelected(Cache.getProperty("NOQUESTIONNAIRES") == null);
376     versioncheck.setSelected(Cache.getDefault("VERSION_CHECK", true));
377
378     /*
379      * Set Output tab defaults
380      */
381     epsRendering.addItem(promptEachTimeOpt);
382     epsRendering.addItem(lineArtOpt);
383     epsRendering.addItem(textOpt);
384     String defaultEPS = Cache.getDefault("EPS_RENDERING",
385             "Prompt each time");
386     if (defaultEPS.equalsIgnoreCase("Text"))
387     {
388       epsRendering.setSelectedItem(textOpt);
389     }
390     else if (defaultEPS.equalsIgnoreCase("Lineart"))
391     {
392       epsRendering.setSelectedItem(lineArtOpt);
393     }
394     else
395     {
396       epsRendering.setSelectedItem(promptEachTimeOpt);
397     }
398     autoIdWidth.setSelected(Cache.getDefault("FIGURE_AUTOIDWIDTH", false));
399     userIdWidth.setEnabled(!autoIdWidth.isSelected());
400     userIdWidthlabel.setEnabled(!autoIdWidth.isSelected());
401     Integer wi = Cache.getIntegerProperty("FIGURE_USERIDWIDTH");
402     userIdWidth.setText(wi == null ? "" : wi.toString());
403     blcjv.setSelected(Cache.getDefault("BLC_JVSUFFIX", true));
404     clustaljv.setSelected(Cache.getDefault("CLUSTAL_JVSUFFIX", true));
405     fastajv.setSelected(Cache.getDefault("FASTA_JVSUFFIX", true));
406     msfjv.setSelected(Cache.getDefault("MSF_JVSUFFIX", true));
407     pfamjv.setSelected(Cache.getDefault("PFAM_JVSUFFIX", true));
408     pileupjv.setSelected(Cache.getDefault("PILEUP_JVSUFFIX", true));
409     pirjv.setSelected(Cache.getDefault("PIR_JVSUFFIX", true));
410     modellerOutput.setSelected(Cache.getDefault("PIR_MODELLER", false));
411     embbedBioJSON.setSelected(Cache.getDefault("EXPORT_EMBBED_BIOJSON",
412             true));
413
414     /*
415      * Set Editing tab defaults
416      */
417     autoCalculateConsCheck.setSelected(Cache.getDefault(
418             "AUTO_CALC_CONSENSUS", true));
419     padGaps.setSelected(Cache.getDefault("PAD_GAPS", false));
420     sortByTree.setSelected(Cache.getDefault("SORT_BY_TREE", false));
421
422     annotations_actionPerformed(null); // update the display of the annotation
423                                        // settings
424   }
425
426   /**
427    * Save user selections on the Preferences tabs to the Cache and write out to
428    * file.
429    * 
430    * @param e
431    */
432   @Override
433   public void ok_actionPerformed(ActionEvent e)
434   {
435     if (!validateSettings())
436     {
437       return;
438     }
439
440     /*
441      * Save Visual settings
442      */
443     Cache.applicationProperties.setProperty("SHOW_JVSUFFIX",
444             Boolean.toString(seqLimit.isSelected()));
445     Cache.applicationProperties.setProperty("RIGHT_ALIGN_IDS",
446             Boolean.toString(rightAlign.isSelected()));
447     Cache.applicationProperties.setProperty("SHOW_FULLSCREEN",
448             Boolean.toString(fullScreen.isSelected()));
449     Cache.applicationProperties.setProperty("SHOW_OVERVIEW",
450             Boolean.toString(openoverv.isSelected()));
451     Cache.applicationProperties.setProperty("SHOW_ANNOTATIONS",
452             Boolean.toString(annotations.isSelected()));
453     Cache.applicationProperties.setProperty("SHOW_CONSERVATION",
454             Boolean.toString(conservation.isSelected()));
455     Cache.applicationProperties.setProperty("SHOW_QUALITY",
456             Boolean.toString(quality.isSelected()));
457     Cache.applicationProperties.setProperty("SHOW_IDENTITY",
458             Boolean.toString(identity.isSelected()));
459
460     Cache.applicationProperties.setProperty("GAP_SYMBOL", gapSymbolCB
461             .getSelectedItem().toString());
462
463     Cache.applicationProperties.setProperty("FONT_NAME", fontNameCB
464             .getSelectedItem().toString());
465     Cache.applicationProperties.setProperty("FONT_STYLE", fontStyleCB
466             .getSelectedItem().toString());
467     Cache.applicationProperties.setProperty("FONT_SIZE", fontSizeCB
468             .getSelectedItem().toString());
469
470     Cache.applicationProperties.setProperty("ID_ITALICS",
471             Boolean.toString(idItalics.isSelected()));
472     Cache.applicationProperties.setProperty("SHOW_UNCONSERVED",
473             Boolean.toString(showUnconserved.isSelected()));
474     Cache.applicationProperties.setProperty("SHOW_GROUP_CONSENSUS",
475             Boolean.toString(showGroupConsensus.isSelected()));
476     Cache.applicationProperties.setProperty("SHOW_GROUP_CONSERVATION",
477             Boolean.toString(showGroupConservation.isSelected()));
478     Cache.applicationProperties.setProperty("SHOW_CONSENSUS_HISTOGRAM",
479             Boolean.toString(showConsensHistogram.isSelected()));
480     Cache.applicationProperties.setProperty("SHOW_CONSENSUS_LOGO",
481             Boolean.toString(showConsensLogo.isSelected()));
482     Cache.applicationProperties.setProperty("ANTI_ALIAS",
483             Boolean.toString(smoothFont.isSelected()));
484     Cache.applicationProperties.setProperty(SCALE_PROTEIN_TO_CDNA,
485             Boolean.toString(scaleProteinToCdna.isSelected()));
486     Cache.applicationProperties.setProperty("SHOW_NPFEATS_TOOLTIP",
487             Boolean.toString(showNpTooltip.isSelected()));
488     Cache.applicationProperties.setProperty("SHOW_DBREFS_TOOLTIP",
489             Boolean.toString(showDbRefTooltip.isSelected()));
490
491     Cache.applicationProperties.setProperty("WRAP_ALIGNMENT",
492             Boolean.toString(wrap.isSelected()));
493
494     Cache.applicationProperties.setProperty("STARTUP_FILE",
495             startupFileTextfield.getText());
496     Cache.applicationProperties.setProperty("SHOW_STARTUP_FILE",
497             Boolean.toString(startupCheckbox.isSelected()));
498
499     Cache.applicationProperties.setProperty("SORT_ALIGNMENT", sortby
500             .getSelectedItem().toString());
501
502     // convert description of sort order to enum name for save
503     SequenceAnnotationOrder annSortOrder = SequenceAnnotationOrder
504             .forDescription(sortAnnBy.getSelectedItem().toString());
505     if (annSortOrder != null)
506     {
507       Cache.applicationProperties.setProperty(SORT_ANNOTATIONS,
508               annSortOrder.name());
509     }
510
511     final boolean showAutocalcFirst = sortAutocalc.getSelectedIndex() == 0;
512     Cache.applicationProperties.setProperty(SHOW_AUTOCALC_ABOVE, Boolean
513             .valueOf(showAutocalcFirst).toString());
514
515     /*
516      * Save Colours settings
517      */
518     Cache.applicationProperties.setProperty(DEFAULT_COLOUR_PROT, protColour
519             .getSelectedItem().toString());
520     Cache.applicationProperties.setProperty(DEFAULT_COLOUR_NUC, nucColour
521             .getSelectedItem().toString());
522     Cache.setColourProperty("ANNOTATIONCOLOUR_MIN",
523             minColour.getBackground());
524     Cache.setColourProperty("ANNOTATIONCOLOUR_MAX",
525             maxColour.getBackground());
526
527     /*
528      * Save Structure settings
529      */
530     Cache.applicationProperties.setProperty(ADD_TEMPFACT_ANN,
531             Boolean.toString(addTempFactor.isSelected()));
532     Cache.applicationProperties.setProperty(ADD_SS_ANN,
533             Boolean.toString(addSecondaryStructure.isSelected()));
534     Cache.applicationProperties.setProperty(USE_RNAVIEW,
535             Boolean.toString(useRnaView.isSelected()));
536     Cache.applicationProperties.setProperty(STRUCT_FROM_PDB,
537             Boolean.toString(structFromPdb.isSelected()));
538     Cache.applicationProperties.setProperty(STRUCTURE_DISPLAY, structViewer
539             .getSelectedItem().toString());
540     Cache.setOrRemove(CHIMERA_PATH, chimeraPath.getText());
541     Cache.applicationProperties.setProperty("MAP_WITH_SIFTS",
542             Boolean.toString(siftsMapping.isSelected()));
543     SiftsSettings.setMapWithSifts(siftsMapping.isSelected());
544
545     /*
546      * Save Output settings
547      */
548     Cache.applicationProperties.setProperty("EPS_RENDERING",
549             ((OptionsParam) epsRendering.getSelectedItem()).getCode());
550
551     /*
552      * Save Connections settings
553      */
554     Cache.setOrRemove("DEFAULT_BROWSER", defaultBrowser.getText());
555
556     jalview.util.BrowserLauncher.resetBrowser();
557
558     if (nameLinks.size() > 0)
559     {
560       StringBuffer links = new StringBuffer();
561       sequenceURLLinks = new Vector<String>();
562       for (int i = 0; i < nameLinks.size(); i++)
563       {
564         sequenceURLLinks.addElement(nameLinks.elementAt(i) + "|"
565                 + urlLinks.elementAt(i));
566         links.append(sequenceURLLinks.elementAt(i).toString());
567         links.append("|");
568       }
569       // remove last "|"
570       links.setLength(links.length() - 1);
571       Cache.applicationProperties.setProperty("SEQUENCE_LINKS",
572               links.toString());
573     }
574     else
575     {
576       Cache.applicationProperties.remove("SEQUENCE_LINKS");
577       sequenceURLLinks.clear();
578     }
579
580     Cache.applicationProperties.setProperty("USE_PROXY",
581             Boolean.toString(useProxy.isSelected()));
582
583     Cache.setOrRemove("PROXY_SERVER", proxyServerTB.getText());
584
585     Cache.setOrRemove("PROXY_PORT", proxyPortTB.getText());
586
587     if (useProxy.isSelected())
588     {
589       System.setProperty("http.proxyHost", proxyServerTB.getText());
590       System.setProperty("http.proxyPort", proxyPortTB.getText());
591     }
592     else
593     {
594       System.setProperty("http.proxyHost", "");
595       System.setProperty("http.proxyPort", "");
596     }
597     Cache.setProperty("VERSION_CHECK",
598             Boolean.toString(versioncheck.isSelected()));
599     if (Cache.getProperty("USAGESTATS") != null || usagestats.isSelected())
600     {
601       // default is false - we only set this if the user has actively agreed
602       Cache.setProperty("USAGESTATS",
603               Boolean.toString(usagestats.isSelected()));
604     }
605     if (!questionnaire.isSelected())
606     {
607       Cache.setProperty("NOQUESTIONNAIRES", "true");
608     }
609     else
610     {
611       // special - made easy to edit a property file to disable questionnaires
612       // by just adding the given line
613       Cache.removeProperty("NOQUESTIONNAIRES");
614     }
615
616     /*
617      * Save Output settings
618      */
619     Cache.applicationProperties.setProperty("BLC_JVSUFFIX",
620             Boolean.toString(blcjv.isSelected()));
621     Cache.applicationProperties.setProperty("CLUSTAL_JVSUFFIX",
622             Boolean.toString(clustaljv.isSelected()));
623     Cache.applicationProperties.setProperty("FASTA_JVSUFFIX",
624             Boolean.toString(fastajv.isSelected()));
625     Cache.applicationProperties.setProperty("MSF_JVSUFFIX",
626             Boolean.toString(msfjv.isSelected()));
627     Cache.applicationProperties.setProperty("PFAM_JVSUFFIX",
628             Boolean.toString(pfamjv.isSelected()));
629     Cache.applicationProperties.setProperty("PILEUP_JVSUFFIX",
630             Boolean.toString(pileupjv.isSelected()));
631     Cache.applicationProperties.setProperty("PIR_JVSUFFIX",
632             Boolean.toString(pirjv.isSelected()));
633     Cache.applicationProperties.setProperty("PIR_MODELLER",
634             Boolean.toString(modellerOutput.isSelected()));
635     Cache.applicationProperties.setProperty("EXPORT_EMBBED_BIOJSON",
636             Boolean.toString(embbedBioJSON.isSelected()));
637     jalview.io.PIRFile.useModellerOutput = modellerOutput.isSelected();
638
639     Cache.applicationProperties.setProperty("FIGURE_AUTOIDWIDTH",
640             Boolean.toString(autoIdWidth.isSelected()));
641     userIdWidth_actionPerformed();
642     Cache.applicationProperties.setProperty("FIGURE_USERIDWIDTH",
643             userIdWidth.getText());
644
645     /*
646      * Save Editing settings
647      */
648     Cache.applicationProperties.setProperty("AUTO_CALC_CONSENSUS",
649             Boolean.toString(autoCalculateConsCheck.isSelected()));
650     Cache.applicationProperties.setProperty("SORT_BY_TREE",
651             Boolean.toString(sortByTree.isSelected()));
652     Cache.applicationProperties.setProperty("PAD_GAPS",
653             Boolean.toString(padGaps.isSelected()));
654
655     dasSource.saveProperties(Cache.applicationProperties);
656     wsPrefs.updateAndRefreshWsMenuConfig(false);
657     Cache.saveProperties();
658     Desktop.instance.doConfigureStructurePrefs();
659     try
660     {
661       frame.setClosed(true);
662     } catch (Exception ex)
663     {
664     }
665   }
666
667   /**
668    * Do any necessary validation before saving settings. Return focus to the
669    * first tab which fails validation.
670    * 
671    * @return
672    */
673   private boolean validateSettings()
674   {
675     if (!validateStructure())
676     {
677       structureTab.requestFocusInWindow();
678       return false;
679     }
680     return true;
681   }
682
683   @Override
684   protected boolean validateStructure()
685   {
686     return validateChimeraPath();
687
688   }
689
690   /**
691    * DOCUMENT ME!
692    */
693   @Override
694   public void startupFileTextfield_mouseClicked()
695   {
696     String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
697     JalviewFileChooser chooser = JalviewFileChooser.forRead(
698             Cache.getProperty("LAST_DIRECTORY"), fileFormat);
699     chooser.setFileView(new JalviewFileView());
700     chooser.setDialogTitle(MessageManager
701             .getString("label.select_startup_file"));
702
703     int value = chooser.showOpenDialog(this);
704
705     if (value == JalviewFileChooser.APPROVE_OPTION)
706     {
707       FileFormatI format = chooser.getSelectedFormat();
708       if (format != null)
709       {
710         Cache.applicationProperties.setProperty("DEFAULT_FILE_FORMAT",
711                 format.toString());
712       }
713       startupFileTextfield.setText(chooser.getSelectedFile()
714               .getAbsolutePath());
715     }
716   }
717
718   /**
719    * DOCUMENT ME!
720    * 
721    * @param e
722    *          DOCUMENT ME!
723    */
724   @Override
725   public void cancel_actionPerformed(ActionEvent e)
726   {
727     try
728     {
729       wsPrefs.updateWsMenuConfig(true);
730       wsPrefs.refreshWs_actionPerformed(e);
731       frame.setClosed(true);
732     } catch (Exception ex)
733     {
734     }
735   }
736
737   /**
738    * DOCUMENT ME!
739    * 
740    * @param e
741    *          DOCUMENT ME!
742    */
743   @Override
744   public void annotations_actionPerformed(ActionEvent e)
745   {
746     conservation.setEnabled(annotations.isSelected());
747     quality.setEnabled(annotations.isSelected());
748     identity.setEnabled(annotations.isSelected());
749     showGroupConsensus.setEnabled(annotations.isSelected());
750     showGroupConservation.setEnabled(annotations.isSelected());
751     showConsensHistogram.setEnabled(annotations.isSelected()
752             && (identity.isSelected() || showGroupConsensus.isSelected()));
753     showConsensLogo.setEnabled(annotations.isSelected()
754             && (identity.isSelected() || showGroupConsensus.isSelected()));
755   }
756
757   @Override
758   public void newLink_actionPerformed(ActionEvent e)
759   {
760
761     GSequenceLink link = new GSequenceLink();
762     boolean valid = false;
763     while (!valid)
764     {
765       if (JvOptionPane.showInternalConfirmDialog(Desktop.desktop, link,
766               MessageManager.getString("label.new_sequence_url_link"),
767               JvOptionPane.OK_CANCEL_OPTION, -1, null) == JvOptionPane.OK_OPTION)
768       {
769         if (link.checkValid())
770         {
771           nameLinks.addElement(link.getName());
772           urlLinks.addElement(link.getURL());
773           updateLinkData();
774           valid = true;
775         }
776       }
777       else
778       {
779         break;
780       }
781     }
782   }
783
784   @Override
785   public void editLink_actionPerformed(ActionEvent e)
786   {
787     GSequenceLink link = new GSequenceLink();
788
789     int index = linkNameList.getSelectedIndex();
790     if (index == -1)
791     {
792       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
793               MessageManager.getString("label.no_link_selected"),
794               MessageManager.getString("label.no_link_selected"),
795               JvOptionPane.WARNING_MESSAGE);
796       return;
797     }
798
799     link.setName(nameLinks.elementAt(index).toString());
800     link.setURL(urlLinks.elementAt(index).toString());
801
802     boolean valid = false;
803     while (!valid)
804     {
805
806       if (JvOptionPane.showInternalConfirmDialog(Desktop.desktop, link,
807               MessageManager.getString("label.new_sequence_url_link"),
808               JvOptionPane.OK_CANCEL_OPTION, -1, null) == JvOptionPane.OK_OPTION)
809       {
810         if (link.checkValid())
811         {
812           nameLinks.setElementAt(link.getName(), index);
813           urlLinks.setElementAt(link.getURL(), index);
814           updateLinkData();
815           valid = true;
816         }
817       }
818
819       else
820       {
821         break;
822       }
823     }
824   }
825
826   @Override
827   public void deleteLink_actionPerformed(ActionEvent e)
828   {
829     int index = linkNameList.getSelectedIndex();
830     if (index == -1)
831     {
832       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
833               MessageManager.getString("label.no_link_selected"),
834               MessageManager.getString("label.no_link_selected"),
835               JvOptionPane.WARNING_MESSAGE);
836       return;
837     }
838     nameLinks.removeElementAt(index);
839     urlLinks.removeElementAt(index);
840     updateLinkData();
841   }
842
843   void updateLinkData()
844   {
845     linkNameList.setListData(nameLinks);
846     linkURLList.setListData(urlLinks);
847   }
848
849   @Override
850   public void defaultBrowser_mouseClicked(MouseEvent e)
851   {
852     JFileChooser chooser = new JFileChooser(".");
853     chooser.setDialogTitle(MessageManager
854             .getString("label.select_default_browser"));
855
856     int value = chooser.showOpenDialog(this);
857
858     if (value == JFileChooser.APPROVE_OPTION)
859     {
860       defaultBrowser.setText(chooser.getSelectedFile().getAbsolutePath());
861     }
862
863   }
864
865   /*
866    * (non-Javadoc)
867    * 
868    * @see
869    * jalview.jbgui.GPreferences#showunconserved_actionPerformed(java.awt.event
870    * .ActionEvent)
871    */
872   @Override
873   protected void showunconserved_actionPerformed(ActionEvent e)
874   {
875     // TODO Auto-generated method stub
876     super.showunconserved_actionPerformed(e);
877   }
878
879   public static List<String> getGroupURLLinks()
880   {
881     return groupURLLinks;
882   }
883
884   @Override
885   public void minColour_actionPerformed(JPanel panel)
886   {
887     Color col = JColorChooser.showDialog(this,
888             MessageManager.getString("label.select_colour_minimum_value"),
889             minColour.getBackground());
890     if (col != null)
891     {
892       panel.setBackground(col);
893     }
894     panel.repaint();
895   }
896
897   @Override
898   public void maxColour_actionPerformed(JPanel panel)
899   {
900     Color col = JColorChooser.showDialog(this,
901             MessageManager.getString("label.select_colour_maximum_value"),
902             maxColour.getBackground());
903     if (col != null)
904     {
905       panel.setBackground(col);
906     }
907     panel.repaint();
908   }
909
910   @Override
911   protected void userIdWidth_actionPerformed()
912   {
913     try
914     {
915       String val = userIdWidth.getText().trim();
916       if (val.length() > 0)
917       {
918         Integer iw = Integer.parseInt(val);
919         if (iw.intValue() < 12)
920         {
921           throw new NumberFormatException();
922         }
923         userIdWidth.setText(iw.toString());
924       }
925     } catch (NumberFormatException x)
926     {
927       JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
928               .getString("warn.user_defined_width_requirements"),
929               MessageManager.getString("label.invalid_id_column_width"),
930               JvOptionPane.WARNING_MESSAGE);
931       userIdWidth.setText("");
932     }
933   }
934
935   @Override
936   protected void autoIdWidth_actionPerformed()
937   {
938     userIdWidth.setEnabled(!autoIdWidth.isSelected());
939     userIdWidthlabel.setEnabled(!autoIdWidth.isSelected());
940   }
941
942   /**
943    * Returns true if chimera path is to a valid executable, else show an error
944    * dialog.
945    */
946   private boolean validateChimeraPath()
947   {
948     if (chimeraPath.getText().trim().length() > 0)
949     {
950       File f = new File(chimeraPath.getText());
951       if (!f.canExecute())
952       {
953         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
954                 MessageManager.getString("label.invalid_chimera_path"),
955                 MessageManager.getString("label.invalid_name"),
956                 JvOptionPane.ERROR_MESSAGE);
957         return false;
958       }
959     }
960     return true;
961   }
962
963   /**
964    * If Chimera is selected, check it can be found on default or user-specified
965    * path, if not show a warning/help dialog.
966    */
967   @Override
968   protected void structureViewer_actionPerformed(String selectedItem)
969   {
970     if (!selectedItem.equals(ViewerType.CHIMERA.name()))
971     {
972       return;
973     }
974     boolean found = false;
975
976     /*
977      * Try user-specified and standard paths for Chimera executable.
978      */
979     List<String> paths = StructureManager.getChimeraPaths();
980     paths.add(0, chimeraPath.getText());
981     for (String path : paths)
982     {
983       if (new File(path.trim()).canExecute())
984       {
985         found = true;
986         break;
987       }
988     }
989     if (!found)
990     {
991       String[] options = { "OK", "Help" };
992       int showHelp = JvOptionPane.showInternalOptionDialog(
993               Desktop.desktop,
994               JvSwingUtils.wrapTooltip(true,
995                       MessageManager.getString("label.chimera_missing")),
996               "", JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
997               null, options, options[0]);
998       if (showHelp == JvOptionPane.NO_OPTION)
999       {
1000         try
1001         {
1002           Help.showHelpWindow(HelpId.StructureViewer);
1003         } catch (HelpSetException e)
1004         {
1005           e.printStackTrace();
1006         }
1007       }
1008     }
1009   }
1010
1011   public class OptionsParam
1012   {
1013     private String name;
1014
1015     private String code;
1016
1017     public OptionsParam(String name, String code)
1018     {
1019       this.name = name;
1020       this.code = code;
1021     }
1022
1023     public String getName()
1024     {
1025       return name;
1026     }
1027
1028     public void setName(String name)
1029     {
1030       this.name = name;
1031     }
1032
1033     public String getCode()
1034     {
1035       return code;
1036     }
1037
1038     public void setCode(String code)
1039     {
1040       this.code = code;
1041     }
1042
1043     @Override
1044     public String toString()
1045     {
1046       return name;
1047     }
1048
1049     @Override
1050     public boolean equals(Object that)
1051     {
1052       if (!(that instanceof OptionsParam))
1053       {
1054         return false;
1055       }
1056       return this.code.equalsIgnoreCase(((OptionsParam) that).code);
1057     }
1058
1059     @Override
1060     public int hashCode()
1061     {
1062       return name.hashCode() + code.hashCode();
1063     }
1064   }
1065 }