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