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