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