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