JAL-2527 Added overview prefs - don't get picked up by overview yet
[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 jalview.analysis.AnnotationSorter.SequenceAnnotationOrder;
24 import jalview.bin.Cache;
25 import jalview.gui.Help.HelpId;
26 import jalview.gui.StructureViewer.ViewerType;
27 import jalview.io.FileFormatI;
28 import jalview.io.JalviewFileChooser;
29 import jalview.io.JalviewFileView;
30 import jalview.jbgui.GPreferences;
31 import jalview.jbgui.GSequenceLink;
32 import jalview.schemes.ColourSchemeI;
33 import jalview.schemes.ColourSchemes;
34 import jalview.schemes.ResidueColourScheme;
35 import jalview.urls.UrlLinkTableModel;
36 import jalview.urls.api.UrlProviderFactoryI;
37 import jalview.urls.api.UrlProviderI;
38 import jalview.urls.desktop.DesktopUrlProviderFactory;
39 import jalview.util.MessageManager;
40 import jalview.util.Platform;
41 import jalview.util.UrlConstants;
42 import jalview.ws.sifts.SiftsSettings;
43
44 import java.awt.BorderLayout;
45 import java.awt.Color;
46 import java.awt.Component;
47 import java.awt.Dimension;
48 import java.awt.Font;
49 import java.awt.event.ActionEvent;
50 import java.awt.event.ActionListener;
51 import java.awt.event.MouseEvent;
52 import java.io.File;
53 import java.util.ArrayList;
54 import java.util.List;
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 import javax.swing.ListSelectionModel;
62 import javax.swing.RowFilter;
63 import javax.swing.RowSorter;
64 import javax.swing.SortOrder;
65 import javax.swing.event.DocumentEvent;
66 import javax.swing.event.DocumentListener;
67 import javax.swing.event.ListSelectionEvent;
68 import javax.swing.event.ListSelectionListener;
69 import javax.swing.table.TableCellRenderer;
70 import javax.swing.table.TableColumn;
71 import javax.swing.table.TableModel;
72 import javax.swing.table.TableRowSorter;
73
74 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
75
76 /**
77  * DOCUMENT ME!
78  * 
79  * @author $author$
80  * @version $Revision$
81  */
82 public class Preferences extends GPreferences
83 {
84   public static final String ENABLE_SPLIT_FRAME = "ENABLE_SPLIT_FRAME";
85
86   public static final String SCALE_PROTEIN_TO_CDNA = "SCALE_PROTEIN_TO_CDNA";
87
88   public static final String DEFAULT_COLOUR = "DEFAULT_COLOUR";
89
90   public static final String DEFAULT_COLOUR_PROT = "DEFAULT_COLOUR_PROT";
91
92   public static final String DEFAULT_COLOUR_NUC = "DEFAULT_COLOUR_NUC";
93
94   public static final String ADD_TEMPFACT_ANN = "ADD_TEMPFACT_ANN";
95
96   public static final String ADD_SS_ANN = "ADD_SS_ANN";
97
98   public static final String USE_RNAVIEW = "USE_RNAVIEW";
99
100   public static final String STRUCT_FROM_PDB = "STRUCT_FROM_PDB";
101
102   public static final String STRUCTURE_DISPLAY = "STRUCTURE_DISPLAY";
103
104   public static final String CHIMERA_PATH = "CHIMERA_PATH";
105
106   public static final String SORT_ANNOTATIONS = "SORT_ANNOTATIONS";
107
108   public static final String SHOW_AUTOCALC_ABOVE = "SHOW_AUTOCALC_ABOVE";
109
110   public static final String SHOW_OCCUPANCY = "SHOW_OCCUPANCY";
111
112   public static final String SHOW_OV_HIDDEN_AT_START = "SHOW_OV_HIDDEN_AT_START";
113
114   public static final String USE_LEGACY_GAP = "USE_LEGACY_GAP";
115
116   private static final int MIN_FONT_SIZE = 1;
117
118   private static final int MAX_FONT_SIZE = 30;
119
120   /**
121    * Holds name and link separated with | character. Sequence ID must be
122    * $SEQUENCE_ID$ or $SEQUENCE_ID=/.possible | chars ./=$
123    */
124   public static UrlProviderI sequenceUrlLinks;
125
126   public static UrlLinkTableModel dataModel;
127
128   /**
129    * Holds name and link separated with | character. Sequence IDS and Sequences
130    * must be $SEQUENCEIDS$ or $SEQUENCEIDS=/.possible | chars ./=$ and
131    * $SEQUENCES$ or $SEQUENCES=/.possible | chars ./=$ and separation character
132    * for first and second token specified after a pipe character at end |,|.
133    * (TODO: proper escape for using | to separate ids or sequences
134    */
135
136   public static List<String> groupURLLinks;
137   static
138   {
139     // get links selected to be in the menu (SEQUENCE_LINKS)
140     // and links entered by the user but not selected (STORED_LINKS)
141     String inMenuString = Cache.getDefault("SEQUENCE_LINKS", "");
142     String notInMenuString = Cache.getDefault("STORED_LINKS", "");
143     String defaultUrl = Cache.getDefault("DEFAULT_URL",
144             UrlConstants.DEFAULT_LABEL);
145
146     // if both links lists are empty, add the DEFAULT_URL link
147     // otherwise we assume the default link is in one of the lists
148     if (inMenuString.isEmpty() && notInMenuString.isEmpty())
149     {
150       inMenuString = UrlConstants.DEFAULT_STRING;
151     }
152     UrlProviderFactoryI factory = new DesktopUrlProviderFactory(defaultUrl,
153             inMenuString, notInMenuString);
154     sequenceUrlLinks = factory.createUrlProvider();
155     dataModel = new UrlLinkTableModel(sequenceUrlLinks);
156
157     /**
158      * TODO: reformulate groupURL encoding so two or more can be stored in the
159      * .properties file as '|' separated strings
160      */
161
162     groupURLLinks = new ArrayList<>();
163   }
164
165   JInternalFrame frame;
166
167   DasSourceBrowser dasSource;
168
169   private WsPreferences wsPrefs;
170
171   private OptionsParam promptEachTimeOpt = new OptionsParam(
172           MessageManager.getString("label.prompt_each_time"),
173           "Prompt each time");
174
175   private OptionsParam lineArtOpt = new OptionsParam(
176           MessageManager.getString("label.lineart"), "Lineart");
177
178   private OptionsParam textOpt = new OptionsParam(
179           MessageManager.getString("action.text"), "Text");
180
181   /**
182    * Creates a new Preferences object.
183    */
184   public Preferences()
185   {
186     super();
187     frame = new JInternalFrame();
188     frame.setContentPane(this);
189     dasSource = new DasSourceBrowser();
190     dasTab.add(dasSource, BorderLayout.CENTER);
191     wsPrefs = new WsPreferences();
192     wsTab.add(wsPrefs, BorderLayout.CENTER);
193     int width = 500, height = 450;
194     new jalview.util.Platform();
195     if (Platform.isAMac())
196     {
197       width = 570;
198       height = 480;
199     }
200
201     Desktop.addInternalFrame(frame,
202             MessageManager.getString("label.preferences"), width, height);
203     frame.setMinimumSize(new Dimension(width, height));
204
205     /*
206      * Set Visual tab defaults
207      */
208     seqLimit.setSelected(Cache.getDefault("SHOW_JVSUFFIX", true));
209     rightAlign.setSelected(Cache.getDefault("RIGHT_ALIGN_IDS", false));
210     fullScreen.setSelected(Cache.getDefault("SHOW_FULLSCREEN", false));
211     annotations.setSelected(Cache.getDefault("SHOW_ANNOTATIONS", true));
212
213     conservation.setSelected(Cache.getDefault("SHOW_CONSERVATION", true));
214     quality.setSelected(Cache.getDefault("SHOW_QUALITY", true));
215     identity.setSelected(Cache.getDefault("SHOW_IDENTITY", true));
216     openoverv.setSelected(Cache.getDefault("SHOW_OVERVIEW", false));
217     showUnconserved
218             .setSelected(Cache.getDefault("SHOW_UNCONSERVED", false));
219     showOccupancy.setSelected(Cache.getDefault(SHOW_OCCUPANCY, false));
220     showGroupConsensus
221             .setSelected(Cache.getDefault("SHOW_GROUP_CONSENSUS", false));
222     showGroupConservation.setSelected(
223             Cache.getDefault("SHOW_GROUP_CONSERVATION", false));
224     showConsensHistogram.setSelected(
225             Cache.getDefault("SHOW_CONSENSUS_HISTOGRAM", true));
226     showConsensLogo
227             .setSelected(Cache.getDefault("SHOW_CONSENSUS_LOGO", false));
228     showNpTooltip
229             .setSelected(Cache.getDefault("SHOW_NPFEATS_TOOLTIP", true));
230     showDbRefTooltip
231             .setSelected(Cache.getDefault("SHOW_DBREFS_TOOLTIP", true));
232
233     String[] fonts = java.awt.GraphicsEnvironment
234             .getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
235     for (int i = 0; i < fonts.length; i++)
236     {
237       fontNameCB.addItem(fonts[i]);
238     }
239
240     for (int i = MIN_FONT_SIZE; i <= MAX_FONT_SIZE; i++)
241     {
242       fontSizeCB.addItem(i + "");
243     }
244
245     fontStyleCB.addItem("plain");
246     fontStyleCB.addItem("bold");
247     fontStyleCB.addItem("italic");
248
249     fontNameCB.setSelectedItem(Cache.getDefault("FONT_NAME", "SansSerif"));
250     fontSizeCB.setSelectedItem(Cache.getDefault("FONT_SIZE", "10"));
251     fontStyleCB.setSelectedItem(
252             Cache.getDefault("FONT_STYLE", Font.PLAIN + ""));
253
254     smoothFont.setSelected(Cache.getDefault("ANTI_ALIAS", false));
255     scaleProteinToCdna
256             .setSelected(Cache.getDefault(SCALE_PROTEIN_TO_CDNA, false));
257
258     idItalics.setSelected(Cache.getDefault("ID_ITALICS", true));
259
260     wrap.setSelected(Cache.getDefault("WRAP_ALIGNMENT", false));
261
262     gapSymbolCB.addItem("-");
263     gapSymbolCB.addItem(".");
264
265     gapSymbolCB.setSelectedItem(Cache.getDefault("GAP_SYMBOL", "-"));
266
267     sortby.addItem("No sort");
268     sortby.addItem("Id");
269     sortby.addItem("Pairwise Identity");
270     sortby.setSelectedItem(Cache.getDefault("SORT_ALIGNMENT", "No sort"));
271
272     sortAnnBy.addItem(SequenceAnnotationOrder.NONE.toString());
273     sortAnnBy
274             .addItem(SequenceAnnotationOrder.SEQUENCE_AND_LABEL.toString());
275     sortAnnBy
276             .addItem(SequenceAnnotationOrder.LABEL_AND_SEQUENCE.toString());
277     SequenceAnnotationOrder savedSort = SequenceAnnotationOrder
278             .valueOf(Cache.getDefault(SORT_ANNOTATIONS,
279                     SequenceAnnotationOrder.NONE.name()));
280     sortAnnBy.setSelectedItem(savedSort.toString());
281
282     sortAutocalc.addItem("Autocalculated first");
283     sortAutocalc.addItem("Autocalculated last");
284     final boolean showAbove = Cache.getDefault(SHOW_AUTOCALC_ABOVE, true);
285     sortAutocalc.setSelectedItem(showAbove ? sortAutocalc.getItemAt(0)
286             : sortAutocalc.getItemAt(1));
287     startupCheckbox
288             .setSelected(Cache.getDefault("SHOW_STARTUP_FILE", true));
289     startupFileTextfield.setText(Cache.getDefault("STARTUP_FILE",
290             Cache.getDefault("www.jalview.org", "http://www.jalview.org")
291                     + "/examples/exampleFile_2_3.jar"));
292
293     /*
294      * Set Colours tab defaults
295      */
296     protColour.addItem(ResidueColourScheme.NONE);
297     nucColour.addItem(ResidueColourScheme.NONE);
298     for (ColourSchemeI cs : ColourSchemes.getInstance().getColourSchemes())
299     {
300       String name = cs.getSchemeName();
301       protColour.addItem(name);
302       nucColour.addItem(name);
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(
311             Cache.getDefaultColour("ANNOTATIONCOLOUR_MIN", Color.orange));
312     maxColour.setBackground(
313             Cache.getDefaultColour("ANNOTATIONCOLOUR_MAX", Color.red));
314
315     /*
316      * Set overview panel defaults
317      */
318     gapColour.setBackground(
319             Cache.getDefaultColour("GAP_COLOUR", Color.lightGray));
320     hiddenColour.setBackground(
321             Cache.getDefaultColour("HIDDEN_COLOUR", Color.darkGray));
322     useLegacyGap.setSelected(Cache.getDefault("USE_LEGACY_GAP", false));
323     gapLabel.setEnabled(!useLegacyGap.isSelected());
324     gapColour.setEnabled(!useLegacyGap.isSelected());
325     showHiddenAtStart
326             .setSelected(Cache.getDefault("SHOW_OV_HIDDEN_AT_START", true));
327
328     /*
329      * Set Structure tab defaults.
330      */
331     final boolean structSelected = Cache.getDefault(STRUCT_FROM_PDB, false);
332     structFromPdb.setSelected(structSelected);
333     useRnaView.setSelected(Cache.getDefault(USE_RNAVIEW, false));
334     useRnaView.setEnabled(structSelected);
335     addSecondaryStructure.setSelected(Cache.getDefault(ADD_SS_ANN, false));
336     addSecondaryStructure.setEnabled(structSelected);
337     addTempFactor.setSelected(Cache.getDefault(ADD_TEMPFACT_ANN, false));
338     addTempFactor.setEnabled(structSelected);
339     structViewer.setSelectedItem(
340             Cache.getDefault(STRUCTURE_DISPLAY, ViewerType.JMOL.name()));
341     chimeraPath.setText(Cache.getDefault(CHIMERA_PATH, ""));
342     chimeraPath.addActionListener(new ActionListener()
343     {
344       @Override
345       public void actionPerformed(ActionEvent e)
346       {
347         validateChimeraPath();
348       }
349     });
350
351     if (Cache.getDefault("MAP_WITH_SIFTS", false))
352     {
353       siftsMapping.setSelected(true);
354     }
355     else
356     {
357       nwMapping.setSelected(true);
358     }
359
360     SiftsSettings
361             .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
362
363     /*
364      * Set Connections tab defaults
365      */
366
367     // set up sorting
368     linkUrlTable.setModel(dataModel);
369     final TableRowSorter<TableModel> sorter = new TableRowSorter<>(
370             linkUrlTable.getModel());
371     linkUrlTable.setRowSorter(sorter);
372     List<RowSorter.SortKey> sortKeys = new ArrayList<>();
373
374     UrlLinkTableModel m = (UrlLinkTableModel) linkUrlTable.getModel();
375     sortKeys.add(new RowSorter.SortKey(m.getPrimaryColumn(),
376             SortOrder.DESCENDING));
377     sortKeys.add(new RowSorter.SortKey(m.getSelectedColumn(),
378             SortOrder.DESCENDING));
379     sortKeys.add(
380             new RowSorter.SortKey(m.getNameColumn(), SortOrder.ASCENDING));
381
382     sorter.setSortKeys(sortKeys);
383     sorter.sort();
384
385     // set up filtering
386     ActionListener onReset;
387     onReset = new ActionListener()
388     {
389       @Override
390       public void actionPerformed(ActionEvent e)
391       {
392         filterTB.setText("");
393         sorter.setRowFilter(RowFilter.regexFilter(""));
394       }
395
396     };
397     doReset.addActionListener(onReset);
398
399     // filter to display only custom urls
400     final RowFilter<TableModel, Object> customUrlFilter = new RowFilter<TableModel, Object>()
401     {
402       @Override
403       public boolean include(
404               Entry<? extends TableModel, ? extends Object> entry)
405       {
406         return ((UrlLinkTableModel) entry.getModel()).isUserEntry(entry);
407       }
408     };
409
410     final TableRowSorter<TableModel> customSorter = new TableRowSorter<>(
411             linkUrlTable.getModel());
412     customSorter.setRowFilter(customUrlFilter);
413
414     ActionListener onCustomOnly;
415     onCustomOnly = new ActionListener()
416     {
417       @Override
418       public void actionPerformed(ActionEvent e)
419       {
420         filterTB.setText("");
421         sorter.setRowFilter(customUrlFilter);
422       }
423     };
424     userOnly.addActionListener(onCustomOnly);
425
426     filterTB.getDocument().addDocumentListener(new DocumentListener()
427     {
428       String caseInsensitiveFlag = "(?i)";
429
430       @Override
431       public void changedUpdate(DocumentEvent e)
432       {
433         sorter.setRowFilter(RowFilter
434                 .regexFilter(caseInsensitiveFlag + filterTB.getText()));
435       }
436
437       @Override
438       public void removeUpdate(DocumentEvent e)
439       {
440         sorter.setRowFilter(RowFilter
441                 .regexFilter(caseInsensitiveFlag + filterTB.getText()));
442       }
443
444       @Override
445       public void insertUpdate(DocumentEvent e)
446       {
447         sorter.setRowFilter(RowFilter
448                 .regexFilter(caseInsensitiveFlag + filterTB.getText()));
449       }
450     });
451
452     // set up list selection functionality
453     linkUrlTable.getSelectionModel()
454             .addListSelectionListener(new UrlListSelectionHandler());
455
456     // set up radio buttons
457     int onClickCol = ((UrlLinkTableModel) linkUrlTable.getModel())
458             .getPrimaryColumn();
459     String onClickName = linkUrlTable.getColumnName(onClickCol);
460     linkUrlTable.getColumn(onClickName)
461             .setCellRenderer(new RadioButtonRenderer());
462     linkUrlTable.getColumn(onClickName)
463             .setCellEditor(new RadioButtonEditor());
464
465     // get boolean columns and resize those to min possible
466     for (int column = 0; column < linkUrlTable.getColumnCount(); column++)
467     {
468       if (linkUrlTable.getModel().getColumnClass(column)
469               .equals(Boolean.class))
470       {
471         TableColumn tableColumn = linkUrlTable.getColumnModel()
472                 .getColumn(column);
473         int preferredWidth = tableColumn.getMinWidth();
474
475         TableCellRenderer cellRenderer = linkUrlTable.getCellRenderer(0,
476                 column);
477         Component c = linkUrlTable.prepareRenderer(cellRenderer, 0, column);
478         int cwidth = c.getPreferredSize().width
479                 + linkUrlTable.getIntercellSpacing().width;
480         preferredWidth = Math.max(preferredWidth, cwidth);
481
482         tableColumn.setPreferredWidth(preferredWidth);
483       }
484     }
485
486     useProxy.setSelected(Cache.getDefault("USE_PROXY", false));
487     useProxy_actionPerformed(); // make sure useProxy is correctly initialised
488     proxyServerTB.setText(Cache.getDefault("PROXY_SERVER", ""));
489     proxyPortTB.setText(Cache.getDefault("PROXY_PORT", ""));
490
491     defaultBrowser.setText(Cache.getDefault("DEFAULT_BROWSER", ""));
492
493     usagestats.setSelected(Cache.getDefault("USAGESTATS", false));
494     // note antisense here: default is true
495     questionnaire
496             .setSelected(Cache.getProperty("NOQUESTIONNAIRES") == null);
497     versioncheck.setSelected(Cache.getDefault("VERSION_CHECK", true));
498
499     /*
500      * Set Output tab defaults
501      */
502     epsRendering.addItem(promptEachTimeOpt);
503     epsRendering.addItem(lineArtOpt);
504     epsRendering.addItem(textOpt);
505     String defaultEPS = Cache.getDefault("EPS_RENDERING",
506             "Prompt each time");
507     if (defaultEPS.equalsIgnoreCase("Text"))
508     {
509       epsRendering.setSelectedItem(textOpt);
510     }
511     else if (defaultEPS.equalsIgnoreCase("Lineart"))
512     {
513       epsRendering.setSelectedItem(lineArtOpt);
514     }
515     else
516     {
517       epsRendering.setSelectedItem(promptEachTimeOpt);
518     }
519     autoIdWidth.setSelected(Cache.getDefault("FIGURE_AUTOIDWIDTH", false));
520     userIdWidth.setEnabled(!autoIdWidth.isSelected());
521     userIdWidthlabel.setEnabled(!autoIdWidth.isSelected());
522     Integer wi = Cache.getIntegerProperty("FIGURE_USERIDWIDTH");
523     userIdWidth.setText(wi == null ? "" : wi.toString());
524     blcjv.setSelected(Cache.getDefault("BLC_JVSUFFIX", true));
525     clustaljv.setSelected(Cache.getDefault("CLUSTAL_JVSUFFIX", true));
526     fastajv.setSelected(Cache.getDefault("FASTA_JVSUFFIX", true));
527     msfjv.setSelected(Cache.getDefault("MSF_JVSUFFIX", true));
528     pfamjv.setSelected(Cache.getDefault("PFAM_JVSUFFIX", true));
529     pileupjv.setSelected(Cache.getDefault("PILEUP_JVSUFFIX", true));
530     pirjv.setSelected(Cache.getDefault("PIR_JVSUFFIX", true));
531     modellerOutput.setSelected(Cache.getDefault("PIR_MODELLER", false));
532     embbedBioJSON
533             .setSelected(Cache.getDefault("EXPORT_EMBBED_BIOJSON", true));
534
535     /*
536      * Set Editing tab defaults
537      */
538     autoCalculateConsCheck
539             .setSelected(Cache.getDefault("AUTO_CALC_CONSENSUS", true));
540     padGaps.setSelected(Cache.getDefault("PAD_GAPS", false));
541     sortByTree.setSelected(Cache.getDefault("SORT_BY_TREE", false));
542
543     annotations_actionPerformed(null); // update the display of the annotation
544                                        // settings
545   }
546
547   /**
548    * Save user selections on the Preferences tabs to the Cache and write out to
549    * file.
550    * 
551    * @param e
552    */
553   @Override
554   public void ok_actionPerformed(ActionEvent e)
555   {
556     if (!validateSettings())
557     {
558       return;
559     }
560
561     /*
562      * Save Visual settings
563      */
564     Cache.applicationProperties.setProperty("SHOW_JVSUFFIX",
565             Boolean.toString(seqLimit.isSelected()));
566     Cache.applicationProperties.setProperty("RIGHT_ALIGN_IDS",
567             Boolean.toString(rightAlign.isSelected()));
568     Cache.applicationProperties.setProperty("SHOW_FULLSCREEN",
569             Boolean.toString(fullScreen.isSelected()));
570     Cache.applicationProperties.setProperty("SHOW_OVERVIEW",
571             Boolean.toString(openoverv.isSelected()));
572     Cache.applicationProperties.setProperty("SHOW_ANNOTATIONS",
573             Boolean.toString(annotations.isSelected()));
574     Cache.applicationProperties.setProperty("SHOW_CONSERVATION",
575             Boolean.toString(conservation.isSelected()));
576     Cache.applicationProperties.setProperty("SHOW_QUALITY",
577             Boolean.toString(quality.isSelected()));
578     Cache.applicationProperties.setProperty("SHOW_IDENTITY",
579             Boolean.toString(identity.isSelected()));
580
581     Cache.applicationProperties.setProperty("GAP_SYMBOL",
582             gapSymbolCB.getSelectedItem().toString());
583
584     Cache.applicationProperties.setProperty("FONT_NAME",
585             fontNameCB.getSelectedItem().toString());
586     Cache.applicationProperties.setProperty("FONT_STYLE",
587             fontStyleCB.getSelectedItem().toString());
588     Cache.applicationProperties.setProperty("FONT_SIZE",
589             fontSizeCB.getSelectedItem().toString());
590
591     Cache.applicationProperties.setProperty("ID_ITALICS",
592             Boolean.toString(idItalics.isSelected()));
593     Cache.applicationProperties.setProperty("SHOW_UNCONSERVED",
594             Boolean.toString(showUnconserved.isSelected()));
595     Cache.applicationProperties.setProperty(SHOW_OCCUPANCY,
596             Boolean.toString(showOccupancy.isSelected()));
597     Cache.applicationProperties.setProperty("SHOW_GROUP_CONSENSUS",
598             Boolean.toString(showGroupConsensus.isSelected()));
599     Cache.applicationProperties.setProperty("SHOW_GROUP_CONSERVATION",
600             Boolean.toString(showGroupConservation.isSelected()));
601     Cache.applicationProperties.setProperty("SHOW_CONSENSUS_HISTOGRAM",
602             Boolean.toString(showConsensHistogram.isSelected()));
603     Cache.applicationProperties.setProperty("SHOW_CONSENSUS_LOGO",
604             Boolean.toString(showConsensLogo.isSelected()));
605     Cache.applicationProperties.setProperty("ANTI_ALIAS",
606             Boolean.toString(smoothFont.isSelected()));
607     Cache.applicationProperties.setProperty(SCALE_PROTEIN_TO_CDNA,
608             Boolean.toString(scaleProteinToCdna.isSelected()));
609     Cache.applicationProperties.setProperty("SHOW_NPFEATS_TOOLTIP",
610             Boolean.toString(showNpTooltip.isSelected()));
611     Cache.applicationProperties.setProperty("SHOW_DBREFS_TOOLTIP",
612             Boolean.toString(showDbRefTooltip.isSelected()));
613
614     Cache.applicationProperties.setProperty("WRAP_ALIGNMENT",
615             Boolean.toString(wrap.isSelected()));
616
617     Cache.applicationProperties.setProperty("STARTUP_FILE",
618             startupFileTextfield.getText());
619     Cache.applicationProperties.setProperty("SHOW_STARTUP_FILE",
620             Boolean.toString(startupCheckbox.isSelected()));
621
622     Cache.applicationProperties.setProperty("SORT_ALIGNMENT",
623             sortby.getSelectedItem().toString());
624
625     // convert description of sort order to enum name for save
626     SequenceAnnotationOrder annSortOrder = SequenceAnnotationOrder
627             .forDescription(sortAnnBy.getSelectedItem().toString());
628     if (annSortOrder != null)
629     {
630       Cache.applicationProperties.setProperty(SORT_ANNOTATIONS,
631               annSortOrder.name());
632     }
633
634     final boolean showAutocalcFirst = sortAutocalc.getSelectedIndex() == 0;
635     Cache.applicationProperties.setProperty(SHOW_AUTOCALC_ABOVE,
636             Boolean.valueOf(showAutocalcFirst).toString());
637
638     /*
639      * Save Colours settings
640      */
641     Cache.applicationProperties.setProperty(DEFAULT_COLOUR_PROT,
642             protColour.getSelectedItem().toString());
643     Cache.applicationProperties.setProperty(DEFAULT_COLOUR_NUC,
644             nucColour.getSelectedItem().toString());
645     Cache.setColourProperty("ANNOTATIONCOLOUR_MIN",
646             minColour.getBackground());
647     Cache.setColourProperty("ANNOTATIONCOLOUR_MAX",
648             maxColour.getBackground());
649
650     /*
651      * Save Overview settings
652      */
653     Cache.setColourProperty("GAP_COLOUR", gapColour.getBackground());
654     Cache.setColourProperty("HIDDEN_COLOUR", hiddenColour.getBackground());
655     Cache.applicationProperties.setProperty(USE_LEGACY_GAP,
656             Boolean.toString(useLegacyGap.isSelected()));
657     Cache.applicationProperties.setProperty(SHOW_OV_HIDDEN_AT_START,
658             Boolean.toString(showHiddenAtStart.isSelected()));
659
660     /*
661      * Save Structure settings
662      */
663     Cache.applicationProperties.setProperty(ADD_TEMPFACT_ANN,
664             Boolean.toString(addTempFactor.isSelected()));
665     Cache.applicationProperties.setProperty(ADD_SS_ANN,
666             Boolean.toString(addSecondaryStructure.isSelected()));
667     Cache.applicationProperties.setProperty(USE_RNAVIEW,
668             Boolean.toString(useRnaView.isSelected()));
669     Cache.applicationProperties.setProperty(STRUCT_FROM_PDB,
670             Boolean.toString(structFromPdb.isSelected()));
671     Cache.applicationProperties.setProperty(STRUCTURE_DISPLAY,
672             structViewer.getSelectedItem().toString());
673     Cache.setOrRemove(CHIMERA_PATH, chimeraPath.getText());
674     Cache.applicationProperties.setProperty("MAP_WITH_SIFTS",
675             Boolean.toString(siftsMapping.isSelected()));
676     SiftsSettings.setMapWithSifts(siftsMapping.isSelected());
677
678     /*
679      * Save Output settings
680      */
681     Cache.applicationProperties.setProperty("EPS_RENDERING",
682             ((OptionsParam) epsRendering.getSelectedItem()).getCode());
683
684     /*
685      * Save Connections settings
686      */
687     Cache.setOrRemove("DEFAULT_BROWSER", defaultBrowser.getText());
688
689     jalview.util.BrowserLauncher.resetBrowser();
690
691     // save user-defined and selected links
692     String menuLinks = sequenceUrlLinks.writeUrlsAsString(true);
693     if (menuLinks.isEmpty())
694     {
695       Cache.applicationProperties.remove("SEQUENCE_LINKS");
696     }
697     else
698     {
699       Cache.applicationProperties.setProperty("SEQUENCE_LINKS",
700               menuLinks.toString());
701     }
702
703     String nonMenuLinks = sequenceUrlLinks.writeUrlsAsString(false);
704     if (nonMenuLinks.isEmpty())
705     {
706       Cache.applicationProperties.remove("STORED_LINKS");
707     }
708     else
709     {
710       Cache.applicationProperties.setProperty("STORED_LINKS",
711               nonMenuLinks.toString());
712     }
713
714     Cache.applicationProperties.setProperty("DEFAULT_URL",
715             sequenceUrlLinks.getPrimaryUrlId());
716
717     Cache.applicationProperties.setProperty("USE_PROXY",
718             Boolean.toString(useProxy.isSelected()));
719
720     Cache.setOrRemove("PROXY_SERVER", proxyServerTB.getText());
721
722     Cache.setOrRemove("PROXY_PORT", proxyPortTB.getText());
723
724     if (useProxy.isSelected())
725     {
726       System.setProperty("http.proxyHost", proxyServerTB.getText());
727       System.setProperty("http.proxyPort", proxyPortTB.getText());
728     }
729     else
730     {
731       System.setProperty("http.proxyHost", "");
732       System.setProperty("http.proxyPort", "");
733     }
734     Cache.setProperty("VERSION_CHECK",
735             Boolean.toString(versioncheck.isSelected()));
736     if (Cache.getProperty("USAGESTATS") != null || usagestats.isSelected())
737     {
738       // default is false - we only set this if the user has actively agreed
739       Cache.setProperty("USAGESTATS",
740               Boolean.toString(usagestats.isSelected()));
741     }
742     if (!questionnaire.isSelected())
743     {
744       Cache.setProperty("NOQUESTIONNAIRES", "true");
745     }
746     else
747     {
748       // special - made easy to edit a property file to disable questionnaires
749       // by just adding the given line
750       Cache.removeProperty("NOQUESTIONNAIRES");
751     }
752
753     /*
754      * Save Output settings
755      */
756     Cache.applicationProperties.setProperty("BLC_JVSUFFIX",
757             Boolean.toString(blcjv.isSelected()));
758     Cache.applicationProperties.setProperty("CLUSTAL_JVSUFFIX",
759             Boolean.toString(clustaljv.isSelected()));
760     Cache.applicationProperties.setProperty("FASTA_JVSUFFIX",
761             Boolean.toString(fastajv.isSelected()));
762     Cache.applicationProperties.setProperty("MSF_JVSUFFIX",
763             Boolean.toString(msfjv.isSelected()));
764     Cache.applicationProperties.setProperty("PFAM_JVSUFFIX",
765             Boolean.toString(pfamjv.isSelected()));
766     Cache.applicationProperties.setProperty("PILEUP_JVSUFFIX",
767             Boolean.toString(pileupjv.isSelected()));
768     Cache.applicationProperties.setProperty("PIR_JVSUFFIX",
769             Boolean.toString(pirjv.isSelected()));
770     Cache.applicationProperties.setProperty("PIR_MODELLER",
771             Boolean.toString(modellerOutput.isSelected()));
772     Cache.applicationProperties.setProperty("EXPORT_EMBBED_BIOJSON",
773             Boolean.toString(embbedBioJSON.isSelected()));
774     jalview.io.PIRFile.useModellerOutput = modellerOutput.isSelected();
775
776     Cache.applicationProperties.setProperty("FIGURE_AUTOIDWIDTH",
777             Boolean.toString(autoIdWidth.isSelected()));
778     userIdWidth_actionPerformed();
779     Cache.applicationProperties.setProperty("FIGURE_USERIDWIDTH",
780             userIdWidth.getText());
781
782     /*
783      * Save Editing settings
784      */
785     Cache.applicationProperties.setProperty("AUTO_CALC_CONSENSUS",
786             Boolean.toString(autoCalculateConsCheck.isSelected()));
787     Cache.applicationProperties.setProperty("SORT_BY_TREE",
788             Boolean.toString(sortByTree.isSelected()));
789     Cache.applicationProperties.setProperty("PAD_GAPS",
790             Boolean.toString(padGaps.isSelected()));
791
792     dasSource.saveProperties(Cache.applicationProperties);
793     wsPrefs.updateAndRefreshWsMenuConfig(false);
794     Cache.saveProperties();
795     Desktop.instance.doConfigureStructurePrefs();
796     try
797     {
798       frame.setClosed(true);
799     } catch (Exception ex)
800     {
801     }
802   }
803
804   /**
805    * Do any necessary validation before saving settings. Return focus to the
806    * first tab which fails validation.
807    * 
808    * @return
809    */
810   private boolean validateSettings()
811   {
812     if (!validateStructure())
813     {
814       structureTab.requestFocusInWindow();
815       return false;
816     }
817     return true;
818   }
819
820   @Override
821   protected boolean validateStructure()
822   {
823     return validateChimeraPath();
824
825   }
826
827   /**
828    * DOCUMENT ME!
829    */
830   @Override
831   public void startupFileTextfield_mouseClicked()
832   {
833     String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
834     JalviewFileChooser chooser = JalviewFileChooser
835             .forRead(Cache.getProperty("LAST_DIRECTORY"), fileFormat);
836     chooser.setFileView(new JalviewFileView());
837     chooser.setDialogTitle(
838             MessageManager.getString("label.select_startup_file"));
839
840     int value = chooser.showOpenDialog(this);
841
842     if (value == JalviewFileChooser.APPROVE_OPTION)
843     {
844       FileFormatI format = chooser.getSelectedFormat();
845       if (format != null)
846       {
847         Cache.applicationProperties.setProperty("DEFAULT_FILE_FORMAT",
848                 format.getName());
849       }
850       startupFileTextfield
851               .setText(chooser.getSelectedFile().getAbsolutePath());
852     }
853   }
854
855   /**
856    * DOCUMENT ME!
857    * 
858    * @param e
859    *          DOCUMENT ME!
860    */
861   @Override
862   public void cancel_actionPerformed(ActionEvent e)
863   {
864     try
865     {
866       wsPrefs.updateWsMenuConfig(true);
867       wsPrefs.refreshWs_actionPerformed(e);
868       frame.setClosed(true);
869     } catch (Exception ex)
870     {
871     }
872   }
873
874   /**
875    * DOCUMENT ME!
876    * 
877    * @param e
878    *          DOCUMENT ME!
879    */
880   @Override
881   public void annotations_actionPerformed(ActionEvent e)
882   {
883     conservation.setEnabled(annotations.isSelected());
884     quality.setEnabled(annotations.isSelected());
885     identity.setEnabled(annotations.isSelected());
886     showOccupancy.setEnabled(annotations.isSelected());
887     showGroupConsensus.setEnabled(annotations.isSelected());
888     showGroupConservation.setEnabled(annotations.isSelected());
889     showConsensHistogram.setEnabled(annotations.isSelected()
890             && (identity.isSelected() || showGroupConsensus.isSelected()));
891     showConsensLogo.setEnabled(annotations.isSelected()
892             && (identity.isSelected() || showGroupConsensus.isSelected()));
893   }
894
895   @Override
896   public void newLink_actionPerformed(ActionEvent e)
897   {
898     GSequenceLink link = new GSequenceLink();
899     boolean valid = false;
900     while (!valid)
901     {
902       if (JvOptionPane.showInternalConfirmDialog(Desktop.desktop, link,
903               MessageManager.getString("label.new_sequence_url_link"),
904               JvOptionPane.OK_CANCEL_OPTION, -1,
905               null) == JvOptionPane.OK_OPTION)
906       {
907         if (link.checkValid())
908         {
909           if (((UrlLinkTableModel) linkUrlTable.getModel())
910                   .isUniqueName(link.getName()))
911           {
912             ((UrlLinkTableModel) linkUrlTable.getModel())
913                     .insertRow(link.getName(), link.getURL());
914             valid = true;
915           }
916           else
917           {
918             link.notifyDuplicate();
919             continue;
920           }
921         }
922       }
923       else
924       {
925         break;
926       }
927     }
928   }
929
930   @Override
931   public void editLink_actionPerformed(ActionEvent e)
932   {
933     GSequenceLink link = new GSequenceLink();
934
935     int index = linkUrlTable.getSelectedRow();
936     if (index == -1)
937     {
938       // button no longer enabled if row is not selected
939       Cache.log.debug("Edit with no row selected in linkUrlTable");
940       return;
941     }
942
943     int nameCol = ((UrlLinkTableModel) linkUrlTable.getModel())
944             .getNameColumn();
945     int urlCol = ((UrlLinkTableModel) linkUrlTable.getModel())
946             .getUrlColumn();
947     String oldName = linkUrlTable.getValueAt(index, nameCol).toString();
948     link.setName(oldName);
949     link.setURL(linkUrlTable.getValueAt(index, urlCol).toString());
950
951     boolean valid = false;
952     while (!valid)
953     {
954       if (JvOptionPane.showInternalConfirmDialog(Desktop.desktop, link,
955               MessageManager.getString("label.edit_sequence_url_link"),
956               JvOptionPane.OK_CANCEL_OPTION, -1,
957               null) == JvOptionPane.OK_OPTION)
958       {
959         if (link.checkValid())
960         {
961           if ((oldName.equals(link.getName()))
962                   || (((UrlLinkTableModel) linkUrlTable.getModel())
963                           .isUniqueName(link.getName())))
964           {
965             linkUrlTable.setValueAt(link.getName(), index, nameCol);
966             linkUrlTable.setValueAt(link.getURL(), index, urlCol);
967             valid = true;
968           }
969           else
970           {
971             link.notifyDuplicate();
972             continue;
973           }
974         }
975       }
976       else
977       {
978         break;
979       }
980     }
981   }
982
983   @Override
984   public void deleteLink_actionPerformed(ActionEvent e)
985   {
986     int index = linkUrlTable.getSelectedRow();
987     int modelIndex = -1;
988     if (index == -1)
989     {
990       // button no longer enabled if row is not selected
991       Cache.log.debug("Delete with no row selected in linkUrlTable");
992       return;
993     }
994     else
995     {
996       modelIndex = linkUrlTable.convertRowIndexToModel(index);
997     }
998
999     // make sure we use the model index to delete, and not the table index
1000     ((UrlLinkTableModel) linkUrlTable.getModel()).removeRow(modelIndex);
1001   }
1002
1003   @Override
1004   public void defaultBrowser_mouseClicked(MouseEvent e)
1005   {
1006     JFileChooser chooser = new JFileChooser(".");
1007     chooser.setDialogTitle(
1008             MessageManager.getString("label.select_default_browser"));
1009
1010     int value = chooser.showOpenDialog(this);
1011
1012     if (value == JFileChooser.APPROVE_OPTION)
1013     {
1014       defaultBrowser.setText(chooser.getSelectedFile().getAbsolutePath());
1015     }
1016
1017   }
1018
1019   /*
1020    * (non-Javadoc)
1021    * 
1022    * @see
1023    * jalview.jbgui.GPreferences#showunconserved_actionPerformed(java.awt.event
1024    * .ActionEvent)
1025    */
1026   @Override
1027   protected void showunconserved_actionPerformed(ActionEvent e)
1028   {
1029     // TODO Auto-generated method stub
1030     super.showunconserved_actionPerformed(e);
1031   }
1032
1033   public static List<String> getGroupURLLinks()
1034   {
1035     return groupURLLinks;
1036   }
1037
1038   @Override
1039   public void minColour_actionPerformed(JPanel panel)
1040   {
1041     Color col = JColorChooser.showDialog(this,
1042             MessageManager.getString("label.select_colour_minimum_value"),
1043             minColour.getBackground());
1044     if (col != null)
1045     {
1046       panel.setBackground(col);
1047     }
1048     panel.repaint();
1049   }
1050
1051   @Override
1052   public void maxColour_actionPerformed(JPanel panel)
1053   {
1054     Color col = JColorChooser.showDialog(this,
1055             MessageManager.getString("label.select_colour_maximum_value"),
1056             maxColour.getBackground());
1057     if (col != null)
1058     {
1059       panel.setBackground(col);
1060     }
1061     panel.repaint();
1062   }
1063
1064   @Override
1065   public void gapColour_actionPerformed(JPanel gap)
1066   {
1067     if (!useLegacyGap.isSelected())
1068     {
1069       Color col = JColorChooser.showDialog(this,
1070               MessageManager.getString("label.select_gap_colour"),
1071               gapColour.getBackground());
1072       if (col != null)
1073       {
1074         gap.setBackground(col);
1075       }
1076       gap.repaint();
1077     }
1078   }
1079
1080   @Override
1081   public void hiddenColour_actionPerformed(JPanel hidden)
1082   {
1083     Color col = JColorChooser.showDialog(this,
1084             MessageManager.getString("label.select_hidden_colour"),
1085             hiddenColour.getBackground());
1086     if (col != null)
1087     {
1088       hidden.setBackground(col);
1089     }
1090     hidden.repaint();
1091   }
1092
1093   @Override
1094   protected void userIdWidth_actionPerformed()
1095   {
1096     try
1097     {
1098       String val = userIdWidth.getText().trim();
1099       if (val.length() > 0)
1100       {
1101         Integer iw = Integer.parseInt(val);
1102         if (iw.intValue() < 12)
1103         {
1104           throw new NumberFormatException();
1105         }
1106         userIdWidth.setText(iw.toString());
1107       }
1108     } catch (NumberFormatException x)
1109     {
1110       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1111               MessageManager
1112                       .getString("warn.user_defined_width_requirements"),
1113               MessageManager.getString("label.invalid_id_column_width"),
1114               JvOptionPane.WARNING_MESSAGE);
1115       userIdWidth.setText("");
1116     }
1117   }
1118
1119   @Override
1120   protected void autoIdWidth_actionPerformed()
1121   {
1122     userIdWidth.setEnabled(!autoIdWidth.isSelected());
1123     userIdWidthlabel.setEnabled(!autoIdWidth.isSelected());
1124   }
1125
1126   /**
1127    * Returns true if chimera path is to a valid executable, else show an error
1128    * dialog.
1129    */
1130   private boolean validateChimeraPath()
1131   {
1132     if (chimeraPath.getText().trim().length() > 0)
1133     {
1134       File f = new File(chimeraPath.getText());
1135       if (!f.canExecute())
1136       {
1137         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1138                 MessageManager.getString("label.invalid_chimera_path"),
1139                 MessageManager.getString("label.invalid_name"),
1140                 JvOptionPane.ERROR_MESSAGE);
1141         return false;
1142       }
1143     }
1144     return true;
1145   }
1146
1147   /**
1148    * If Chimera is selected, check it can be found on default or user-specified
1149    * path, if not show a warning/help dialog.
1150    */
1151   @Override
1152   protected void structureViewer_actionPerformed(String selectedItem)
1153   {
1154     if (!selectedItem.equals(ViewerType.CHIMERA.name()))
1155     {
1156       return;
1157     }
1158     boolean found = false;
1159
1160     /*
1161      * Try user-specified and standard paths for Chimera executable.
1162      */
1163     List<String> paths = StructureManager.getChimeraPaths();
1164     paths.add(0, chimeraPath.getText());
1165     for (String path : paths)
1166     {
1167       if (new File(path.trim()).canExecute())
1168       {
1169         found = true;
1170         break;
1171       }
1172     }
1173     if (!found)
1174     {
1175       String[] options = { "OK", "Help" };
1176       int showHelp = JvOptionPane.showInternalOptionDialog(Desktop.desktop,
1177               JvSwingUtils.wrapTooltip(true,
1178                       MessageManager.getString("label.chimera_missing")),
1179               "", JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
1180               null, options, options[0]);
1181       if (showHelp == JvOptionPane.NO_OPTION)
1182       {
1183         try
1184         {
1185           Help.showHelpWindow(HelpId.StructureViewer);
1186         } catch (HelpSetException e)
1187         {
1188           e.printStackTrace();
1189         }
1190       }
1191     }
1192   }
1193
1194   public class OptionsParam
1195   {
1196     private String name;
1197
1198     private String code;
1199
1200     public OptionsParam(String name, String code)
1201     {
1202       this.name = name;
1203       this.code = code;
1204     }
1205
1206     public String getName()
1207     {
1208       return name;
1209     }
1210
1211     public void setName(String name)
1212     {
1213       this.name = name;
1214     }
1215
1216     public String getCode()
1217     {
1218       return code;
1219     }
1220
1221     public void setCode(String code)
1222     {
1223       this.code = code;
1224     }
1225
1226     @Override
1227     public String toString()
1228     {
1229       return name;
1230     }
1231
1232     @Override
1233     public boolean equals(Object that)
1234     {
1235       if (!(that instanceof OptionsParam))
1236       {
1237         return false;
1238       }
1239       return this.code.equalsIgnoreCase(((OptionsParam) that).code);
1240     }
1241
1242     @Override
1243     public int hashCode()
1244     {
1245       return name.hashCode() + code.hashCode();
1246     }
1247   }
1248
1249   private class UrlListSelectionHandler implements ListSelectionListener
1250   {
1251
1252     @Override
1253     public void valueChanged(ListSelectionEvent e)
1254     {
1255       ListSelectionModel lsm = (ListSelectionModel) e.getSource();
1256
1257       int index = lsm.getMinSelectionIndex();
1258       if (index == -1)
1259       {
1260         // no selection, so disable delete/edit buttons
1261         editLink.setEnabled(false);
1262         deleteLink.setEnabled(false);
1263         return;
1264       }
1265       int modelIndex = linkUrlTable.convertRowIndexToModel(index);
1266
1267       // enable/disable edit and delete link buttons
1268       if (((UrlLinkTableModel) linkUrlTable.getModel())
1269               .isRowDeletable(modelIndex))
1270       {
1271         deleteLink.setEnabled(true);
1272       }
1273       else
1274       {
1275         deleteLink.setEnabled(false);
1276       }
1277
1278       if (((UrlLinkTableModel) linkUrlTable.getModel())
1279               .isRowEditable(modelIndex))
1280       {
1281         editLink.setEnabled(true);
1282       }
1283       else
1284       {
1285         editLink.setEnabled(false);
1286       }
1287     }
1288   }
1289 }