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