JAL-2418 source formatting
[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
217             .setSelected(Cache.getDefault("SHOW_GROUP_CONSENSUS", false));
218     showGroupConservation.setSelected(
219             Cache.getDefault("SHOW_GROUP_CONSERVATION", false));
220     showConsensHistogram.setSelected(
221             Cache.getDefault("SHOW_CONSENSUS_HISTOGRAM", true));
222     showConsensLogo
223             .setSelected(Cache.getDefault("SHOW_CONSENSUS_LOGO", false));
224     showNpTooltip
225             .setSelected(Cache.getDefault("SHOW_NPFEATS_TOOLTIP", true));
226     showDbRefTooltip
227             .setSelected(Cache.getDefault("SHOW_DBREFS_TOOLTIP", 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(
248             Cache.getDefault("FONT_STYLE", Font.PLAIN + ""));
249
250     smoothFont.setSelected(Cache.getDefault("ANTI_ALIAS", false));
251     scaleProteinToCdna
252             .setSelected(Cache.getDefault(SCALE_PROTEIN_TO_CDNA, 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(
307             Cache.getDefaultColour("ANNOTATIONCOLOUR_MIN", Color.orange));
308     maxColour.setBackground(
309             Cache.getDefaultColour("ANNOTATIONCOLOUR_MAX", 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(
323             Cache.getDefault(STRUCTURE_DISPLAY, 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(
363             new RowSorter.SortKey(m.getNameColumn(), 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
417                 .regexFilter(caseInsensitiveFlag + filterTB.getText()));
418       }
419
420       @Override
421       public void removeUpdate(DocumentEvent e)
422       {
423         sorter.setRowFilter(RowFilter
424                 .regexFilter(caseInsensitiveFlag + filterTB.getText()));
425       }
426
427       @Override
428       public void insertUpdate(DocumentEvent e)
429       {
430         sorter.setRowFilter(RowFilter
431                 .regexFilter(caseInsensitiveFlag + filterTB.getText()));
432       }
433     });
434
435     // set up list selection functionality
436     linkUrlTable.getSelectionModel()
437             .addListSelectionListener(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)
444             .setCellRenderer(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()
455                 .getColumn(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
516             .setSelected(Cache.getDefault("EXPORT_EMBBED_BIOJSON", true));
517
518     /*
519      * Set Editing tab defaults
520      */
521     autoCalculateConsCheck
522             .setSelected(Cache.getDefault("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",
565             gapSymbolCB.getSelectedItem().toString());
566
567     Cache.applicationProperties.setProperty("FONT_NAME",
568             fontNameCB.getSelectedItem().toString());
569     Cache.applicationProperties.setProperty("FONT_STYLE",
570             fontStyleCB.getSelectedItem().toString());
571     Cache.applicationProperties.setProperty("FONT_SIZE",
572             fontSizeCB.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",
606             sortby.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,
619             Boolean.valueOf(showAutocalcFirst).toString());
620
621     /*
622      * Save Colours settings
623      */
624     Cache.applicationProperties.setProperty(DEFAULT_COLOUR_PROT,
625             protColour.getSelectedItem().toString());
626     Cache.applicationProperties.setProperty(DEFAULT_COLOUR_NUC,
627             nucColour.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,
645             structViewer.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
808             .forRead(Cache.getProperty("LAST_DIRECTORY"), fileFormat);
809     chooser.setFileView(new JalviewFileView());
810     chooser.setDialogTitle(
811             MessageManager.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
824               .setText(chooser.getSelectedFile().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,
878               null) == JvOptionPane.OK_OPTION)
879       {
880         if (link.checkValid())
881         {
882           if (((UrlLinkTableModel) linkUrlTable.getModel())
883                   .isUniqueName(link.getName()))
884           {
885             ((UrlLinkTableModel) linkUrlTable.getModel())
886                     .insertRow(link.getName(), link.getURL());
887             valid = true;
888           }
889           else
890           {
891             link.notifyDuplicate();
892             continue;
893           }
894         }
895       }
896       else
897       {
898         break;
899       }
900     }
901   }
902
903   @Override
904   public void editLink_actionPerformed(ActionEvent e)
905   {
906     GSequenceLink link = new GSequenceLink();
907
908     int index = linkUrlTable.getSelectedRow();
909     if (index == -1)
910     {
911       // button no longer enabled if row is not selected
912       Cache.log.debug("Edit with no row selected in linkUrlTable");
913       return;
914     }
915
916     int nameCol = ((UrlLinkTableModel) linkUrlTable.getModel())
917             .getNameColumn();
918     int urlCol = ((UrlLinkTableModel) linkUrlTable.getModel())
919             .getUrlColumn();
920     String oldName = linkUrlTable.getValueAt(index, nameCol).toString();
921     link.setName(oldName);
922     link.setURL(linkUrlTable.getValueAt(index, urlCol).toString());
923
924     boolean valid = false;
925     while (!valid)
926     {
927       if (JvOptionPane.showInternalConfirmDialog(Desktop.desktop, link,
928               MessageManager.getString("label.edit_sequence_url_link"),
929               JvOptionPane.OK_CANCEL_OPTION, -1,
930               null) == JvOptionPane.OK_OPTION)
931       {
932         if (link.checkValid())
933         {
934           if ((oldName.equals(link.getName()))
935                   || (((UrlLinkTableModel) linkUrlTable.getModel())
936                           .isUniqueName(link.getName())))
937           {
938             linkUrlTable.setValueAt(link.getName(), index, nameCol);
939             linkUrlTable.setValueAt(link.getURL(), index, urlCol);
940             valid = true;
941           }
942           else
943           {
944             link.notifyDuplicate();
945             continue;
946           }
947         }
948       }
949       else
950       {
951         break;
952       }
953     }
954   }
955
956   @Override
957   public void deleteLink_actionPerformed(ActionEvent e)
958   {
959     int index = linkUrlTable.getSelectedRow();
960     int modelIndex = -1;
961     if (index == -1)
962     {
963       // button no longer enabled if row is not selected
964       Cache.log.debug("Delete with no row selected in linkUrlTable");
965       return;
966     }
967     else
968     {
969       modelIndex = linkUrlTable.convertRowIndexToModel(index);
970     }
971
972     // make sure we use the model index to delete, and not the table index
973     ((UrlLinkTableModel) linkUrlTable.getModel()).removeRow(modelIndex);
974   }
975
976   @Override
977   public void defaultBrowser_mouseClicked(MouseEvent e)
978   {
979     JFileChooser chooser = new JFileChooser(".");
980     chooser.setDialogTitle(
981             MessageManager.getString("label.select_default_browser"));
982
983     int value = chooser.showOpenDialog(this);
984
985     if (value == JFileChooser.APPROVE_OPTION)
986     {
987       defaultBrowser.setText(chooser.getSelectedFile().getAbsolutePath());
988     }
989
990   }
991
992   /*
993    * (non-Javadoc)
994    * 
995    * @see
996    * jalview.jbgui.GPreferences#showunconserved_actionPerformed(java.awt.event
997    * .ActionEvent)
998    */
999   @Override
1000   protected void showunconserved_actionPerformed(ActionEvent e)
1001   {
1002     // TODO Auto-generated method stub
1003     super.showunconserved_actionPerformed(e);
1004   }
1005
1006   public static List<String> getGroupURLLinks()
1007   {
1008     return groupURLLinks;
1009   }
1010
1011   @Override
1012   public void minColour_actionPerformed(JPanel panel)
1013   {
1014     Color col = JColorChooser.showDialog(this,
1015             MessageManager.getString("label.select_colour_minimum_value"),
1016             minColour.getBackground());
1017     if (col != null)
1018     {
1019       panel.setBackground(col);
1020     }
1021     panel.repaint();
1022   }
1023
1024   @Override
1025   public void maxColour_actionPerformed(JPanel panel)
1026   {
1027     Color col = JColorChooser.showDialog(this,
1028             MessageManager.getString("label.select_colour_maximum_value"),
1029             maxColour.getBackground());
1030     if (col != null)
1031     {
1032       panel.setBackground(col);
1033     }
1034     panel.repaint();
1035   }
1036
1037   @Override
1038   protected void userIdWidth_actionPerformed()
1039   {
1040     try
1041     {
1042       String val = userIdWidth.getText().trim();
1043       if (val.length() > 0)
1044       {
1045         Integer iw = Integer.parseInt(val);
1046         if (iw.intValue() < 12)
1047         {
1048           throw new NumberFormatException();
1049         }
1050         userIdWidth.setText(iw.toString());
1051       }
1052     } catch (NumberFormatException x)
1053     {
1054       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1055               MessageManager
1056                       .getString("warn.user_defined_width_requirements"),
1057               MessageManager.getString("label.invalid_id_column_width"),
1058               JvOptionPane.WARNING_MESSAGE);
1059       userIdWidth.setText("");
1060     }
1061   }
1062
1063   @Override
1064   protected void autoIdWidth_actionPerformed()
1065   {
1066     userIdWidth.setEnabled(!autoIdWidth.isSelected());
1067     userIdWidthlabel.setEnabled(!autoIdWidth.isSelected());
1068   }
1069
1070   /**
1071    * Returns true if chimera path is to a valid executable, else show an error
1072    * dialog.
1073    */
1074   private boolean validateChimeraPath()
1075   {
1076     if (chimeraPath.getText().trim().length() > 0)
1077     {
1078       File f = new File(chimeraPath.getText());
1079       if (!f.canExecute())
1080       {
1081         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1082                 MessageManager.getString("label.invalid_chimera_path"),
1083                 MessageManager.getString("label.invalid_name"),
1084                 JvOptionPane.ERROR_MESSAGE);
1085         return false;
1086       }
1087     }
1088     return true;
1089   }
1090
1091   /**
1092    * If Chimera is selected, check it can be found on default or user-specified
1093    * path, if not show a warning/help dialog.
1094    */
1095   @Override
1096   protected void structureViewer_actionPerformed(String selectedItem)
1097   {
1098     if (!selectedItem.equals(ViewerType.CHIMERA.name()))
1099     {
1100       return;
1101     }
1102     boolean found = false;
1103
1104     /*
1105      * Try user-specified and standard paths for Chimera executable.
1106      */
1107     List<String> paths = StructureManager.getChimeraPaths();
1108     paths.add(0, chimeraPath.getText());
1109     for (String path : paths)
1110     {
1111       if (new File(path.trim()).canExecute())
1112       {
1113         found = true;
1114         break;
1115       }
1116     }
1117     if (!found)
1118     {
1119       String[] options = { "OK", "Help" };
1120       int showHelp = JvOptionPane.showInternalOptionDialog(Desktop.desktop,
1121               JvSwingUtils.wrapTooltip(true,
1122                       MessageManager.getString("label.chimera_missing")),
1123               "", JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
1124               null, options, options[0]);
1125       if (showHelp == JvOptionPane.NO_OPTION)
1126       {
1127         try
1128         {
1129           Help.showHelpWindow(HelpId.StructureViewer);
1130         } catch (HelpSetException e)
1131         {
1132           e.printStackTrace();
1133         }
1134       }
1135     }
1136   }
1137
1138   public class OptionsParam
1139   {
1140     private String name;
1141
1142     private String code;
1143
1144     public OptionsParam(String name, String code)
1145     {
1146       this.name = name;
1147       this.code = code;
1148     }
1149
1150     public String getName()
1151     {
1152       return name;
1153     }
1154
1155     public void setName(String name)
1156     {
1157       this.name = name;
1158     }
1159
1160     public String getCode()
1161     {
1162       return code;
1163     }
1164
1165     public void setCode(String code)
1166     {
1167       this.code = code;
1168     }
1169
1170     @Override
1171     public String toString()
1172     {
1173       return name;
1174     }
1175
1176     @Override
1177     public boolean equals(Object that)
1178     {
1179       if (!(that instanceof OptionsParam))
1180       {
1181         return false;
1182       }
1183       return this.code.equalsIgnoreCase(((OptionsParam) that).code);
1184     }
1185
1186     @Override
1187     public int hashCode()
1188     {
1189       return name.hashCode() + code.hashCode();
1190     }
1191   }
1192
1193   private class UrlListSelectionHandler implements ListSelectionListener
1194   {
1195
1196     @Override
1197     public void valueChanged(ListSelectionEvent e)
1198     {
1199       ListSelectionModel lsm = (ListSelectionModel) e.getSource();
1200
1201       int index = lsm.getMinSelectionIndex();
1202       if (index == -1)
1203       {
1204         // no selection, so disable delete/edit buttons
1205         editLink.setEnabled(false);
1206         deleteLink.setEnabled(false);
1207         return;
1208       }
1209       int modelIndex = linkUrlTable.convertRowIndexToModel(index);
1210
1211       // enable/disable edit and delete link buttons
1212       if (((UrlLinkTableModel) linkUrlTable.getModel())
1213               .isRowDeletable(modelIndex))
1214       {
1215         deleteLink.setEnabled(true);
1216       }
1217       else
1218       {
1219         deleteLink.setEnabled(false);
1220       }
1221
1222       if (((UrlLinkTableModel) linkUrlTable.getModel())
1223               .isRowEditable(modelIndex))
1224       {
1225         editLink.setEnabled(true);
1226       }
1227       else
1228       {
1229         editLink.setEnabled(false);
1230       }
1231     }
1232   }
1233 }