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