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