JAL-1601 Load and display JPred4 service in AlignFrame
[jalview.git] / src / jalview / gui / AlignFrame.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.util.Locale;
24
25 import java.io.IOException;
26 import java.util.HashSet;
27 import java.util.Set;
28
29 import javax.swing.JFileChooser;
30 import javax.swing.JOptionPane;
31 import java.awt.BorderLayout;
32 import java.awt.Color;
33 import java.awt.Component;
34 import java.awt.Dimension;
35 import java.awt.Rectangle;
36 import java.awt.Toolkit;
37 import java.awt.datatransfer.Clipboard;
38 import java.awt.datatransfer.DataFlavor;
39 import java.awt.datatransfer.StringSelection;
40 import java.awt.datatransfer.Transferable;
41 import java.awt.dnd.DnDConstants;
42 import java.awt.dnd.DropTargetDragEvent;
43 import java.awt.dnd.DropTargetDropEvent;
44 import java.awt.dnd.DropTargetEvent;
45 import java.awt.dnd.DropTargetListener;
46 import java.awt.event.ActionEvent;
47 import java.awt.event.ActionListener;
48 import java.awt.event.FocusAdapter;
49 import java.awt.event.FocusEvent;
50 import java.awt.event.ItemEvent;
51 import java.awt.event.ItemListener;
52 import java.awt.event.KeyAdapter;
53 import java.awt.event.KeyEvent;
54 import java.awt.event.MouseEvent;
55 import java.awt.print.PageFormat;
56 import java.awt.print.PrinterJob;
57 import java.beans.PropertyChangeEvent;
58 import java.beans.PropertyChangeListener;
59 import java.io.File;
60 import java.io.FileWriter;
61 import java.io.PrintWriter;
62 import java.net.URL;
63 import java.util.ArrayList;
64 import java.util.Arrays;
65 import java.util.Collection;
66 import java.util.Deque;
67 import java.util.Enumeration;
68 import java.util.Hashtable;
69 import java.util.List;
70 import java.util.Vector;
71
72 import javax.swing.ButtonGroup;
73 import javax.swing.JCheckBoxMenuItem;
74 import javax.swing.JComponent;
75 import javax.swing.JEditorPane;
76 import javax.swing.JInternalFrame;
77 import javax.swing.JLabel;
78 import javax.swing.JLayeredPane;
79 import javax.swing.JMenu;
80 import javax.swing.JMenuItem;
81 import javax.swing.JPanel;
82 import javax.swing.JScrollPane;
83 import javax.swing.SwingUtilities;
84 import javax.swing.event.InternalFrameAdapter;
85 import javax.swing.event.InternalFrameEvent;
86
87 import ext.vamsas.ServiceHandle;
88 import jalview.analysis.AlignmentSorter;
89 import jalview.analysis.AlignmentUtils;
90 import jalview.analysis.CrossRef;
91 import jalview.analysis.Dna;
92 import jalview.analysis.GeneticCodeI;
93 import jalview.analysis.ParseProperties;
94 import jalview.analysis.SequenceIdMatcher;
95 import jalview.api.AlignExportSettingsI;
96 import jalview.api.AlignViewControllerGuiI;
97 import jalview.api.AlignViewControllerI;
98 import jalview.api.AlignViewportI;
99 import jalview.api.AlignmentViewPanel;
100 import jalview.api.FeatureSettingsControllerI;
101 import jalview.api.FeatureSettingsModelI;
102 import jalview.api.SplitContainerI;
103 import jalview.api.ViewStyleI;
104 import jalview.api.analysis.SimilarityParamsI;
105 import jalview.bin.Cache;
106 import jalview.bin.Console;
107 import jalview.bin.Jalview;
108 import jalview.commands.CommandI;
109 import jalview.commands.EditCommand;
110 import jalview.commands.EditCommand.Action;
111 import jalview.commands.OrderCommand;
112 import jalview.commands.RemoveGapColCommand;
113 import jalview.commands.RemoveGapsCommand;
114 import jalview.commands.SlideSequencesCommand;
115 import jalview.commands.TrimRegionCommand;
116 import jalview.datamodel.AlignExportSettingsAdapter;
117 import jalview.datamodel.AlignedCodonFrame;
118 import jalview.datamodel.Alignment;
119 import jalview.datamodel.AlignmentAnnotation;
120 import jalview.datamodel.AlignmentExportData;
121 import jalview.datamodel.AlignmentI;
122 import jalview.datamodel.AlignmentOrder;
123 import jalview.datamodel.AlignmentView;
124 import jalview.datamodel.ColumnSelection;
125 import jalview.datamodel.HiddenColumns;
126 import jalview.datamodel.PDBEntry;
127 import jalview.datamodel.SeqCigar;
128 import jalview.datamodel.Sequence;
129 import jalview.datamodel.SequenceGroup;
130 import jalview.datamodel.SequenceI;
131 import jalview.gui.ColourMenuHelper.ColourChangeListener;
132 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
133 import jalview.hmmer.HMMAlign;
134 import jalview.hmmer.HMMBuild;
135 import jalview.hmmer.HMMERParamStore;
136 import jalview.hmmer.HMMERPreset;
137 import jalview.hmmer.HMMSearch;
138 import jalview.hmmer.HmmerCommand;
139 import jalview.hmmer.JackHMMER;
140 import jalview.io.AlignmentProperties;
141 import jalview.io.AnnotationFile;
142 import jalview.io.BackupFiles;
143 import jalview.io.BioJsHTMLOutput;
144 import jalview.io.DataSourceType;
145 import jalview.io.FileFormat;
146 import jalview.io.FileFormatI;
147 import jalview.io.FileFormats;
148 import jalview.io.FileLoader;
149 import jalview.io.FileParse;
150 import jalview.io.FormatAdapter;
151 import jalview.io.HtmlSvgOutput;
152 import jalview.io.IdentifyFile;
153 import jalview.io.JPredFile;
154 import jalview.io.JalviewFileChooser;
155 import jalview.io.JalviewFileView;
156 import jalview.io.JnetAnnotationMaker;
157 import jalview.io.NewickFile;
158 import jalview.io.ScoreMatrixFile;
159 import jalview.io.TCoffeeScoreFile;
160 import jalview.io.vcf.VCFLoader;
161 import jalview.jbgui.GAlignFrame;
162 import jalview.project.Jalview2XML;
163 import jalview.schemes.ColourSchemeI;
164 import jalview.schemes.ColourSchemes;
165 import jalview.schemes.ResidueColourScheme;
166 import jalview.schemes.TCoffeeColourScheme;
167 import jalview.util.HttpUtils;
168 import jalview.util.ImageMaker.TYPE;
169 import jalview.util.MessageManager;
170 import jalview.util.Platform;
171 import jalview.viewmodel.AlignmentViewport;
172 import jalview.viewmodel.ViewportRanges;
173 import jalview.ws.DBRefFetcher;
174 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
175 import jalview.ws.ServiceChangeListener;
176 import jalview.ws.WSDiscovererI;
177 import jalview.ws.api.ServiceWithParameters;
178 import jalview.ws.jws1.Discoverer;
179 import jalview.ws.jws2.Jws2Discoverer;
180 import jalview.ws.jws2.PreferredServiceRegistry;
181 import jalview.ws.params.ArgumentI;
182 import jalview.ws.params.ParamDatastoreI;
183 import jalview.ws.params.WsParamSetI;
184 import jalview.ws.seqfetcher.DbSourceProxy;
185 import jalview.ws2.client.api.WebServiceDiscovererI;
186 import jalview.ws2.client.ebi.JobDispatcherWSDiscoverer;
187 import jalview.ws2.client.jpred4.JPred4WSDiscoverer;
188 import jalview.ws2.client.slivka.SlivkaWSDiscoverer;
189 import jalview.ws2.gui.WebServicesMenuManager;
190
191 import java.io.IOException;
192 import java.util.HashSet;
193 import java.util.Set;
194
195 import javax.swing.JFileChooser;
196 import javax.swing.JOptionPane;
197
198 import java.awt.BorderLayout;
199 import java.awt.Color;
200 import java.awt.Component;
201 import java.awt.Dimension;
202 import java.awt.Rectangle;
203 import java.awt.Toolkit;
204 import java.awt.datatransfer.Clipboard;
205 import java.awt.datatransfer.DataFlavor;
206 import java.awt.datatransfer.StringSelection;
207 import java.awt.datatransfer.Transferable;
208 import java.awt.dnd.DnDConstants;
209 import java.awt.dnd.DropTargetDragEvent;
210 import java.awt.dnd.DropTargetDropEvent;
211 import java.awt.dnd.DropTargetEvent;
212 import java.awt.dnd.DropTargetListener;
213 import java.awt.event.ActionEvent;
214 import java.awt.event.ActionListener;
215 import java.awt.event.FocusAdapter;
216 import java.awt.event.FocusEvent;
217 import java.awt.event.ItemEvent;
218 import java.awt.event.ItemListener;
219 import java.awt.event.KeyAdapter;
220 import java.awt.event.KeyEvent;
221 import java.awt.event.MouseEvent;
222 import java.awt.print.PageFormat;
223 import java.awt.print.PrinterJob;
224 import java.beans.PropertyChangeEvent;
225 import java.beans.PropertyChangeListener;
226 import java.io.File;
227 import java.io.FileWriter;
228 import java.io.PrintWriter;
229 import java.net.URL;
230 import java.util.ArrayList;
231 import java.util.Arrays;
232 import java.util.Collection;
233 import java.util.Deque;
234 import java.util.Enumeration;
235 import java.util.Hashtable;
236 import java.util.List;
237 import java.util.Vector;
238
239 import javax.swing.ButtonGroup;
240 import javax.swing.JCheckBoxMenuItem;
241 import javax.swing.JComponent;
242 import javax.swing.JEditorPane;
243 import javax.swing.JInternalFrame;
244 import javax.swing.JLabel;
245 import javax.swing.JLayeredPane;
246 import javax.swing.JMenu;
247 import javax.swing.JMenuItem;
248 import javax.swing.JPanel;
249 import javax.swing.JScrollPane;
250 import javax.swing.SwingUtilities;
251 import javax.swing.event.InternalFrameAdapter;
252 import javax.swing.event.InternalFrameEvent;
253
254 import ext.vamsas.ServiceHandle;
255
256 /**
257  * DOCUMENT ME!
258  * 
259  * @author $author$
260  * @version $Revision$
261  */
262 @SuppressWarnings("serial")
263 public class AlignFrame extends GAlignFrame
264         implements DropTargetListener, IProgressIndicator,
265         AlignViewControllerGuiI, ColourChangeListener, ServiceChangeListener
266 {
267
268   public static int frameCount;
269   public static final int DEFAULT_WIDTH = 700;
270
271   public static final int DEFAULT_HEIGHT = 500;
272
273   /*
274    * The currently displayed panel (selected tabbed view if more than one)
275    */
276   public AlignmentPanel alignPanel;
277
278   AlignViewport viewport;
279
280   public AlignViewControllerI avc;
281
282   List<AlignmentPanel> alignPanels = new ArrayList<>();
283
284   /**
285    * Last format used to load or save alignments in this window
286    */
287   FileFormatI currentFileFormat = null;
288
289   /**
290    * Current filename for this alignment
291    */
292   String fileName = null;
293
294   /**
295    * TODO: remove reference to 'FileObject' in AlignFrame - not correct mapping
296    */
297   File fileObject;
298
299   private int id;
300
301   private DataSourceType protocol ;
302   /**
303    * Creates a new AlignFrame object with specific width and height.
304    * 
305    * @param al
306    * @param width
307    * @param height
308    */
309   public AlignFrame(AlignmentI al, int width, int height)
310   {
311     this(al, null, width, height);
312   }
313
314   /**
315    * Creates a new AlignFrame object with specific width, height and
316    * sequenceSetId
317    * 
318    * @param al
319    * @param width
320    * @param height
321    * @param sequenceSetId
322    */
323   public AlignFrame(AlignmentI al, int width, int height,
324           String sequenceSetId)
325   {
326     this(al, null, width, height, sequenceSetId);
327   }
328
329   /**
330    * Creates a new AlignFrame object with specific width, height and
331    * sequenceSetId
332    * 
333    * @param al
334    * @param width
335    * @param height
336    * @param sequenceSetId
337    * @param viewId
338    */
339   public AlignFrame(AlignmentI al, int width, int height,
340           String sequenceSetId, String viewId)
341   {
342     this(al, null, width, height, sequenceSetId, viewId);
343   }
344
345   /**
346    * new alignment window with hidden columns
347    * 
348    * @param al
349    *          AlignmentI
350    * @param hiddenColumns
351    *          ColumnSelection or null
352    * @param width
353    *          Width of alignment frame
354    * @param height
355    *          height of frame.
356    */
357   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
358           int height)
359   {
360     this(al, hiddenColumns, width, height, null);
361   }
362
363   /**
364    * Create alignment frame for al with hiddenColumns, a specific width and
365    * height, and specific sequenceId
366    * 
367    * @param al
368    * @param hiddenColumns
369    * @param width
370    * @param height
371    * @param sequenceSetId
372    *          (may be null)
373    */
374   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
375           int height, String sequenceSetId)
376   {
377     this(al, hiddenColumns, width, height, sequenceSetId, null);
378   }
379
380   /**
381    * Create alignment frame for al with hiddenColumns, a specific width and
382    * height, and specific sequenceId
383    * 
384    * @param al
385    * @param hiddenColumns
386    * @param width
387    * @param height
388    * @param sequenceSetId
389    *          (may be null)
390    * @param viewId
391    *          (may be null)
392    */
393   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
394           int height, String sequenceSetId, String viewId)
395   {
396     id = (++frameCount);
397     setSize(width, height);
398
399     if (al.getDataset() == null)
400     {
401       al.setDataset(null);
402     }
403
404     viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
405
406     // JalviewJS needs to distinguish a new panel from an old one in init()
407     // alignPanel = new AlignmentPanel(this, viewport);
408     // addAlignmentPanel(alignPanel, true);
409     init();
410   }
411
412   public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
413           HiddenColumns hiddenColumns, int width, int height)
414   {
415     setSize(width, height);
416
417     if (al.getDataset() == null)
418     {
419       al.setDataset(null);
420     }
421
422     viewport = new AlignViewport(al, hiddenColumns);
423
424     if (hiddenSeqs != null && hiddenSeqs.length > 0)
425     {
426       viewport.hideSequence(hiddenSeqs);
427     }
428     // alignPanel = new AlignmentPanel(this, viewport);
429     // addAlignmentPanel(alignPanel, true);
430     init();
431   }
432
433   /**
434    * Make a new AlignFrame from existing alignmentPanels
435    * 
436    * @param ap
437    *          AlignmentPanel
438    * @param av
439    *          AlignViewport
440    */
441   public AlignFrame(AlignmentPanel ap)
442   {
443     viewport = ap.av;
444     alignPanel = ap;
445     // addAlignmentPanel(ap, false);
446     init();
447   }
448
449   /**
450    * initalise the alignframe from the underlying viewport data and the
451    * configurations
452    */
453   void init()
454   {
455     boolean newPanel = (alignPanel == null);
456     viewport.setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
457     if (newPanel)
458     {
459       if (Platform.isJS())
460       {
461         // need to set this up front if NOANNOTATION is
462         // used in conjunction with SHOWOVERVIEW.
463
464         // I have not determined if this is appropriate for
465         // Jalview/Java, as it means we are setting this flag
466         // for all subsequent AlignFrames. For now, at least,
467         // I am setting it to be JalviewJS-only.
468
469         boolean showAnnotation = Jalview.getInstance().getShowAnnotation();
470         viewport.setShowAnnotation(showAnnotation);
471       }
472       alignPanel = new AlignmentPanel(this, viewport);
473     }
474     addAlignmentPanel(alignPanel, newPanel);
475     // setBackground(Color.white); // BH 2019
476
477     if (!Jalview.isHeadlessMode())
478     {
479       progressBar = new ProgressBar(this.statusPanel, this.statusBar);
480       // JalviewJS options
481       statusPanel.setVisible(Jalview.getInstance().getShowStatus());
482       alignFrameMenuBar.setVisible(Jalview.getInstance().getAllowMenuBar());
483     }
484
485     avc = new jalview.controller.AlignViewController(this, viewport,
486             alignPanel);
487     if (viewport.getAlignmentConservationAnnotation() == null)
488     {
489       // BLOSUM62Colour.setEnabled(false);
490       conservationMenuItem.setEnabled(false);
491       modifyConservation.setEnabled(false);
492       // PIDColour.setEnabled(false);
493       // abovePIDThreshold.setEnabled(false);
494       // modifyPID.setEnabled(false);
495     }
496
497     String sortby = Cache.getDefault(Preferences.SORT_ALIGNMENT,
498             "No sort");
499
500     if (sortby.equals("Id"))
501     {
502       sortIDMenuItem_actionPerformed(null);
503     }
504     else if (sortby.equals("Pairwise Identity"))
505     {
506       sortPairwiseMenuItem_actionPerformed(null);
507     }
508
509     // BH see above
510     //
511     // this.alignPanel.av
512     // .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
513
514     setMenusFromViewport(viewport);
515     buildSortByAnnotationScoresMenu();
516     calculateTree.addActionListener(new ActionListener()
517     {
518
519       @Override
520       public void actionPerformed(ActionEvent e)
521       {
522         openTreePcaDialog();
523       }
524     });
525     buildColourMenu();
526
527     if (Desktop.getDesktopPane() != null)
528     {
529       this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
530       addServiceListeners();
531       if (!Platform.isJS())
532       {
533       }
534       setGUINucleotide();
535     }
536
537     if (viewport.getWrapAlignment())
538     {
539       wrapMenuItem_actionPerformed(null);
540     }
541
542     if (Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
543     {
544       this.overviewMenuItem_actionPerformed(null);
545     }
546
547     addKeyListener();
548
549     final List<AlignmentViewPanel> selviews = new ArrayList<>();
550     final List<AlignmentPanel> origview = new ArrayList<>();
551     final String menuLabel = MessageManager
552             .getString("label.copy_format_from");
553     ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
554             new ViewSetProvider()
555             {
556
557               @Override
558               public AlignmentPanel[] getAllAlignmentPanels()
559               {
560                 origview.clear();
561                 origview.add(alignPanel);
562                 // make an array of all alignment panels except for this one
563                 List<AlignmentPanel> aps = new ArrayList<>(
564                         Arrays.asList(Desktop.getAlignmentPanels(null)));
565                 aps.remove(AlignFrame.this.alignPanel);
566                 return aps.toArray(new AlignmentPanel[aps.size()]);
567               }
568             }, selviews, new ItemListener()
569             {
570
571               @Override
572               public void itemStateChanged(ItemEvent e)
573               {
574                 if (origview.size() > 0)
575                 {
576                   final AlignmentPanel ap = origview.get(0);
577
578                   /*
579                    * Copy the ViewStyle of the selected panel to 'this one'.
580                    * Don't change value of 'scaleProteinAsCdna' unless copying
581                    * from a SplitFrame.
582                    */
583                   ViewStyleI vs = selviews.get(0).getAlignViewport()
584                           .getViewStyle();
585                   boolean fromSplitFrame = selviews.get(0)
586                           .getAlignViewport().getCodingComplement() != null;
587                   if (!fromSplitFrame)
588                   {
589                     vs.setScaleProteinAsCdna(ap.getAlignViewport()
590                             .getViewStyle().isScaleProteinAsCdna());
591                   }
592                   ap.getAlignViewport().setViewStyle(vs);
593
594                   /*
595                    * Also rescale ViewStyle of SplitFrame complement if there is
596                    * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
597                    * the whole ViewStyle (allow cDNA protein to have different
598                    * fonts)
599                    */
600                   AlignViewportI complement = ap.getAlignViewport()
601                           .getCodingComplement();
602                   if (complement != null && vs.isScaleProteinAsCdna())
603                   {
604                     AlignFrame af = Desktop.getAlignFrameFor(complement);
605                     ((SplitFrame) af.getSplitViewContainer())
606                             .adjustLayout();
607                     af.setMenusForViewport();
608                   }
609
610                   ap.updateLayout();
611                   ap.setSelected(true);
612                   ap.alignFrame.setMenusForViewport();
613
614                 }
615               }
616             });
617     if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase(Locale.ROOT)
618             .indexOf("devel") > -1
619             || Cache.getDefault("VERSION", "DEVELOPMENT")
620                     .toLowerCase(Locale.ROOT).indexOf("test") > -1)
621     {
622       formatMenu.add(vsel);
623     }
624     addFocusListener(new FocusAdapter()
625     {
626       @Override
627       public void focusGained(FocusEvent e)
628       {
629         Jalview.setCurrentAlignFrame(AlignFrame.this);
630       }
631     });
632
633   }
634
635   /**
636    * Change the filename and format for the alignment, and enable the 'reload'
637    * button functionality.
638    * 
639    * @param file
640    *          valid filename
641    * @param format
642    *          format of file
643    */
644   @Deprecated
645   public void setFileName(String file, FileFormatI format)
646   {
647     fileName = file;
648     setFileFormat(format);
649     reload.setEnabled(true);
650   }
651
652   /**
653    * 
654    * @param fileName
655    * @param file  from SwingJS; may contain bytes -- for reload
656    * @param protocol from SwingJS; may be RELATIVE_URL
657    * @param format
658    */
659   public void setFile(String fileName, File file, DataSourceType protocol, FileFormatI format)
660   {
661     this.fileName = fileName;
662     this.fileObject = file;
663     this.protocol = protocol;
664     setFileFormat(format);
665     reload.setEnabled(true);
666   }
667
668   /**
669    * JavaScript will have this, maybe others. More dependable than a file name
670    * and maintains a reference to the actual bytes loaded.
671    * 
672    * @param file
673    */
674   public void setFileObject(File file)
675   {
676     this.fileObject = file;
677   }
678
679   /**
680    * Add a KeyListener with handlers for various KeyPressed and KeyReleased
681    * events
682    */
683   void addKeyListener()
684   {
685     addKeyListener(new KeyAdapter()
686     {
687       @Override
688       public void keyPressed(KeyEvent evt)
689       {
690         if (viewport.cursorMode
691                 && ((evt.getKeyCode() >= KeyEvent.VK_0
692                         && evt.getKeyCode() <= KeyEvent.VK_9)
693                         || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
694                                 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
695                 && Character.isDigit(evt.getKeyChar()))
696         {
697           alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
698         }
699
700         switch (evt.getKeyCode())
701         {
702
703         case KeyEvent.VK_ESCAPE: // escape key
704                                  // alignPanel.deselectAllSequences();
705           alignPanel.deselectAllSequences();
706
707           break;
708
709         case KeyEvent.VK_DOWN:
710           if (evt.isAltDown() || !viewport.cursorMode)
711           {
712             moveSelectedSequences(false);
713           }
714           if (viewport.cursorMode)
715           {
716             alignPanel.getSeqPanel().moveCursor(0, 1, evt.isShiftDown());
717           }
718           break;
719
720         case KeyEvent.VK_UP:
721           if (evt.isAltDown() || !viewport.cursorMode)
722           {
723             moveSelectedSequences(true);
724           }
725           if (viewport.cursorMode)
726           {
727             alignPanel.getSeqPanel().moveCursor(0, -1, evt.isShiftDown());
728           }
729
730           break;
731
732         case KeyEvent.VK_LEFT:
733           if (evt.isAltDown() || !viewport.cursorMode)
734           {
735             slideSequences(false,
736                     alignPanel.getSeqPanel().getKeyboardNo1());
737           }
738           else
739           {
740             alignPanel.getSeqPanel().moveCursor(-1, 0, evt.isShiftDown());
741           }
742
743           break;
744
745         case KeyEvent.VK_RIGHT:
746           if (evt.isAltDown() || !viewport.cursorMode)
747           {
748             slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
749           }
750           else
751           {
752             alignPanel.getSeqPanel().moveCursor(1, 0, evt.isShiftDown());
753           }
754           break;
755
756         case KeyEvent.VK_SPACE:
757           if (viewport.cursorMode)
758           {
759             alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
760                     || evt.isShiftDown() || evt.isAltDown());
761           }
762           break;
763
764         // case KeyEvent.VK_A:
765         // if (viewport.cursorMode)
766         // {
767         // alignPanel.seqPanel.insertNucAtCursor(false,"A");
768         // //System.out.println("A");
769         // }
770         // break;
771         /*
772          * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
773          * System.out.println("closing bracket"); } break;
774          */
775         case KeyEvent.VK_DELETE:
776         case KeyEvent.VK_BACK_SPACE:
777           if (!viewport.cursorMode)
778           {
779             cut_actionPerformed();
780           }
781           else
782           {
783             alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
784                     || evt.isShiftDown() || evt.isAltDown());
785           }
786
787           break;
788
789         case KeyEvent.VK_S:
790           if (viewport.cursorMode)
791           {
792             alignPanel.getSeqPanel().setCursorRow();
793           }
794           break;
795         case KeyEvent.VK_C:
796           if (viewport.cursorMode && !evt.isControlDown())
797           {
798             alignPanel.getSeqPanel().setCursorColumn();
799           }
800           break;
801         case KeyEvent.VK_P:
802           if (viewport.cursorMode)
803           {
804             alignPanel.getSeqPanel().setCursorPosition();
805           }
806           break;
807
808         case KeyEvent.VK_ENTER:
809         case KeyEvent.VK_COMMA:
810           if (viewport.cursorMode)
811           {
812             alignPanel.getSeqPanel().setCursorRowAndColumn();
813           }
814           break;
815
816         case KeyEvent.VK_Q:
817           if (viewport.cursorMode)
818           {
819             alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
820           }
821           break;
822         case KeyEvent.VK_M:
823           if (viewport.cursorMode)
824           {
825             alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
826           }
827           break;
828
829         case KeyEvent.VK_F2:
830           viewport.cursorMode = !viewport.cursorMode;
831           setStatus(MessageManager
832                   .formatMessage("label.keyboard_editing_mode", new String[]
833                   { (viewport.cursorMode ? "on" : "off") }));
834           if (viewport.cursorMode)
835           {
836             ViewportRanges ranges = viewport.getRanges();
837             alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
838                     .getStartRes();
839             alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
840                     .getStartSeq();
841           }
842           alignPanel.getSeqPanel().seqCanvas.repaint();
843           break;
844
845         case KeyEvent.VK_F1:
846           try
847           {
848             Help.showHelpWindow();
849           } catch (Exception ex)
850           {
851             ex.printStackTrace();
852           }
853           break;
854         case KeyEvent.VK_H:
855         {
856           boolean toggleSeqs = !evt.isControlDown();
857           boolean toggleCols = !evt.isShiftDown();
858           toggleHiddenRegions(toggleSeqs, toggleCols);
859           break;
860         }
861         case KeyEvent.VK_B:
862         {
863           boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
864           boolean modifyExisting = true; // always modify, don't clear
865                                          // evt.isShiftDown();
866           boolean invertHighlighted = evt.isAltDown();
867           avc.markHighlightedColumns(invertHighlighted, modifyExisting,
868                   toggleSel);
869           break;
870         }
871         case KeyEvent.VK_PAGE_UP:
872           viewport.getRanges().pageUp();
873           break;
874         case KeyEvent.VK_PAGE_DOWN:
875           viewport.getRanges().pageDown();
876           break;
877         }
878       }
879
880       @Override
881       public void keyReleased(KeyEvent evt)
882       {
883         switch (evt.getKeyCode())
884         {
885         case KeyEvent.VK_LEFT:
886           if (evt.isAltDown() || !viewport.cursorMode)
887           {
888             viewport.notifyAlignment();
889           }
890           break;
891
892         case KeyEvent.VK_RIGHT:
893           if (evt.isAltDown() || !viewport.cursorMode)
894           {
895             viewport.notifyAlignment();
896           }
897           break;
898         }
899       }
900     });
901   }
902
903   public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
904   {
905     ap.alignFrame = this;
906     avc = new jalview.controller.AlignViewController(this, viewport,
907             alignPanel);
908
909     alignPanels.add(ap);
910
911     PaintRefresher.Register(ap, ap.av.getSequenceSetId());
912
913     int aSize = alignPanels.size();
914
915     tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
916
917     if (aSize == 1 && ap.av.getViewName() == null)
918     {
919       this.getContentPane().add(ap, BorderLayout.CENTER);
920     }
921     else
922     {
923       if (aSize == 2)
924       {
925         setInitialTabVisible();
926       }
927
928       expandViews.setEnabled(true);
929       gatherViews.setEnabled(true);
930       tabbedPane.addTab(ap.av.getViewName(), ap);
931
932       ap.setVisible(false);
933     }
934
935     if (newPanel)
936     {
937       if (ap.av.isPadGaps())
938       {
939         ap.av.getAlignment().padGaps();
940       }
941       if (Jalview.getInstance().getStartCalculations())
942       {
943         ap.av.updateConservation(ap);
944         ap.av.updateConsensus(ap);
945         ap.av.updateStrucConsensus(ap);
946         ap.av.initInformationWorker(ap);
947       }
948     }
949   }
950
951   public void setInitialTabVisible()
952   {
953     expandViews.setEnabled(true);
954     gatherViews.setEnabled(true);
955     tabbedPane.setVisible(true);
956     AlignmentPanel first = alignPanels.get(0);
957     tabbedPane.addTab(first.av.getViewName(), first);
958     this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
959   }
960
961   public AlignViewport getViewport()
962   {
963     return viewport;
964   }
965
966   @Override
967   public void servicesChanged(WSDiscovererI discoverer,
968           Collection<? extends ServiceWithParameters> services)
969   {
970     buildWebServicesMenu();
971   }
972
973   private WebServiceDiscovererI.ServicesChangeListener slivkaServiceChangeListener =
974       (discoverer, services) -> {
975         // run when slivka services change
976         var menu = AlignFrame.this.slivkaMenu;
977         menu.setServices(discoverer);
978         menu.setInProgress(discoverer.isRunning());
979         menu.setNoServices(services.isEmpty() && discoverer.isDone());
980       };
981
982   private WebServiceDiscovererI.ServicesChangeListener ebiServiceChangeListener =
983       (discoverer, services) -> {
984         // run when ebi services change
985         var menu = AlignFrame.this.ebiMenu;
986         menu.setServices(discoverer);
987         menu.setInProgress(discoverer.isRunning());
988         menu.setNoServices(services.isEmpty() && discoverer.isDone());
989       };
990   
991   private WebServiceDiscovererI.ServicesChangeListener jpred4ServiceChangeListener =
992       (discoverer, services) -> {
993         // run when jpred4 services change
994         var menu = AlignFrame.this.jpred4Menu;
995         menu.setServices(discoverer);
996         menu.setInProgress(discoverer.isRunning());
997         menu.setNoServices(services.isEmpty() && discoverer.isDone());
998       };
999
1000   /* Set up intrinsic listeners for dynamically generated GUI bits. */
1001   private void addServiceListeners()
1002   {
1003     if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
1004     {
1005       WebServiceDiscovererI discoverer = SlivkaWSDiscoverer.getInstance();
1006       discoverer.addServicesChangeListener(slivkaServiceChangeListener);
1007     }
1008     if (Cache.getDefault("SHOW_EBI_SERVICES", true))
1009     {
1010       JobDispatcherWSDiscoverer.getInstance().addServicesChangeListener(ebiServiceChangeListener);
1011     }
1012     if (Cache.getDefault("SHOW_JPRED4_SERVICES", true))
1013     {
1014       JPred4WSDiscoverer.getInstance().addServicesChangeListener(jpred4ServiceChangeListener);
1015     }
1016     if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
1017     {
1018       WSDiscovererI discoverer = Jws2Discoverer.getInstance();
1019       discoverer.addServiceChangeListener(this);
1020     }
1021     // legacy event listener for compatibility with jws1
1022     PropertyChangeListener legacyListener = (changeEvent) -> {
1023       buildWebServicesMenu();
1024     };
1025     Desktop.getInstance().addJalviewPropertyChangeListener("services",legacyListener);
1026     
1027     addInternalFrameListener(new InternalFrameAdapter() {
1028       @Override
1029       public void internalFrameClosed(InternalFrameEvent e) {
1030         System.out.println("deregistering discoverer listener");
1031         SlivkaWSDiscoverer.getInstance().removeServicesChangeListener(slivkaServiceChangeListener);
1032         JPred4WSDiscoverer.getInstance().removeServicesChangeListener(jpred4ServiceChangeListener);
1033         Jws2Discoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
1034         Desktop.getInstance().removeJalviewPropertyChangeListener("services", legacyListener);
1035         closeMenuItem_actionPerformed(true);
1036       }
1037     });
1038     buildWebServicesMenu();
1039   }
1040
1041   /**
1042    * Configure menu items that vary according to whether the alignment is
1043    * nucleotide or protein
1044    */
1045   public void setGUINucleotide()
1046   {
1047     AlignmentI al = getViewport().getAlignment();
1048     boolean nucleotide = al.isNucleotide();
1049
1050     loadVcf.setVisible(nucleotide);
1051     showTranslation.setVisible(nucleotide);
1052     showReverse.setVisible(nucleotide);
1053     showReverseComplement.setVisible(nucleotide);
1054     conservationMenuItem.setEnabled(!nucleotide);
1055     modifyConservation
1056             .setEnabled(!nucleotide && conservationMenuItem.isSelected());
1057     showGroupConservation.setEnabled(!nucleotide);
1058
1059     showComplementMenuItem
1060             .setText(nucleotide ? MessageManager.getString("label.protein")
1061                     : MessageManager.getString("label.nucleotide"));
1062   }
1063
1064   /**
1065    * set up menus for the current viewport. This may be called after any
1066    * operation that affects the data in the current view (selection changed,
1067    * etc) to update the menus to reflect the new state.
1068    */
1069   @Override
1070   public void setMenusForViewport()
1071   {
1072     setMenusFromViewport(viewport);
1073   }
1074
1075   /**
1076    * Need to call this method when tabs are selected for multiple views, or when
1077    * loading from Jalview2XML.java
1078    * 
1079    * @param av
1080    *          AlignViewport
1081    */
1082   public void setMenusFromViewport(AlignViewport av)
1083   {
1084     padGapsMenuitem.setSelected(av.isPadGaps());
1085     colourTextMenuItem.setSelected(av.isShowColourText());
1086     abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
1087     modifyPID.setEnabled(abovePIDThreshold.isSelected());
1088     conservationMenuItem.setSelected(av.getConservationSelected());
1089     modifyConservation.setEnabled(conservationMenuItem.isSelected());
1090     seqLimits.setSelected(av.getShowJVSuffix());
1091     idRightAlign.setSelected(av.isRightAlignIds());
1092     centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
1093     renderGapsMenuItem.setSelected(av.isRenderGaps());
1094     wrapMenuItem.setSelected(av.getWrapAlignment());
1095     scaleAbove.setVisible(av.getWrapAlignment());
1096     scaleLeft.setVisible(av.getWrapAlignment());
1097     scaleRight.setVisible(av.getWrapAlignment());
1098     annotationPanelMenuItem.setState(av.isShowAnnotation());
1099     // Show/hide annotations only enabled if annotation panel is shown
1100     syncAnnotationMenuItems(av.isShowAnnotation());
1101     viewBoxesMenuItem.setSelected(av.getShowBoxes());
1102     viewTextMenuItem.setSelected(av.getShowText());
1103     showNonconservedMenuItem.setSelected(av.getShowUnconserved());
1104     showGroupConsensus.setSelected(av.isShowGroupConsensus());
1105     showGroupConservation.setSelected(av.isShowGroupConservation());
1106     showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
1107     showSequenceLogo.setSelected(av.isShowSequenceLogo());
1108     normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
1109     showInformationHistogram.setSelected(av.isShowInformationHistogram());
1110     showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
1111     normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
1112
1113     ColourMenuHelper.setColourSelected(colourMenu,
1114             av.getGlobalColourScheme());
1115
1116     showSeqFeatures.setSelected(av.isShowSequenceFeatures());
1117     hiddenMarkers.setState(av.getShowHiddenMarkers());
1118     applyToAllGroups.setState(av.getColourAppliesToAllGroups());
1119     showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
1120     showDbRefsMenuitem.setSelected(av.isShowDBRefs());
1121     autoCalculate
1122             .setSelected(av.getAutoCalculateConsensusAndConservation());
1123     sortByTree.setSelected(av.sortByTree);
1124     listenToViewSelections.setSelected(av.followSelection);
1125
1126     showProducts.setEnabled(canShowProducts());
1127     setGroovyEnabled(Desktop.getGroovyConsole() != null);
1128
1129     updateEditMenuBar();
1130   }
1131
1132   /**
1133    * Set the enabled state of the 'Run Groovy' option in the Calculate menu
1134    * 
1135    * @param b
1136    */
1137   public void setGroovyEnabled(boolean b)
1138   {
1139     runGroovy.setEnabled(b);
1140   }
1141
1142   private IProgressIndicator progressBar;
1143
1144   /*
1145    * (non-Javadoc)
1146    * 
1147    * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
1148    */
1149   @Override
1150   public void setProgressBar(String message, long id)
1151   {
1152     progressBar.setProgressBar(message, id);
1153   }
1154   
1155   @Override
1156   public void addProgressBar(long id, String message)
1157   {
1158     progressBar.addProgressBar(id, message);
1159   }
1160
1161   @Override
1162   public void removeProgressBar(long id)
1163   {
1164     progressBar.removeProgressBar(id);
1165   }
1166
1167   @Override
1168   public void registerHandler(final long id,
1169           final IProgressIndicatorHandler handler)
1170   {
1171     progressBar.registerHandler(id, handler);
1172   }
1173
1174   /**
1175    * 
1176    * @return true if any progress bars are still active
1177    */
1178   @Override
1179   public boolean operationInProgress()
1180   {
1181     return progressBar.operationInProgress();
1182   }
1183
1184   /**
1185    * Sets the text of the status bar. Note that setting a null or empty value
1186    * will cause the status bar to be hidden, with possibly undesirable flicker
1187    * of the screen layout.
1188    */
1189   @Override
1190   public void setStatus(String text)
1191   {
1192     statusBar.setText(text == null || text.isEmpty() ? " " : text);
1193   }
1194
1195   /*
1196    * Added so Castor Mapping file can obtain Jalview Version
1197    */
1198   public String getVersion()
1199   {
1200     return Cache.getProperty("VERSION");
1201   }
1202
1203   public FeatureRenderer getFeatureRenderer()
1204   {
1205     return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1206   }
1207
1208   @Override
1209   public void fetchSequence_actionPerformed()
1210   {
1211     new SequenceFetcher(this);
1212   }
1213
1214   @Override
1215   public void addFromFile_actionPerformed(ActionEvent e)
1216   {
1217     Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1218   }
1219
1220   @Override
1221   public void hmmBuild_actionPerformed(boolean withDefaults)
1222   {
1223     if (!alignmentIsSufficient(1))
1224     {
1225       return;
1226     }
1227
1228     /*
1229      * get default parameters, and optionally show a dialog
1230      * to allow them to be modified
1231      */
1232     ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1233     List<ArgumentI> args = store.getServiceParameters();
1234
1235     if (!withDefaults)
1236     {
1237       WsParamSetI set = new HMMERPreset();
1238       WsJobParameters params = new WsJobParameters(store, set, args);
1239       params.showRunDialog().thenAccept((startJob) -> {
1240         if (startJob)
1241         {
1242           var args2 = params.getJobParams();
1243           new Thread(new HMMBuild(this, args2)).start();
1244         }
1245       });
1246     }
1247     else
1248     {
1249       new Thread(new HMMBuild(this, args)).start();
1250     }
1251   }
1252
1253   @Override
1254   public void hmmAlign_actionPerformed(boolean withDefaults)
1255   {
1256     if (!(checkForHMM() && alignmentIsSufficient(2)))
1257     {
1258       return;
1259     }
1260
1261     /*
1262      * get default parameters, and optionally show a dialog
1263      * to allow them to be modified
1264      */
1265     ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1266     List<ArgumentI> args = store.getServiceParameters();
1267
1268     if (!withDefaults)
1269     {
1270       WsParamSetI set = new HMMERPreset();
1271       WsJobParameters params = new WsJobParameters(store, set, args);
1272       params.showRunDialog().thenAccept((startJob) -> {
1273         if (startJob)
1274         {
1275           var args2 = params.getJobParams();
1276           new Thread(new HMMAlign(this, args2)).start();
1277         }
1278       });
1279     }
1280     else
1281     {
1282       new Thread(new HMMAlign(this, args)).start();
1283     }
1284   }
1285
1286   @Override
1287   public void hmmSearch_actionPerformed(boolean withDefaults)
1288   {
1289     if (!checkForHMM())
1290     {
1291       return;
1292     }
1293
1294     /*
1295      * get default parameters, and (if requested) show 
1296      * dialog to allow modification
1297      */
1298     ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1299     List<ArgumentI> args = store.getServiceParameters();
1300
1301     if (!withDefaults)
1302     {
1303       WsParamSetI set = new HMMERPreset();
1304       WsJobParameters params = new WsJobParameters(store, set, args);
1305       params.showRunDialog().thenAccept((startJob) -> {
1306         if (startJob)
1307         {
1308           var args2 = params.getJobParams();
1309           new Thread(new HMMSearch(this, args2)).start();
1310           alignPanel.repaint();
1311         }
1312       });
1313     }
1314     else
1315     {
1316       new Thread(new HMMSearch(this, args)).start();
1317       alignPanel.repaint();
1318     }
1319   }
1320
1321   @Override
1322   public void jackhmmer_actionPerformed(boolean withDefaults)
1323   {
1324
1325     /*
1326      * get default parameters, and (if requested) show 
1327      * dialog to allow modification
1328      */
1329
1330     ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
1331     List<ArgumentI> args = store.getServiceParameters();
1332
1333     if (!withDefaults)
1334     {
1335       WsParamSetI set = new HMMERPreset();
1336       WsJobParameters params = new WsJobParameters(store, set, args);
1337       params.showRunDialog().thenAccept((startJob) -> {
1338         if (startJob)
1339         {
1340           var args2 = params.getJobParams();
1341           new Thread(new JackHMMER(this, args2)).start();
1342           alignPanel.repaint();
1343         }
1344       });
1345     }
1346     else
1347     {
1348       new Thread(new JackHMMER(this, args)).start();
1349       alignPanel.repaint();
1350     }
1351   }
1352
1353   /**
1354    * Checks if the alignment has at least one hidden Markov model, if not shows
1355    * a dialog advising to run hmmbuild or load an HMM profile
1356    * 
1357    * @return
1358    */
1359   private boolean checkForHMM()
1360   {
1361     if (viewport.getAlignment().getHmmSequences().isEmpty())
1362     {
1363       JOptionPane.showMessageDialog(this,
1364               MessageManager.getString("warn.no_hmm"));
1365       return false;
1366     }
1367     return true;
1368   }
1369
1370   @Override
1371   protected void filterByEValue_actionPerformed()
1372   {
1373     viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
1374   }
1375
1376   @Override
1377   protected void filterByScore_actionPerformed()
1378   {
1379     viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
1380   }
1381
1382   private double inputDouble(String message)
1383   {
1384     String str = null;
1385     Double d = null;
1386     while (d == null || d <= 0)
1387     {
1388       str = JOptionPane.showInputDialog(this.alignPanel, message);
1389       try
1390       {
1391         d = Double.valueOf(str);
1392       } catch (NumberFormatException e)
1393       {
1394       }
1395     }
1396     return d;
1397   }
1398
1399   /**
1400    * Checks if the alignment contains the required number of sequences.
1401    * 
1402    * @param required
1403    * @return
1404    */
1405   public boolean alignmentIsSufficient(int required)
1406   {
1407     if (getViewport().getSequenceSelection().length < required)
1408     {
1409       JOptionPane.showMessageDialog(this,
1410               MessageManager.getString("label.not_enough_sequences"));
1411       return false;
1412     }
1413     return true;
1414   }
1415
1416   /**
1417    * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1418    * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1419    * comma-separated list)
1420    */
1421   @Override
1422   public void addDatabase_actionPerformed() throws IOException
1423   {
1424     if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1425     {
1426       Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1427     }
1428
1429     String path = openFileChooser(false);
1430     if (path != null && new File(path).exists())
1431     {
1432       IdentifyFile identifier = new IdentifyFile();
1433       FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1434       if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1435               || format == FileFormat.Pfam)
1436       {
1437         String currentDbPaths = Cache
1438                 .getProperty(Preferences.HMMSEARCH_DBS);
1439         currentDbPaths += Preferences.COMMA + path;
1440         Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1441       }
1442       else
1443       {
1444         JOptionPane.showMessageDialog(this,
1445                 MessageManager.getString("warn.invalid_format"));
1446       }
1447     }
1448   }
1449
1450   /**
1451    * Opens a file chooser, optionally restricted to selecting folders
1452    * (directories) only. Answers the path to the selected file or folder, or
1453    * null if none is chosen.
1454    * 
1455    * @param
1456    * @return
1457    */
1458   protected String openFileChooser(boolean forFolder)
1459   {
1460     // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1461     String choice = null;
1462     JFileChooser chooser = new JFileChooser();
1463     if (forFolder)
1464     {
1465       chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1466     }
1467     chooser.setDialogTitle(
1468             MessageManager.getString("label.open_local_file"));
1469     chooser.setToolTipText(MessageManager.getString("action.open"));
1470
1471     int value = chooser.showOpenDialog(this);
1472
1473     if (value == JFileChooser.APPROVE_OPTION)
1474     {
1475       choice = chooser.getSelectedFile().getPath();
1476     }
1477     return choice;
1478   }
1479
1480   @Override
1481   public void reload_actionPerformed(ActionEvent e)
1482   {
1483     if (fileName == null && fileObject == null)
1484     {
1485       return;
1486     }
1487     // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1488     // originating file's format
1489     // TODO: work out how to recover feature settings for correct view(s) when
1490     // file is reloaded.
1491     if (FileFormat.Jalview.equals(currentFileFormat))
1492     {
1493       JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1494       for (int i = 0; i < frames.length; i++)
1495       {
1496         if (frames[i] instanceof AlignFrame && frames[i] != this
1497                 && ((AlignFrame) frames[i]).fileName != null
1498                 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1499         {
1500           try
1501           {
1502             frames[i].setSelected(true);
1503             Desktop.getInstance().closeAssociatedWindows();
1504           } catch (java.beans.PropertyVetoException ex)
1505           {
1506           }
1507         }
1508
1509       }
1510       Desktop.getInstance().closeAssociatedWindows();
1511
1512       FileLoader loader = new FileLoader();
1513       loader.LoadFile(viewport, (fileObject == null ? fileName : fileObject), protocol, currentFileFormat);
1514     }
1515     else
1516     {
1517       Rectangle bounds = this.getBounds();
1518
1519       FileLoader loader = new FileLoader();
1520
1521       AlignFrame newframe = null;
1522
1523       if (fileObject == null)
1524       {
1525         newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1526                 currentFileFormat);
1527       }
1528       else
1529       {
1530         newframe = loader.LoadFileWaitTillLoaded(fileObject,
1531                 DataSourceType.FILE, currentFileFormat);
1532       }
1533
1534       newframe.setBounds(bounds);
1535       if (featureSettings != null && featureSettings.isShowing())
1536       {
1537         final Rectangle fspos = featureSettings.frame.getBounds();
1538         // TODO: need a 'show feature settings' function that takes bounds -
1539         // need to refactor Desktop.addFrame
1540         newframe.featureSettings_actionPerformed(null);
1541         final FeatureSettings nfs = newframe.featureSettings;
1542         SwingUtilities.invokeLater(new Runnable()
1543         {
1544           @Override
1545           public void run()
1546           {
1547             nfs.frame.setBounds(fspos);
1548           }
1549         });
1550         this.featureSettings.close();
1551         this.featureSettings = null;
1552       }
1553       this.closeMenuItem_actionPerformed(true);
1554     }
1555   }
1556
1557   @Override
1558   public void addFromText_actionPerformed(ActionEvent e)
1559   {
1560     Desktop.getInstance()
1561             .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1562   }
1563
1564   @Override
1565   public void addFromURL_actionPerformed(ActionEvent e)
1566   {
1567     Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1568   }
1569
1570   @Override
1571   public void save_actionPerformed(ActionEvent e)
1572   {
1573     if (fileName == null || (currentFileFormat == null)
1574             || HttpUtils.startsWithHttpOrHttps(fileName))
1575     {
1576       saveAs_actionPerformed();
1577     }
1578     else
1579     {
1580       saveAlignment(fileName, currentFileFormat);
1581     }
1582   }
1583
1584   /**
1585    * Saves the alignment to a file with a name chosen by the user, if necessary
1586    * warning if a file would be overwritten
1587    */
1588   @Override
1589   public void saveAs_actionPerformed()
1590   {
1591     String format = currentFileFormat == null ? null
1592             : currentFileFormat.getName();
1593     JalviewFileChooser chooser = JalviewFileChooser
1594             .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1595
1596     chooser.setFileView(new JalviewFileView());
1597     chooser.setDialogTitle(
1598             MessageManager.getString("label.save_alignment_to_file"));
1599     chooser.setToolTipText(MessageManager.getString("action.save"));
1600
1601     int value = chooser.showSaveDialog(this);
1602
1603     if (value != JalviewFileChooser.APPROVE_OPTION)
1604     {
1605       return;
1606     }
1607     currentFileFormat = chooser.getSelectedFormat();
1608     // todo is this (2005) test now obsolete - value is never null?
1609     while (currentFileFormat == null)
1610     {
1611       JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1612               MessageManager
1613                       .getString("label.select_file_format_before_saving"),
1614               MessageManager.getString("label.file_format_not_specified"),
1615               JvOptionPane.WARNING_MESSAGE);
1616       currentFileFormat = chooser.getSelectedFormat();
1617       value = chooser.showSaveDialog(this);
1618       if (value != JalviewFileChooser.APPROVE_OPTION)
1619       {
1620         return;
1621       }
1622     }
1623
1624     fileName = chooser.getSelectedFile().getPath();
1625
1626     Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1627     Cache.setProperty("LAST_DIRECTORY", fileName);
1628     saveAlignment(fileName, currentFileFormat);
1629   }
1630
1631   boolean lastSaveSuccessful = false;
1632
1633   FileFormatI lastFormatSaved;
1634
1635   String lastFilenameSaved;
1636
1637   /**
1638    * Raise a dialog or status message for the last call to saveAlignment.
1639    *
1640    * @return true if last call to saveAlignment(file, format) was successful.
1641    */
1642   public boolean isSaveAlignmentSuccessful()
1643   {
1644
1645     if (!lastSaveSuccessful)
1646     {
1647       if (!Platform.isHeadless())
1648       {
1649         JvOptionPane.showInternalMessageDialog(this, MessageManager
1650                 .formatMessage("label.couldnt_save_file", new Object[]
1651                 { lastFilenameSaved }),
1652                 MessageManager.getString("label.error_saving_file"),
1653                 JvOptionPane.WARNING_MESSAGE);
1654       }
1655       else
1656       {
1657         Console.error(MessageManager
1658                 .formatMessage("label.couldnt_save_file", new Object[]
1659                 { lastFilenameSaved }));
1660       }
1661     }
1662     else
1663     {
1664
1665       setStatus(MessageManager.formatMessage(
1666               "label.successfully_saved_to_file_in_format", new Object[]
1667               { lastFilenameSaved, lastFormatSaved }));
1668
1669     }
1670     return lastSaveSuccessful;
1671   }
1672
1673   /**
1674    * Saves the alignment to the specified file path, in the specified format,
1675    * which may be an alignment format, or Jalview project format. If the
1676    * alignment has hidden regions, or the format is one capable of including
1677    * non-sequence data (features, annotations, groups), then the user may be
1678    * prompted to specify what to include in the output.
1679    * 
1680    * @param file
1681    * @param format
1682    */
1683   public void saveAlignment(String file, FileFormatI format)
1684   {
1685     lastSaveSuccessful = true;
1686     lastFilenameSaved = file;
1687     lastFormatSaved = format;
1688
1689     if (FileFormat.Jalview.equals(format))
1690     {
1691       String shortName = title;
1692       if (shortName.indexOf(File.separatorChar) > -1)
1693       {
1694         shortName = shortName
1695                 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1696       }
1697       lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1698               shortName);
1699
1700       statusBar.setText(MessageManager.formatMessage(
1701               "label.successfully_saved_to_file_in_format", new Object[]
1702               { fileName, format }));
1703
1704       return;
1705     }
1706
1707     AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1708     Runnable cancelAction = new Runnable()
1709     {
1710       @Override
1711       public void run()
1712       {
1713         lastSaveSuccessful = false;
1714       }
1715     };
1716     Runnable outputAction = new Runnable()
1717     {
1718       @Override
1719       public void run()
1720       {
1721         // todo defer this to inside formatSequences (or later)
1722         AlignmentExportData exportData = viewport
1723                 .getAlignExportData(options);
1724         String output = new FormatAdapter(alignPanel, options)
1725                 .formatSequences(format, exportData.getAlignment(),
1726                         exportData.getOmitHidden(),
1727                         exportData.getStartEndPostions(),
1728                         viewport.getAlignment().getHiddenColumns());
1729         if (output == null)
1730         {
1731           lastSaveSuccessful = false;
1732         }
1733         else
1734         {
1735           // create backupfiles object and get new temp filename destination
1736           boolean doBackup = BackupFiles.getEnabled();
1737           BackupFiles backupfiles = null;
1738           if (doBackup)
1739           {
1740             Console.trace(
1741                     "ALIGNFRAME making backupfiles object for " + file);
1742             backupfiles = new BackupFiles(file);
1743           }
1744           try
1745           {
1746             String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1747                     : file;
1748             Console.trace("ALIGNFRAME setting PrintWriter");
1749             PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1750
1751             if (backupfiles != null)
1752             {
1753               Console.trace("ALIGNFRAME about to write to temp file "
1754                       + backupfiles.getTempFilePath());
1755             }
1756
1757             out.print(output);
1758             Console.trace("ALIGNFRAME about to close file");
1759             out.close();
1760             Console.trace("ALIGNFRAME closed file");
1761             AlignFrame.this.setTitle(file);
1762             statusBar.setText(MessageManager.formatMessage(
1763                     "label.successfully_saved_to_file_in_format",
1764                     new Object[]
1765                     { fileName, format.getName() }));
1766             lastSaveSuccessful = true;
1767           } catch (IOException e)
1768           {
1769             lastSaveSuccessful = false;
1770             Console.error(
1771                     "ALIGNFRAME Something happened writing the temp file");
1772             Console.error(e.getMessage());
1773             Console.debug(Cache.getStackTraceString(e));
1774           } catch (Exception ex)
1775           {
1776             lastSaveSuccessful = false;
1777             Console.error(
1778                     "ALIGNFRAME Something unexpected happened writing the temp file");
1779             Console.error(ex.getMessage());
1780             Console.debug(Cache.getStackTraceString(ex));
1781           }
1782
1783           if (doBackup)
1784           {
1785             backupfiles.setWriteSuccess(lastSaveSuccessful);
1786             Console.debug("ALIGNFRAME writing temp file was "
1787                     + (lastSaveSuccessful ? "" : "NOT ") + "successful");
1788             // do the backup file roll and rename the temp file to actual file
1789             Console.trace(
1790                     "ALIGNFRAME about to rollBackupsAndRenameTempFile");
1791             lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1792             Console.debug(
1793                     "ALIGNFRAME performed rollBackupsAndRenameTempFile "
1794                             + (lastSaveSuccessful ? "" : "un")
1795                             + "successfully");
1796           }
1797         }
1798       }
1799     };
1800
1801     /*
1802      * show dialog with export options if applicable; else just do it
1803      */
1804     if (AlignExportOptions.isNeeded(viewport, format))
1805     {
1806       AlignExportOptions choices = new AlignExportOptions(
1807               alignPanel.getAlignViewport(), format, options);
1808       choices.setResponseAction(0, outputAction);
1809       choices.setResponseAction(1, cancelAction);
1810       choices.showDialog();
1811     }
1812     else
1813     {
1814       outputAction.run();
1815     }
1816   }
1817
1818   /**
1819    * Outputs the alignment to textbox in the requested format, if necessary
1820    * first prompting the user for whether to include hidden regions or
1821    * non-sequence data
1822    * 
1823    * @param fileFormatName
1824    */
1825   @Override
1826   protected void outputText_actionPerformed(String fileFormatName)
1827   {
1828     FileFormatI fileFormat = FileFormats.getInstance()
1829             .forName(fileFormatName);
1830     AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1831     Runnable outputAction = new Runnable()
1832     {
1833       @Override
1834       public void run()
1835       {
1836         // todo defer this to inside formatSequences (or later)
1837         AlignmentExportData exportData = viewport
1838                 .getAlignExportData(options);
1839         CutAndPasteTransfer cap = new CutAndPasteTransfer();
1840         cap.setForInput(null);
1841         try
1842         {
1843           FileFormatI format = fileFormat;
1844           cap.setText(new FormatAdapter(alignPanel, options)
1845                   .formatSequences(format, exportData.getAlignment(),
1846                           exportData.getOmitHidden(),
1847                           exportData.getStartEndPostions(),
1848                           viewport.getAlignment().getHiddenColumns()));
1849           Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1850                   "label.alignment_output_command", new Object[]
1851                   { fileFormat.getName() }), 600, 500);
1852         } catch (OutOfMemoryError oom)
1853         {
1854           new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1855                   oom);
1856           cap.dispose();
1857         }
1858       }
1859     };
1860
1861     /*
1862      * show dialog with export options if applicable; else just do it
1863      */
1864     if (AlignExportOptions.isNeeded(viewport, fileFormat))
1865     {
1866       AlignExportOptions choices = new AlignExportOptions(
1867               alignPanel.getAlignViewport(), fileFormat, options);
1868       choices.setResponseAction(0, outputAction);
1869       choices.showDialog();
1870     }
1871     else
1872     {
1873       outputAction.run();
1874     }
1875   }
1876
1877   /**
1878    * DOCUMENT ME!
1879    * 
1880    * @param e
1881    *          DOCUMENT ME!
1882    */
1883   @Override
1884   protected void htmlMenuItem_actionPerformed(ActionEvent e)
1885   {
1886     HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1887     htmlSVG.exportHTML(null);
1888   }
1889
1890   @Override
1891   public void bioJSMenuItem_actionPerformed(ActionEvent e)
1892   {
1893     BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1894     bjs.exportHTML(null);
1895   }
1896
1897   // ??
1898   public void createImageMap(File file, String image)
1899   {
1900     alignPanel.makePNGImageMap(file, image);
1901   }
1902
1903   /**
1904    * Creates a PNG image of the alignment and writes it to the given file. If
1905    * the file is null, the user is prompted to choose a file.
1906    * 
1907    * @param f
1908    */
1909   @Override
1910   public void createPNG(File f)
1911   {
1912     alignPanel.makeAlignmentImage(TYPE.PNG, f);
1913   }
1914
1915   /**
1916    * Creates an EPS image of the alignment and writes it to the given file. If
1917    * the file is null, the user is prompted to choose a file.
1918    * 
1919    * @param f
1920    */
1921   @Override
1922   public void createEPS(File f)
1923   {
1924     alignPanel.makeAlignmentImage(TYPE.EPS, f);
1925   }
1926
1927   /**
1928    * Creates an SVG image of the alignment and writes it to the given file. If
1929    * the file is null, the user is prompted to choose a file.
1930    * 
1931    * @param f
1932    */
1933   @Override
1934   public void createSVG(File f)
1935   {
1936     alignPanel.makeAlignmentImage(TYPE.SVG, f);
1937   }
1938
1939   @Override
1940   public void pageSetup_actionPerformed(ActionEvent e)
1941   {
1942     PrinterJob printJob = PrinterJob.getPrinterJob();
1943     PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1944   }
1945
1946   /**
1947    * DOCUMENT ME!
1948    * 
1949    * @param e
1950    *          DOCUMENT ME!
1951    */
1952   @Override
1953   public void printMenuItem_actionPerformed(ActionEvent e)
1954   {
1955     // Putting in a thread avoids Swing painting problems
1956     PrintThread thread = new PrintThread(alignPanel);
1957     thread.start();
1958   }
1959
1960   @Override
1961   public void exportFeatures_actionPerformed(ActionEvent e)
1962   {
1963     new AnnotationExporter(alignPanel).exportFeatures();
1964   }
1965
1966   @Override
1967   public void exportAnnotations_actionPerformed(ActionEvent e)
1968   {
1969     new AnnotationExporter(alignPanel).exportAnnotations();
1970   }
1971
1972   @Override
1973   public void associatedData_actionPerformed(ActionEvent e)
1974           throws IOException, InterruptedException
1975   {
1976     final JalviewFileChooser chooser = new JalviewFileChooser(
1977             Cache.getProperty("LAST_DIRECTORY"));
1978     chooser.setFileView(new JalviewFileView());
1979     String tooltip = MessageManager
1980             .getString("label.load_jalview_annotations");
1981     chooser.setDialogTitle(tooltip);
1982     chooser.setToolTipText(tooltip);
1983     chooser.setResponseHandler(0, new Runnable()
1984     {
1985       @Override
1986       public void run()
1987       {
1988         String choice = chooser.getSelectedFile().getPath();
1989         Cache.setProperty("LAST_DIRECTORY", choice);
1990         loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1991       }
1992     });
1993
1994     chooser.showOpenDialog(this);
1995   }
1996
1997   /**
1998    * Close the current view or all views in the alignment frame. If the frame
1999    * only contains one view then the alignment will be removed from memory.
2000    * 
2001    * @param closeAllTabs
2002    */
2003   @Override
2004   public void closeMenuItem_actionPerformed(boolean closeAllTabs)
2005   {
2006     if (alignPanels != null && alignPanels.size() < 2)
2007     {
2008       closeAllTabs = true;
2009     }
2010
2011     try
2012     {
2013       if (alignPanels != null)
2014       {
2015         if (closeAllTabs)
2016         {
2017           if (this.isClosed())
2018           {
2019             // really close all the windows - otherwise wait till
2020             // setClosed(true) is called
2021             for (int i = 0; i < alignPanels.size(); i++)
2022             {
2023               AlignmentPanel ap = alignPanels.get(i);
2024               ap.closePanel();
2025             }
2026           }
2027         }
2028         else
2029         {
2030           closeView(alignPanel);
2031         }
2032       }
2033       if (closeAllTabs)
2034       {
2035         if (featureSettings != null && featureSettings.isOpen())
2036         {
2037           featureSettings.close();
2038           featureSettings = null;
2039         }
2040         /*
2041          * this will raise an INTERNAL_FRAME_CLOSED event and this method will
2042          * be called recursively, with the frame now in 'closed' state
2043          */
2044         this.setClosed(true);
2045       }
2046     } catch (Exception ex)
2047     {
2048       ex.printStackTrace();
2049     }
2050   }
2051
2052   /**
2053    * Close the specified panel and close up tabs appropriately.
2054    * 
2055    * @param panelToClose
2056    */
2057   public void closeView(AlignmentPanel panelToClose)
2058   {
2059     int index = tabbedPane.getSelectedIndex();
2060     int closedindex = tabbedPane.indexOfComponent(panelToClose);
2061     alignPanels.remove(panelToClose);
2062     panelToClose.closePanel();
2063     panelToClose = null;
2064
2065     tabbedPane.removeTabAt(closedindex);
2066     tabbedPane.validate();
2067
2068     if (index > closedindex || index == tabbedPane.getTabCount())
2069     {
2070       // modify currently selected tab index if necessary.
2071       index--;
2072     }
2073
2074     this.tabSelectionChanged(index);
2075   }
2076
2077   /**
2078    * DOCUMENT ME!
2079    */
2080   void updateEditMenuBar()
2081   {
2082
2083     if (viewport.getHistoryList().size() > 0)
2084     {
2085       undoMenuItem.setEnabled(true);
2086       CommandI command = viewport.getHistoryList().peek();
2087       undoMenuItem.setText(MessageManager
2088               .formatMessage("label.undo_command", new Object[]
2089               { command.getDescription() }));
2090     }
2091     else
2092     {
2093       undoMenuItem.setEnabled(false);
2094       undoMenuItem.setText(MessageManager.getString("action.undo"));
2095     }
2096
2097     if (viewport.getRedoList().size() > 0)
2098     {
2099       redoMenuItem.setEnabled(true);
2100
2101       CommandI command = viewport.getRedoList().peek();
2102       redoMenuItem.setText(MessageManager
2103               .formatMessage("label.redo_command", new Object[]
2104               { command.getDescription() }));
2105     }
2106     else
2107     {
2108       redoMenuItem.setEnabled(false);
2109       redoMenuItem.setText(MessageManager.getString("action.redo"));
2110     }
2111   }
2112
2113   @Override
2114   public void addHistoryItem(CommandI command)
2115   {
2116     if (command.getSize() > 0)
2117     {
2118       viewport.addToHistoryList(command);
2119       viewport.clearRedoList();
2120       updateEditMenuBar();
2121       viewport.updateHiddenColumns();
2122       // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
2123       // && viewport.getColumnSelection().getHiddenColumns() != null &&
2124       // viewport.getColumnSelection()
2125       // .getHiddenColumns().size() > 0);
2126     }
2127   }
2128
2129   /**
2130    * 
2131    * @return alignment objects for all views
2132    */
2133   AlignmentI[] getViewAlignments()
2134   {
2135     if (alignPanels != null)
2136     {
2137       AlignmentI[] als = new AlignmentI[alignPanels.size()];
2138       int i = 0;
2139       for (AlignmentPanel ap : alignPanels)
2140       {
2141         als[i++] = ap.av.getAlignment();
2142       }
2143       return als;
2144     }
2145     if (viewport != null)
2146     {
2147       return new AlignmentI[] { viewport.getAlignment() };
2148     }
2149     return null;
2150   }
2151
2152   /**
2153    * DOCUMENT ME!
2154    * 
2155    * @param e
2156    *          DOCUMENT ME!
2157    */
2158   @Override
2159   protected void undoMenuItem_actionPerformed(ActionEvent e)
2160   {
2161     if (viewport.getHistoryList().isEmpty())
2162     {
2163       return;
2164     }
2165     CommandI command = viewport.getHistoryList().pop();
2166     viewport.addToRedoList(command);
2167     command.undoCommand(getViewAlignments());
2168
2169     AlignmentViewport originalSource = getOriginatingSource(command);
2170     updateEditMenuBar();
2171
2172     if (originalSource != null)
2173     {
2174       if (originalSource != viewport)
2175       {
2176         Console.warn(
2177                 "Implementation worry: mismatch of viewport origin for undo");
2178       }
2179       originalSource.updateHiddenColumns();
2180       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2181       // null
2182       // && viewport.getColumnSelection().getHiddenColumns() != null &&
2183       // viewport.getColumnSelection()
2184       // .getHiddenColumns().size() > 0);
2185       originalSource.notifyAlignment();
2186     }
2187   }
2188
2189   /**
2190    * DOCUMENT ME!
2191    * 
2192    * @param e
2193    *          DOCUMENT ME!
2194    */
2195   @Override
2196   protected void redoMenuItem_actionPerformed(ActionEvent e)
2197   {
2198     if (viewport.getRedoList().size() < 1)
2199     {
2200       return;
2201     }
2202
2203     CommandI command = viewport.getRedoList().pop();
2204     viewport.addToHistoryList(command);
2205     command.doCommand(getViewAlignments());
2206
2207     AlignmentViewport originalSource = getOriginatingSource(command);
2208     updateEditMenuBar();
2209
2210     if (originalSource != null)
2211     {
2212
2213       if (originalSource != viewport)
2214       {
2215         Console.warn(
2216                 "Implementation worry: mismatch of viewport origin for redo");
2217       }
2218       originalSource.updateHiddenColumns();
2219       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2220       // null
2221       // && viewport.getColumnSelection().getHiddenColumns() != null &&
2222       // viewport.getColumnSelection()
2223       // .getHiddenColumns().size() > 0);
2224       originalSource.notifyAlignment();
2225     }
2226   }
2227
2228   AlignmentViewport getOriginatingSource(CommandI command)
2229   {
2230     AlignmentViewport originalSource = null;
2231     // For sequence removal and addition, we need to fire
2232     // the property change event FROM the viewport where the
2233     // original alignment was altered
2234     AlignmentI al = null;
2235     if (command instanceof EditCommand)
2236     {
2237       EditCommand editCommand = (EditCommand) command;
2238       al = editCommand.getAlignment();
2239       List<Component> comps = PaintRefresher.components
2240               .get(viewport.getSequenceSetId());
2241
2242       for (Component comp : comps)
2243       {
2244         if (comp instanceof AlignmentPanel)
2245         {
2246           if (al == ((AlignmentPanel) comp).av.getAlignment())
2247           {
2248             originalSource = ((AlignmentPanel) comp).av;
2249             break;
2250           }
2251         }
2252       }
2253     }
2254
2255     if (originalSource == null)
2256     {
2257       // The original view is closed, we must validate
2258       // the current view against the closed view first
2259       if (al != null)
2260       {
2261         PaintRefresher.validateSequences(al, viewport.getAlignment());
2262       }
2263
2264       originalSource = viewport;
2265     }
2266
2267     return originalSource;
2268   }
2269
2270   /**
2271    * Calls AlignmentI.moveSelectedSequencesByOne with current sequence selection
2272    * or the sequence under cursor in keyboard mode
2273    * 
2274    * @param up
2275    *          or down (if !up)
2276    */
2277   public void moveSelectedSequences(boolean up)
2278   {
2279     SequenceGroup sg = viewport.getSelectionGroup();
2280
2281     if (sg == null)
2282     {
2283       if (viewport.cursorMode)
2284       {
2285         sg = new SequenceGroup();
2286         sg.addSequence(viewport.getAlignment().getSequenceAt(
2287                 alignPanel.getSeqPanel().seqCanvas.cursorY), false);
2288       }
2289       else
2290       {
2291         return;
2292       }
2293     }
2294
2295     if (sg.getSize() < 1)
2296     {
2297       return;
2298     }
2299
2300     // TODO: JAL-3733 - add an event to the undo buffer for this !
2301
2302     viewport.getAlignment().moveSelectedSequencesByOne(sg,
2303             viewport.getHiddenRepSequences(), up);
2304     alignPanel.paintAlignment(true, false);
2305   }
2306
2307   synchronized void slideSequences(boolean right, int size)
2308   {
2309     List<SequenceI> sg = new ArrayList<>();
2310     if (viewport.cursorMode)
2311     {
2312       sg.add(viewport.getAlignment()
2313               .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2314     }
2315     else if (viewport.getSelectionGroup() != null
2316             && viewport.getSelectionGroup().getSize() != viewport
2317                     .getAlignment().getHeight())
2318     {
2319       sg = viewport.getSelectionGroup()
2320               .getSequences(viewport.getHiddenRepSequences());
2321     }
2322
2323     if (sg.size() < 1)
2324     {
2325       return;
2326     }
2327
2328     List<SequenceI> invertGroup = new ArrayList<>();
2329
2330     for (SequenceI seq : viewport.getAlignment().getSequences())
2331     {
2332       if (!sg.contains(seq))
2333       {
2334         invertGroup.add(seq);
2335       }
2336     }
2337
2338     SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2339
2340     SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2341     for (int i = 0; i < invertGroup.size(); i++)
2342     {
2343       seqs2[i] = invertGroup.get(i);
2344     }
2345
2346     SlideSequencesCommand ssc;
2347     if (right)
2348     {
2349       ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2350               viewport.getGapCharacter());
2351     }
2352     else
2353     {
2354       ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2355               viewport.getGapCharacter());
2356     }
2357
2358     int groupAdjustment = 0;
2359     if (ssc.getGapsInsertedBegin() && right)
2360     {
2361       if (viewport.cursorMode)
2362       {
2363         alignPanel.getSeqPanel().moveCursor(size, 0);
2364       }
2365       else
2366       {
2367         groupAdjustment = size;
2368       }
2369     }
2370     else if (!ssc.getGapsInsertedBegin() && !right)
2371     {
2372       if (viewport.cursorMode)
2373       {
2374         alignPanel.getSeqPanel().moveCursor(-size, 0);
2375       }
2376       else
2377       {
2378         groupAdjustment = -size;
2379       }
2380     }
2381
2382     if (groupAdjustment != 0)
2383     {
2384       viewport.getSelectionGroup().setStartRes(
2385               viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2386       viewport.getSelectionGroup().setEndRes(
2387               viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2388     }
2389
2390     /*
2391      * just extend the last slide command if compatible; but not if in
2392      * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2393      */
2394     boolean appendHistoryItem = false;
2395     Deque<CommandI> historyList = viewport.getHistoryList();
2396     boolean inSplitFrame = getSplitViewContainer() != null;
2397     if (!inSplitFrame && historyList != null && historyList.size() > 0
2398             && historyList.peek() instanceof SlideSequencesCommand)
2399     {
2400       appendHistoryItem = ssc.appendSlideCommand(
2401               (SlideSequencesCommand) historyList.peek());
2402     }
2403
2404     if (!appendHistoryItem)
2405     {
2406       addHistoryItem(ssc);
2407     }
2408
2409     repaint();
2410   }
2411
2412   /**
2413    * DOCUMENT ME!
2414    * 
2415    * @param e
2416    *          DOCUMENT ME!
2417    */
2418   @Override
2419   protected void copy_actionPerformed()
2420   {
2421     if (viewport.getSelectionGroup() == null)
2422     {
2423       return;
2424     }
2425     // TODO: preserve the ordering of displayed alignment annotation in any
2426     // internal paste (particularly sequence associated annotation)
2427     SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2428     String[] omitHidden = null;
2429
2430     if (viewport.hasHiddenColumns())
2431     {
2432       omitHidden = viewport.getViewAsString(true);
2433     }
2434
2435     String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2436             seqs, omitHidden, null);
2437
2438     StringSelection ss = new StringSelection(output);
2439
2440     Desktop d = Desktop.getInstance();
2441     try
2442     {
2443       d.internalCopy = true;
2444       // Its really worth setting the clipboard contents
2445       // to empty before setting the large StringSelection!!
2446       Toolkit.getDefaultToolkit().getSystemClipboard()
2447               .setContents(new StringSelection(""), null);
2448
2449       Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2450               d);
2451     } catch (OutOfMemoryError er)
2452     {
2453       new OOMWarning("copying region", er);
2454       return;
2455     }
2456
2457     HiddenColumns hiddenColumns = null;
2458     if (viewport.hasHiddenColumns())
2459     {
2460       int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2461       int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2462
2463       // create new HiddenColumns object with copy of hidden regions
2464       // between startRes and endRes, offset by startRes
2465       hiddenColumns = new HiddenColumns(
2466               viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2467               hiddenCutoff, hiddenOffset);
2468     }
2469
2470     d.jalviewClipboard = new Object[] { seqs,
2471         viewport.getAlignment().getDataset(), hiddenColumns };
2472     setStatus(MessageManager.formatMessage(
2473             "label.copied_sequences_to_clipboard", new Object[]
2474             { Integer.valueOf(seqs.length).toString() }));
2475   }
2476
2477   /**
2478    * DOCUMENT ME!
2479    * 
2480    * @param e
2481    *          DOCUMENT ME!
2482    * @throws InterruptedException
2483    * @throws IOException
2484    */
2485   @Override
2486   protected void pasteNew_actionPerformed(ActionEvent e)
2487           throws IOException, InterruptedException
2488   {
2489     paste(true);
2490   }
2491
2492   /**
2493    * DOCUMENT ME!
2494    * 
2495    * @param e
2496    *          DOCUMENT ME!
2497    * @throws InterruptedException
2498    * @throws IOException
2499    */
2500   @Override
2501   protected void pasteThis_actionPerformed(ActionEvent e)
2502           throws IOException, InterruptedException
2503   {
2504     paste(false);
2505   }
2506
2507   /**
2508    * Paste contents of Jalview clipboard
2509    * 
2510    * @param newAlignment
2511    *          true to paste to a new alignment, otherwise add to this.
2512    * @throws InterruptedException
2513    * @throws IOException
2514    */
2515   void paste(boolean newAlignment) throws IOException, InterruptedException
2516   {
2517     boolean externalPaste = true;
2518     try
2519     {
2520       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2521       Transferable contents = c.getContents(this);
2522
2523       if (contents == null)
2524       {
2525         return;
2526       }
2527
2528       String str;
2529       FileFormatI format;
2530       try
2531       {
2532         str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2533         if (str.length() < 1)
2534         {
2535           return;
2536         }
2537
2538         format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2539
2540       } catch (OutOfMemoryError er)
2541       {
2542         new OOMWarning("Out of memory pasting sequences!!", er);
2543         return;
2544       }
2545
2546       SequenceI[] sequences;
2547       boolean annotationAdded = false;
2548       AlignmentI alignment = null;
2549
2550       Desktop d = Desktop.getInstance();
2551
2552       if (d.jalviewClipboard != null)
2553       {
2554         // The clipboard was filled from within Jalview, we must use the
2555         // sequences
2556         // And dataset from the copied alignment
2557         SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2558         // be doubly sure that we create *new* sequence objects.
2559         sequences = new SequenceI[newseq.length];
2560         for (int i = 0; i < newseq.length; i++)
2561         {
2562           sequences[i] = new Sequence(newseq[i]);
2563         }
2564         alignment = new Alignment(sequences);
2565         externalPaste = false;
2566       }
2567       else
2568       {
2569         // parse the clipboard as an alignment.
2570         alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2571                 format);
2572         sequences = alignment.getSequencesArray();
2573       }
2574
2575       int alwidth = 0;
2576       ArrayList<Integer> newGraphGroups = new ArrayList<>();
2577       int fgroup = -1;
2578
2579       if (newAlignment)
2580       {
2581
2582         if (d.jalviewClipboard != null)
2583         {
2584           // dataset is inherited
2585           alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2586         }
2587         else
2588         {
2589           // new dataset is constructed
2590           alignment.setDataset(null);
2591         }
2592         alwidth = alignment.getWidth() + 1;
2593       }
2594       else
2595       {
2596         AlignmentI pastedal = alignment; // preserve pasted alignment object
2597         // Add pasted sequences and dataset into existing alignment.
2598         alignment = viewport.getAlignment();
2599         alwidth = alignment.getWidth() + 1;
2600         // decide if we need to import sequences from an existing dataset
2601         boolean importDs = d.jalviewClipboard != null
2602                 && d.jalviewClipboard[1] != alignment.getDataset();
2603         // importDs==true instructs us to copy over new dataset sequences from
2604         // an existing alignment
2605         Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2606                                                                       // create
2607         // minimum dataset set
2608
2609         for (int i = 0; i < sequences.length; i++)
2610         {
2611           if (importDs)
2612           {
2613             newDs.addElement(null);
2614           }
2615           SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2616           // paste
2617           if (importDs && ds != null)
2618           {
2619             if (!newDs.contains(ds))
2620             {
2621               newDs.setElementAt(ds, i);
2622               ds = new Sequence(ds);
2623               // update with new dataset sequence
2624               sequences[i].setDatasetSequence(ds);
2625             }
2626             else
2627             {
2628               ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2629             }
2630           }
2631           else
2632           {
2633             // copy and derive new dataset sequence
2634             sequences[i] = sequences[i].deriveSequence();
2635             alignment.getDataset()
2636                     .addSequence(sequences[i].getDatasetSequence());
2637             // TODO: avoid creation of duplicate dataset sequences with a
2638             // 'contains' method using SequenceI.equals()/SequenceI.contains()
2639           }
2640           alignment.addSequence(sequences[i]); // merges dataset
2641         }
2642         if (newDs != null)
2643         {
2644           newDs.clear(); // tidy up
2645         }
2646         if (alignment.getAlignmentAnnotation() != null)
2647         {
2648           for (AlignmentAnnotation alan : alignment
2649                   .getAlignmentAnnotation())
2650           {
2651             if (alan.graphGroup > fgroup)
2652             {
2653               fgroup = alan.graphGroup;
2654             }
2655           }
2656         }
2657         if (pastedal.getAlignmentAnnotation() != null)
2658         {
2659           // Add any annotation attached to alignment.
2660           AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2661           for (int i = 0; i < alann.length; i++)
2662           {
2663             annotationAdded = true;
2664             if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2665             {
2666               AlignmentAnnotation newann = new AlignmentAnnotation(
2667                       alann[i]);
2668               if (newann.graphGroup > -1)
2669               {
2670                 if (newGraphGroups.size() <= newann.graphGroup
2671                         || newGraphGroups.get(newann.graphGroup) == null)
2672                 {
2673                   for (int q = newGraphGroups
2674                           .size(); q <= newann.graphGroup; q++)
2675                   {
2676                     newGraphGroups.add(q, null);
2677                   }
2678                   newGraphGroups.set(newann.graphGroup,
2679                           Integer.valueOf(++fgroup));
2680                 }
2681                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2682                         .intValue();
2683               }
2684
2685               newann.padAnnotation(alwidth);
2686               alignment.addAnnotation(newann);
2687             }
2688           }
2689         }
2690       }
2691       if (!newAlignment)
2692       {
2693         // /////
2694         // ADD HISTORY ITEM
2695         //
2696         addHistoryItem(new EditCommand(
2697                 MessageManager.getString("label.add_sequences"),
2698                 Action.PASTE, sequences, 0, alignment.getWidth(),
2699                 alignment));
2700       }
2701       // Add any annotations attached to sequences
2702       for (int i = 0; i < sequences.length; i++)
2703       {
2704         if (sequences[i].getAnnotation() != null)
2705         {
2706           AlignmentAnnotation newann;
2707           for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2708           {
2709             annotationAdded = true;
2710             newann = sequences[i].getAnnotation()[a];
2711             newann.adjustForAlignment();
2712             newann.padAnnotation(alwidth);
2713             if (newann.graphGroup > -1)
2714             {
2715               if (newann.graphGroup > -1)
2716               {
2717                 if (newGraphGroups.size() <= newann.graphGroup
2718                         || newGraphGroups.get(newann.graphGroup) == null)
2719                 {
2720                   for (int q = newGraphGroups
2721                           .size(); q <= newann.graphGroup; q++)
2722                   {
2723                     newGraphGroups.add(q, null);
2724                   }
2725                   newGraphGroups.set(newann.graphGroup,
2726                           Integer.valueOf(++fgroup));
2727                 }
2728                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2729                         .intValue();
2730               }
2731             }
2732             alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2733             // was
2734             // duplicated
2735             // earlier
2736             alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2737                     a);
2738           }
2739         }
2740       }
2741       if (!newAlignment)
2742       {
2743
2744         // propagate alignment changed.
2745         viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2746         if (annotationAdded)
2747         {
2748           // Duplicate sequence annotation in all views.
2749           AlignmentI[] alview = this.getViewAlignments();
2750           for (int i = 0; i < sequences.length; i++)
2751           {
2752             AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2753             if (sann == null)
2754             {
2755               continue;
2756             }
2757             for (int avnum = 0; avnum < alview.length; avnum++)
2758             {
2759               if (alview[avnum] != alignment)
2760               {
2761                 // duplicate in a view other than the one with input focus
2762                 int avwidth = alview[avnum].getWidth() + 1;
2763                 // this relies on sann being preserved after we
2764                 // modify the sequence's annotation array for each duplication
2765                 for (int a = 0; a < sann.length; a++)
2766                 {
2767                   AlignmentAnnotation newann = new AlignmentAnnotation(
2768                           sann[a]);
2769                   sequences[i].addAlignmentAnnotation(newann);
2770                   newann.padAnnotation(avwidth);
2771                   alview[avnum].addAnnotation(newann); // annotation was
2772                   // duplicated earlier
2773                   // TODO JAL-1145 graphGroups are not updated for sequence
2774                   // annotation added to several views. This may cause
2775                   // strangeness
2776                   alview[avnum].setAnnotationIndex(newann, a);
2777                 }
2778               }
2779             }
2780           }
2781           buildSortByAnnotationScoresMenu();
2782         }
2783         viewport.notifyAlignment();
2784         if (alignPanels != null)
2785         {
2786           for (AlignmentPanel ap : alignPanels)
2787           {
2788             ap.validateAnnotationDimensions(false);
2789           }
2790         }
2791         else
2792         {
2793           alignPanel.validateAnnotationDimensions(false);
2794         }
2795
2796       }
2797       else
2798       {
2799         AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2800                 DEFAULT_HEIGHT);
2801         String newtitle = new String("Copied sequences");
2802
2803         if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2804         {
2805           HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2806           af.viewport.setHiddenColumns(hc);
2807         }
2808
2809         // >>>This is a fix for the moment, until a better solution is
2810         // found!!<<<
2811         af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2812                 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2813                         .getFeatureRenderer());
2814
2815         // TODO: maintain provenance of an alignment, rather than just make the
2816         // title a concatenation of operations.
2817         if (!externalPaste)
2818         {
2819           if (title.startsWith("Copied sequences"))
2820           {
2821             newtitle = title;
2822           }
2823           else
2824           {
2825             newtitle = newtitle.concat("- from " + title);
2826           }
2827         }
2828         else
2829         {
2830           newtitle = new String("Pasted sequences");
2831         }
2832
2833         Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2834                 DEFAULT_HEIGHT);
2835
2836       }
2837
2838     } catch (Exception ex)
2839     {
2840       ex.printStackTrace();
2841       System.out.println("Exception whilst pasting: " + ex);
2842       // could be anything being pasted in here
2843     }
2844
2845   }
2846
2847   @Override
2848   protected void expand_newalign(ActionEvent e)
2849   {
2850     try
2851     {
2852       AlignmentI alignment = AlignmentUtils
2853               .expandContext(getViewport().getAlignment(), -1);
2854       AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2855               DEFAULT_HEIGHT);
2856       String newtitle = new String("Flanking alignment");
2857
2858       Desktop d = Desktop.getInstance();
2859       if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2860       {
2861         HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2862         af.viewport.setHiddenColumns(hc);
2863       }
2864
2865       // >>>This is a fix for the moment, until a better solution is
2866       // found!!<<<
2867       af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2868               .transferSettings(alignPanel.getSeqPanel().seqCanvas
2869                       .getFeatureRenderer());
2870
2871       // TODO: maintain provenance of an alignment, rather than just make the
2872       // title a concatenation of operations.
2873       {
2874         if (title.startsWith("Copied sequences"))
2875         {
2876           newtitle = title;
2877         }
2878         else
2879         {
2880           newtitle = newtitle.concat("- from " + title);
2881         }
2882       }
2883
2884       Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2885
2886     } catch (Exception ex)
2887     {
2888       ex.printStackTrace();
2889       System.out.println("Exception whilst pasting: " + ex);
2890       // could be anything being pasted in here
2891     } catch (OutOfMemoryError oom)
2892     {
2893       new OOMWarning("Viewing flanking region of alignment", oom);
2894     }
2895   }
2896
2897   /**
2898    * Action Cut (delete and copy) the selected region
2899    */
2900   @Override
2901   protected void cut_actionPerformed()
2902   {
2903     copy_actionPerformed();
2904     delete_actionPerformed();
2905   }
2906
2907   /**
2908    * Performs menu option to Delete the currently selected region
2909    */
2910   @Override
2911   protected void delete_actionPerformed()
2912   {
2913
2914     SequenceGroup sg = viewport.getSelectionGroup();
2915     if (sg == null)
2916     {
2917       return;
2918     }
2919
2920     Runnable okAction = new Runnable()
2921     {
2922       @Override
2923       public void run()
2924       {
2925         SequenceI[] cut = sg.getSequences()
2926                 .toArray(new SequenceI[sg.getSize()]);
2927
2928         addHistoryItem(new EditCommand(
2929                 MessageManager.getString("label.cut_sequences"), Action.CUT,
2930                 cut, sg.getStartRes(),
2931                 sg.getEndRes() - sg.getStartRes() + 1,
2932                 viewport.getAlignment()));
2933
2934         viewport.setSelectionGroup(null);
2935         viewport.sendSelection();
2936         viewport.getAlignment().deleteGroup(sg);
2937
2938         viewport.notifyAlignment();
2939         if (viewport.getAlignment().getHeight() < 1)
2940         {
2941           try
2942           {
2943             AlignFrame.this.setClosed(true);
2944           } catch (Exception ex)
2945           {
2946           }
2947         } else {
2948           updateAll(null);
2949         }
2950       }
2951     };
2952
2953     /*
2954      * If the cut affects all sequences, prompt for confirmation
2955      */
2956     boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2957             .getHeight();
2958     boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2959             + 1) == viewport.getAlignment().getWidth()) ? true : false;
2960     if (wholeHeight && wholeWidth)
2961     {
2962       JvOptionPane dialog = JvOptionPane
2963               .newOptionDialog(Desktop.getDesktopPane());
2964       dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2965       Object[] options = new Object[] {
2966           MessageManager.getString("action.ok"),
2967           MessageManager.getString("action.cancel") };
2968       dialog.showDialog(MessageManager.getString("warn.delete_all"),
2969               MessageManager.getString("label.delete_all"),
2970               JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2971               options, options[0]);
2972     }
2973     else
2974     {
2975       okAction.run();
2976     }
2977   }
2978
2979   /**
2980    * DOCUMENT ME!
2981    * 
2982    * @param e
2983    *          DOCUMENT ME!
2984    */
2985   @Override
2986   protected void deleteGroups_actionPerformed(ActionEvent e)
2987   {
2988     if (avc.deleteGroups())
2989     {
2990       updateAll(viewport.getSequenceSetId());
2991     }
2992   }
2993
2994   private void updateAll(String id)
2995   {
2996     if (id == null)
2997     {
2998       // this will force a non-fast repaint of both the IdPanel and SeqPanel
2999       alignPanel.getIdPanel().getIdCanvas().setNoFastPaint();
3000       alignPanel.getSeqPanel().seqCanvas.setNoFastPaint();
3001       alignPanel.repaint();
3002     }
3003     else
3004     {
3005       // original version
3006       PaintRefresher.Refresh(this, id);
3007       alignPanel.paintAlignment(true, true);
3008     }
3009     alignPanel.updateAnnotation();
3010   }
3011
3012   /**
3013    * DOCUMENT ME!
3014    * 
3015    * @param e
3016    *          DOCUMENT ME!
3017    */
3018   @Override
3019   public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
3020   {
3021     alignPanel.selectAllSequences();
3022   }
3023
3024   /**
3025    * DOCUMENT ME!
3026    * 
3027    * @param e
3028    *          DOCUMENT ME!
3029    */
3030   @Override
3031   public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
3032   {
3033     alignPanel.deselectAllSequences();
3034   }
3035
3036   /**
3037    * DOCUMENT ME!
3038    * 
3039    * @param e
3040    *          DOCUMENT ME!
3041    */
3042   @Override
3043   public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
3044   {
3045     SequenceGroup sg = viewport.getSelectionGroup();
3046
3047     if (sg == null)
3048     {
3049       alignPanel.selectAllSequences();
3050
3051       return;
3052     }
3053
3054     for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
3055     {
3056       sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
3057     }
3058     // JAL-2034 - should delegate to
3059     // alignPanel to decide if overview needs
3060     // updating.
3061
3062     alignPanel.paintAlignment(true, false);
3063     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
3064     viewport.sendSelection();
3065   }
3066
3067   @Override
3068   public void invertColSel_actionPerformed(ActionEvent e)
3069   {
3070     viewport.invertColumnSelection();
3071     alignPanel.paintAlignment(true, false);
3072     viewport.sendSelection();
3073   }
3074
3075   /**
3076    * DOCUMENT ME!
3077    * 
3078    * @param e
3079    *          DOCUMENT ME!
3080    */
3081   @Override
3082   public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
3083   {
3084     trimAlignment(true);
3085   }
3086
3087   /**
3088    * DOCUMENT ME!
3089    * 
3090    * @param e
3091    *          DOCUMENT ME!
3092    */
3093   @Override
3094   public void remove2RightMenuItem_actionPerformed(ActionEvent e)
3095   {
3096     trimAlignment(false);
3097   }
3098
3099   void trimAlignment(boolean trimLeft)
3100   {
3101     ColumnSelection colSel = viewport.getColumnSelection();
3102     int column;
3103
3104     if (!colSel.isEmpty())
3105     {
3106       if (trimLeft)
3107       {
3108         column = colSel.getMin();
3109       }
3110       else
3111       {
3112         column = colSel.getMax();
3113       }
3114
3115       SequenceI[] seqs;
3116       if (viewport.getSelectionGroup() != null)
3117       {
3118         seqs = viewport.getSelectionGroup()
3119                 .getSequencesAsArray(viewport.getHiddenRepSequences());
3120       }
3121       else
3122       {
3123         seqs = viewport.getAlignment().getSequencesArray();
3124       }
3125
3126       TrimRegionCommand trimRegion;
3127       if (trimLeft)
3128       {
3129         trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
3130                 column, viewport.getAlignment());
3131         viewport.getRanges().setStartRes(0);
3132       }
3133       else
3134       {
3135         trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
3136                 column, viewport.getAlignment());
3137       }
3138
3139       setStatus(MessageManager.formatMessage("label.removed_columns",
3140               new String[]
3141               { Integer.valueOf(trimRegion.getSize()).toString() }));
3142
3143       addHistoryItem(trimRegion);
3144
3145       for (SequenceGroup sg : viewport.getAlignment().getGroups())
3146       {
3147         if ((trimLeft && !sg.adjustForRemoveLeft(column))
3148                 || (!trimLeft && !sg.adjustForRemoveRight(column)))
3149         {
3150           viewport.getAlignment().deleteGroup(sg);
3151         }
3152       }
3153
3154       viewport.notifyAlignment();
3155     }
3156   }
3157
3158   /**
3159    * DOCUMENT ME!
3160    * 
3161    * @param e
3162    *          DOCUMENT ME!
3163    */
3164   @Override
3165   public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
3166   {
3167     int start = 0, end = viewport.getAlignment().getWidth() - 1;
3168
3169     SequenceI[] seqs;
3170     if (viewport.getSelectionGroup() != null)
3171     {
3172       seqs = viewport.getSelectionGroup()
3173               .getSequencesAsArray(viewport.getHiddenRepSequences());
3174       start = viewport.getSelectionGroup().getStartRes();
3175       end = viewport.getSelectionGroup().getEndRes();
3176     }
3177     else
3178     {
3179       seqs = viewport.getAlignment().getSequencesArray();
3180     }
3181
3182     RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
3183             "Remove Gapped Columns", seqs, start, end,
3184             viewport.getAlignment());
3185
3186     addHistoryItem(removeGapCols);
3187
3188     setStatus(MessageManager.formatMessage("label.removed_empty_columns",
3189             new Object[]
3190             { Integer.valueOf(removeGapCols.getSize()).toString() }));
3191
3192     // This is to maintain viewport position on first residue
3193     // of first sequence
3194     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3195     ViewportRanges ranges = viewport.getRanges();
3196     int startRes = seq.findPosition(ranges.getStartRes());
3197     // ShiftList shifts;
3198     // viewport.getAlignment().removeGaps(shifts=new ShiftList());
3199     // edit.alColumnChanges=shifts.getInverse();
3200     // if (viewport.hasHiddenColumns)
3201     // viewport.getColumnSelection().compensateForEdits(shifts);
3202     ranges.setStartRes(seq.findIndex(startRes) - 1);
3203     viewport.notifyAlignment();
3204
3205   }
3206
3207   /**
3208    * DOCUMENT ME!
3209    * 
3210    * @param e
3211    *          DOCUMENT ME!
3212    */
3213   @Override
3214   public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
3215   {
3216     int start = 0, end = viewport.getAlignment().getWidth() - 1;
3217
3218     SequenceI[] seqs;
3219     if (viewport.getSelectionGroup() != null)
3220     {
3221       seqs = viewport.getSelectionGroup()
3222               .getSequencesAsArray(viewport.getHiddenRepSequences());
3223       start = viewport.getSelectionGroup().getStartRes();
3224       end = viewport.getSelectionGroup().getEndRes();
3225     }
3226     else
3227     {
3228       seqs = viewport.getAlignment().getSequencesArray();
3229     }
3230
3231     // This is to maintain viewport position on first residue
3232     // of first sequence
3233     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3234     int startRes = seq.findPosition(viewport.getRanges().getStartRes());
3235
3236     addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
3237             viewport.getAlignment()));
3238
3239     viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
3240
3241     viewport.notifyAlignment();
3242
3243   }
3244
3245   /**
3246    * DOCUMENT ME!
3247    * 
3248    * @param e
3249    *          DOCUMENT ME!
3250    */
3251   @Override
3252   public void padGapsMenuitem_actionPerformed(ActionEvent e)
3253   {
3254     viewport.setPadGaps(padGapsMenuitem.isSelected());
3255     viewport.notifyAlignment();
3256   }
3257
3258   /**
3259    * Opens a Finder dialog
3260    * 
3261    * @param e
3262    */
3263   @Override
3264   public void findMenuItem_actionPerformed(ActionEvent e)
3265   {
3266     new Finder(alignPanel, false, null);
3267   }
3268
3269   /**
3270    * Create a new view of the current alignment.
3271    */
3272   @Override
3273   public void newView_actionPerformed(ActionEvent e)
3274   {
3275     newView(null, true);
3276   }
3277
3278   /**
3279    * Creates and shows a new view of the current alignment.
3280    * 
3281    * @param viewTitle
3282    *          title of newly created view; if null, one will be generated
3283    * @param copyAnnotation
3284    *          if true then duplicate all annnotation, groups and settings
3285    * @return new alignment panel, already displayed.
3286    */
3287   public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
3288   {
3289     /*
3290      * Create a new AlignmentPanel (with its own, new Viewport)
3291      */
3292     AlignmentPanel newap = new jalview.project.Jalview2XML()
3293             .copyAlignPanel(alignPanel);
3294     if (!copyAnnotation)
3295     {
3296       /*
3297        * remove all groups and annotation except for the automatic stuff
3298        */
3299       newap.av.getAlignment().deleteAllGroups();
3300       newap.av.getAlignment().deleteAllAnnotations(false);
3301     }
3302
3303     newap.av.setGatherViewsHere(false);
3304
3305     if (viewport.getViewName() == null)
3306     {
3307       viewport.setViewName(
3308               MessageManager.getString("label.view_name_original"));
3309     }
3310
3311     /*
3312      * Views share the same edits undo and redo stacks
3313      */
3314     newap.av.setHistoryList(viewport.getHistoryList());
3315     newap.av.setRedoList(viewport.getRedoList());
3316
3317     /*
3318      * copy any visualisation settings that are not saved in the project
3319      */
3320     newap.av.setColourAppliesToAllGroups(
3321             viewport.getColourAppliesToAllGroups());
3322
3323     /*
3324      * Views share the same mappings; need to deregister any new mappings
3325      * created by copyAlignPanel, and register the new reference to the shared
3326      * mappings
3327      */
3328     newap.av.replaceMappings(viewport.getAlignment());
3329
3330     /*
3331      * start up cDNA consensus (if applicable) now mappings are in place
3332      */
3333     if (newap.av.initComplementConsensus())
3334     {
3335       newap.refresh(true); // adjust layout of annotations
3336     }
3337
3338     newap.av.setViewName(getNewViewName(viewTitle));
3339
3340     addAlignmentPanel(newap, true);
3341     newap.alignmentChanged();
3342
3343     if (alignPanels.size() == 2)
3344     {
3345       viewport.setGatherViewsHere(true);
3346     }
3347     tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3348     return newap;
3349   }
3350
3351   /**
3352    * Make a new name for the view, ensuring it is unique within the current
3353    * sequenceSetId. (This used to be essential for Jalview Project archives, but
3354    * these now use viewId. Unique view names are still desirable for usability.)
3355    * 
3356    * @param viewTitle
3357    * @return
3358    */
3359   protected String getNewViewName(String viewTitle)
3360   {
3361     int index = Desktop.getViewCount(viewport.getSequenceSetId());
3362     boolean addFirstIndex = false;
3363     if (viewTitle == null || viewTitle.trim().length() == 0)
3364     {
3365       viewTitle = MessageManager.getString("action.view");
3366       addFirstIndex = true;
3367     }
3368     else
3369     {
3370       index = 1;// we count from 1 if given a specific name
3371     }
3372     String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3373
3374     List<Component> comps = PaintRefresher.components
3375             .get(viewport.getSequenceSetId());
3376
3377     List<String> existingNames = getExistingViewNames(comps);
3378
3379     while (existingNames.contains(newViewName))
3380     {
3381       newViewName = viewTitle + " " + (++index);
3382     }
3383     return newViewName;
3384   }
3385
3386   /**
3387    * Returns a list of distinct view names found in the given list of
3388    * components. View names are held on the viewport of an AlignmentPanel.
3389    * 
3390    * @param comps
3391    * @return
3392    */
3393   protected List<String> getExistingViewNames(List<Component> comps)
3394   {
3395     List<String> existingNames = new ArrayList<>();
3396     for (Component comp : comps)
3397     {
3398       if (comp instanceof AlignmentPanel)
3399       {
3400         AlignmentPanel ap = (AlignmentPanel) comp;
3401         if (!existingNames.contains(ap.av.getViewName()))
3402         {
3403           existingNames.add(ap.av.getViewName());
3404         }
3405       }
3406     }
3407     return existingNames;
3408   }
3409
3410   /**
3411    * Explode tabbed views into separate windows.
3412    */
3413   @Override
3414   public void expandViews_actionPerformed(ActionEvent e)
3415   {
3416     Desktop.explodeViews(this);
3417   }
3418
3419   /**
3420    * Gather views in separate windows back into a tabbed presentation.
3421    */
3422   @Override
3423   public void gatherViews_actionPerformed(ActionEvent e)
3424   {
3425     Desktop.getInstance().gatherViews(this);
3426   }
3427
3428   /**
3429    * DOCUMENT ME!
3430    * 
3431    * @param e
3432    *          DOCUMENT ME!
3433    */
3434   @Override
3435   public void font_actionPerformed(ActionEvent e)
3436   {
3437     new FontChooser(alignPanel);
3438   }
3439
3440   /**
3441    * DOCUMENT ME!
3442    * 
3443    * @param e
3444    *          DOCUMENT ME!
3445    */
3446   @Override
3447   protected void seqLimit_actionPerformed(ActionEvent e)
3448   {
3449     viewport.setShowJVSuffix(seqLimits.isSelected());
3450
3451     alignPanel.getIdPanel().getIdCanvas()
3452             .setPreferredSize(alignPanel.calculateIdWidth());
3453     alignPanel.paintAlignment(true, false);
3454   }
3455
3456   @Override
3457   public void idRightAlign_actionPerformed(ActionEvent e)
3458   {
3459     viewport.setRightAlignIds(idRightAlign.isSelected());
3460     alignPanel.paintAlignment(false, false);
3461   }
3462
3463   @Override
3464   public void centreColumnLabels_actionPerformed(ActionEvent e)
3465   {
3466     viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3467     alignPanel.paintAlignment(false, false);
3468   }
3469
3470   /*
3471    * (non-Javadoc)
3472    * 
3473    * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3474    */
3475   @Override
3476   protected void followHighlight_actionPerformed()
3477   {
3478     /*
3479      * Set the 'follow' flag on the Viewport (and scroll to position if now
3480      * true).
3481      */
3482     final boolean state = this.followHighlightMenuItem.getState();
3483     viewport.setFollowHighlight(state);
3484     if (state)
3485     {
3486       alignPanel.scrollToPosition(viewport.getSearchResults());
3487     }
3488   }
3489
3490   /**
3491    * DOCUMENT ME!
3492    * 
3493    * @param e
3494    *          DOCUMENT ME!
3495    */
3496   @Override
3497   protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3498   {
3499     viewport.setColourText(colourTextMenuItem.isSelected());
3500     alignPanel.paintAlignment(false, false);
3501   }
3502
3503   /**
3504    * DOCUMENT ME!
3505    * 
3506    * @param e
3507    *          DOCUMENT ME!
3508    */
3509   @Override
3510   public void wrapMenuItem_actionPerformed(ActionEvent e)
3511   {
3512     scaleAbove.setVisible(wrapMenuItem.isSelected());
3513     scaleLeft.setVisible(wrapMenuItem.isSelected());
3514     scaleRight.setVisible(wrapMenuItem.isSelected());
3515     viewport.setWrapAlignment(wrapMenuItem.isSelected());
3516     alignPanel.updateLayout();
3517   }
3518
3519   @Override
3520   public void showAllSeqs_actionPerformed(ActionEvent e)
3521   {
3522     viewport.showAllHiddenSeqs();
3523   }
3524
3525   @Override
3526   public void showAllColumns_actionPerformed(ActionEvent e)
3527   {
3528     viewport.showAllHiddenColumns();
3529     alignPanel.paintAlignment(true, true);
3530     viewport.sendSelection();
3531   }
3532
3533   @Override
3534   public void hideSelSequences_actionPerformed(ActionEvent e)
3535   {
3536     viewport.hideAllSelectedSeqs();
3537   }
3538
3539   /**
3540    * called by key handler and the hide all/show all menu items
3541    * 
3542    * @param toggleSeqs
3543    * @param toggleCols
3544    */
3545   protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3546   {
3547
3548     boolean hide = false;
3549     SequenceGroup sg = viewport.getSelectionGroup();
3550     if (!toggleSeqs && !toggleCols)
3551     {
3552       // Hide everything by the current selection - this is a hack - we do the
3553       // invert and then hide
3554       // first check that there will be visible columns after the invert.
3555       if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3556               && sg.getStartRes() <= sg.getEndRes()))
3557       {
3558         // now invert the sequence set, if required - empty selection implies
3559         // that no hiding is required.
3560         if (sg != null)
3561         {
3562           invertSequenceMenuItem_actionPerformed(null);
3563           sg = viewport.getSelectionGroup();
3564           toggleSeqs = true;
3565
3566         }
3567         viewport.expandColSelection(sg, true);
3568         // finally invert the column selection and get the new sequence
3569         // selection.
3570         invertColSel_actionPerformed(null);
3571         toggleCols = true;
3572       }
3573     }
3574
3575     if (toggleSeqs)
3576     {
3577       if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3578       {
3579         hideSelSequences_actionPerformed(null);
3580         hide = true;
3581       }
3582       else if (!(toggleCols && viewport.hasSelectedColumns()))
3583       {
3584         showAllSeqs_actionPerformed(null);
3585       }
3586     }
3587
3588     if (toggleCols)
3589     {
3590       if (viewport.hasSelectedColumns())
3591       {
3592         hideSelColumns_actionPerformed(null);
3593         if (!toggleSeqs)
3594         {
3595           viewport.setSelectionGroup(sg);
3596         }
3597       }
3598       else if (!hide)
3599       {
3600         showAllColumns_actionPerformed(null);
3601       }
3602     }
3603   }
3604
3605   /*
3606    * (non-Javadoc)
3607    * 
3608    * @see
3609    * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3610    * event.ActionEvent)
3611    */
3612   @Override
3613   public void hideAllButSelection_actionPerformed(ActionEvent e)
3614   {
3615     toggleHiddenRegions(false, false);
3616     viewport.sendSelection();
3617   }
3618
3619   /*
3620    * (non-Javadoc)
3621    * 
3622    * @see
3623    * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3624    * .ActionEvent)
3625    */
3626   @Override
3627   public void hideAllSelection_actionPerformed(ActionEvent e)
3628   {
3629     SequenceGroup sg = viewport.getSelectionGroup();
3630     viewport.expandColSelection(sg, false);
3631     viewport.hideAllSelectedSeqs();
3632     viewport.hideSelectedColumns();
3633     alignPanel.updateLayout();
3634     alignPanel.paintAlignment(true, true);
3635     viewport.sendSelection();
3636   }
3637
3638   /*
3639    * (non-Javadoc)
3640    * 
3641    * @see
3642    * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3643    * ActionEvent)
3644    */
3645   @Override
3646   public void showAllhidden_actionPerformed(ActionEvent e)
3647   {
3648     viewport.showAllHiddenColumns();
3649     viewport.showAllHiddenSeqs();
3650     alignPanel.paintAlignment(true, true);
3651     viewport.sendSelection();
3652   }
3653
3654   @Override
3655   public void hideSelColumns_actionPerformed(ActionEvent e)
3656   {
3657     viewport.hideSelectedColumns();
3658     alignPanel.updateLayout();
3659     alignPanel.paintAlignment(true, true);
3660     viewport.sendSelection();
3661   }
3662
3663   @Override
3664   public void hiddenMarkers_actionPerformed(ActionEvent e)
3665   {
3666     viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3667     repaint();
3668   }
3669
3670   /**
3671    * DOCUMENT ME!
3672    * 
3673    * @param e
3674    *          DOCUMENT ME!
3675    */
3676   @Override
3677   protected void scaleAbove_actionPerformed(ActionEvent e)
3678   {
3679     viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3680     alignPanel.updateLayout();
3681     alignPanel.paintAlignment(true, false);
3682   }
3683
3684   /**
3685    * DOCUMENT ME!
3686    * 
3687    * @param e
3688    *          DOCUMENT ME!
3689    */
3690   @Override
3691   protected void scaleLeft_actionPerformed(ActionEvent e)
3692   {
3693     viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3694     alignPanel.updateLayout();
3695     alignPanel.paintAlignment(true, false);
3696   }
3697
3698   /**
3699    * DOCUMENT ME!
3700    * 
3701    * @param e
3702    *          DOCUMENT ME!
3703    */
3704   @Override
3705   protected void scaleRight_actionPerformed(ActionEvent e)
3706   {
3707     viewport.setScaleRightWrapped(scaleRight.isSelected());
3708     alignPanel.updateLayout();
3709     alignPanel.paintAlignment(true, false);
3710   }
3711
3712   /**
3713    * DOCUMENT ME!
3714    * 
3715    * @param e
3716    *          DOCUMENT ME!
3717    */
3718   @Override
3719   public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3720   {
3721     viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3722     alignPanel.paintAlignment(false, false);
3723   }
3724
3725   /**
3726    * DOCUMENT ME!
3727    * 
3728    * @param e
3729    *          DOCUMENT ME!
3730    */
3731   @Override
3732   public void viewTextMenuItem_actionPerformed(ActionEvent e)
3733   {
3734     viewport.setShowText(viewTextMenuItem.isSelected());
3735     alignPanel.paintAlignment(false, false);
3736   }
3737
3738   /**
3739    * DOCUMENT ME!
3740    * 
3741    * @param e
3742    *          DOCUMENT ME!
3743    */
3744   @Override
3745   protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3746   {
3747     viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3748     alignPanel.paintAlignment(false, false);
3749   }
3750
3751   public FeatureSettings featureSettings;
3752
3753   @Override
3754   public FeatureSettingsControllerI getFeatureSettingsUI()
3755   {
3756     return featureSettings;
3757   }
3758
3759   @Override
3760   public void featureSettings_actionPerformed(ActionEvent e)
3761   {
3762     showFeatureSettingsUI();
3763   }
3764
3765   @Override
3766   public FeatureSettingsControllerI showFeatureSettingsUI()
3767   {
3768     if (featureSettings != null)
3769     {
3770       featureSettings.closeOldSettings();
3771       featureSettings = null;
3772     }
3773     if (!showSeqFeatures.isSelected())
3774     {
3775       // make sure features are actually displayed
3776       showSeqFeatures.setSelected(true);
3777       showSeqFeatures_actionPerformed(null);
3778     }
3779     featureSettings = new FeatureSettings(this);
3780     return featureSettings;
3781   }
3782
3783   /**
3784    * Set or clear 'Show Sequence Features'
3785    * 
3786    * @param evt
3787    *          DOCUMENT ME!
3788    */
3789   @Override
3790   public void showSeqFeatures_actionPerformed(ActionEvent evt)
3791   {
3792     viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3793     alignPanel.paintAlignment(true, true);
3794   }
3795
3796   /**
3797    * Action on toggle of the 'Show annotations' menu item. This shows or hides
3798    * the annotations panel as a whole.
3799    * 
3800    * The options to show/hide all annotations should be enabled when the panel
3801    * is shown, and disabled when the panel is hidden.
3802    * 
3803    * @param e
3804    */
3805   @Override
3806   public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3807   {
3808     final boolean setVisible = annotationPanelMenuItem.isSelected();
3809     viewport.setShowAnnotation(setVisible);
3810     syncAnnotationMenuItems(setVisible);
3811     alignPanel.updateLayout();
3812     repaint();
3813     SwingUtilities.invokeLater(new Runnable() {
3814
3815       @Override
3816       public void run()
3817       {
3818         alignPanel.updateScrollBarsFromRanges();
3819       }
3820       
3821     });
3822   }
3823
3824   private void syncAnnotationMenuItems(boolean setVisible)
3825   {
3826     showAllSeqAnnotations.setEnabled(setVisible);
3827     hideAllSeqAnnotations.setEnabled(setVisible);
3828     showAllAlAnnotations.setEnabled(setVisible);
3829     hideAllAlAnnotations.setEnabled(setVisible);
3830   }
3831
3832   @Override
3833   public void alignmentProperties()
3834   {
3835     JComponent pane;
3836     StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3837
3838             .formatAsHtml();
3839     String content = MessageManager.formatMessage("label.html_content",
3840             new Object[]
3841             { contents.toString() });
3842     contents = null;
3843
3844     if (Platform.isJS())
3845     {
3846       JLabel textLabel = new JLabel();
3847       textLabel.setText(content);
3848       textLabel.setBackground(Color.WHITE);
3849
3850       pane = new JPanel(new BorderLayout());
3851       ((JPanel) pane).setOpaque(true);
3852       pane.setBackground(Color.WHITE);
3853       ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3854     }
3855     else
3856     /**
3857      * Java only
3858      * 
3859      * @j2sIgnore
3860      */
3861     {
3862       JEditorPane editPane = new JEditorPane("text/html", "");
3863       editPane.setEditable(false);
3864       editPane.setText(content);
3865       pane = editPane;
3866     }
3867
3868     JInternalFrame frame = new JInternalFrame();
3869
3870     frame.getContentPane().add(new JScrollPane(pane));
3871
3872     Desktop.addInternalFrame(frame, MessageManager
3873             .formatMessage("label.alignment_properties", new Object[]
3874             { getTitle() }), 500, 400);
3875   }
3876
3877   /**
3878    * DOCUMENT ME!
3879    * 
3880    * @param e
3881    *          DOCUMENT ME!
3882    */
3883   @Override
3884   public void overviewMenuItem_actionPerformed(ActionEvent e)
3885   {
3886     if (alignPanel.overviewPanel != null)
3887     {
3888       return;
3889     }
3890
3891     JInternalFrame frame = new JInternalFrame();
3892     // BH 2019.07.26 we allow for an embedded
3893     // undecorated overview with defined size
3894     frame.setName(Platform.getAppID("overview"));
3895     //
3896     Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3897     if (dim != null && dim.width == 0)
3898     {
3899       dim = null; // hidden, not embedded
3900     }
3901     OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3902     frame.setContentPane(overview);
3903     if (dim == null)
3904     {
3905       dim = new Dimension();
3906       // was frame.getSize(), but that is 0,0 at this point;
3907     }
3908     else
3909     {
3910       // we are imbedding, and so we have an undecorated frame
3911       // and we can set the the frame dimensions accordingly.
3912     }
3913     // allowing for unresizable option using, style="resize:none"
3914     boolean resizable = (Platform.getEmbeddedAttribute(frame,
3915             "resize") != "none");
3916     Desktop.addInternalFrame(frame, MessageManager
3917             .formatMessage("label.overview_params", new Object[]
3918             { this.getTitle() }), Desktop.FRAME_MAKE_VISIBLE, dim.width,
3919             dim.height, resizable, Desktop.FRAME_ALLOW_ANY_SIZE);
3920     frame.pack();
3921     frame.setLayer(JLayeredPane.PALETTE_LAYER);
3922     frame.addInternalFrameListener(
3923             new javax.swing.event.InternalFrameAdapter()
3924             {
3925               @Override
3926               public void internalFrameClosed(
3927                       javax.swing.event.InternalFrameEvent evt)
3928               {
3929                 overview.dispose();
3930                 alignPanel.setOverviewPanel(null);
3931               }
3932             });
3933     if (getKeyListeners().length > 0)
3934     {
3935       frame.addKeyListener(getKeyListeners()[0]);
3936     }
3937
3938     alignPanel.setOverviewPanel(overview);
3939   }
3940
3941   @Override
3942   public void textColour_actionPerformed()
3943   {
3944     new TextColourChooser().chooseColour(alignPanel, null);
3945   }
3946
3947   /*
3948    * public void covariationColour_actionPerformed() {
3949    * changeColour(new
3950    * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3951    * ()[0])); }
3952    */
3953   @Override
3954   public void annotationColour_actionPerformed()
3955   {
3956     new AnnotationColourChooser(viewport, alignPanel);
3957   }
3958
3959   @Override
3960   public void annotationColumn_actionPerformed(ActionEvent e)
3961   {
3962     new AnnotationColumnChooser(viewport, alignPanel);
3963   }
3964
3965   /**
3966    * Action on the user checking or unchecking the option to apply the selected
3967    * colour scheme to all groups. If unchecked, groups may have their own
3968    * independent colour schemes.
3969    * 
3970    * @param selected
3971    */
3972   @Override
3973   public void applyToAllGroups_actionPerformed(boolean selected)
3974   {
3975     viewport.setColourAppliesToAllGroups(selected);
3976   }
3977
3978   /**
3979    * Action on user selecting a colour from the colour menu
3980    * 
3981    * @param name
3982    *          the name (not the menu item label!) of the colour scheme
3983    */
3984   @Override
3985   public void changeColour_actionPerformed(String name)
3986   {
3987     /*
3988      * 'User Defined' opens a panel to configure or load a
3989      * user-defined colour scheme
3990      */
3991     if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3992     {
3993       new UserDefinedColours(alignPanel);
3994       return;
3995     }
3996
3997     /*
3998      * otherwise set the chosen colour scheme (or null for 'None')
3999      */
4000     ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
4001             viewport, viewport.getAlignment(),
4002             viewport.getHiddenRepSequences());
4003     changeColour(cs);
4004   }
4005
4006   /**
4007    * Actions on setting or changing the alignment colour scheme
4008    * 
4009    * @param cs
4010    */
4011   @Override
4012   public void changeColour(ColourSchemeI cs)
4013   {
4014     // TODO: pull up to controller method
4015     ColourMenuHelper.setColourSelected(colourMenu, cs);
4016
4017     viewport.setGlobalColourScheme(cs);
4018
4019     alignPanel.paintAlignment(true, true);
4020   }
4021
4022   /**
4023    * Show the PID threshold slider panel
4024    */
4025   @Override
4026   protected void modifyPID_actionPerformed()
4027   {
4028     SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
4029             alignPanel.getViewName());
4030     SliderPanel.showPIDSlider();
4031   }
4032
4033   /**
4034    * Show the Conservation slider panel
4035    */
4036   @Override
4037   protected void modifyConservation_actionPerformed()
4038   {
4039     SliderPanel.setConservationSlider(alignPanel,
4040             viewport.getResidueShading(), alignPanel.getViewName());
4041     SliderPanel.showConservationSlider();
4042   }
4043
4044   /**
4045    * Action on selecting or deselecting (Colour) By Conservation
4046    */
4047   @Override
4048   public void conservationMenuItem_actionPerformed(boolean selected)
4049   {
4050     modifyConservation.setEnabled(selected);
4051     viewport.setConservationSelected(selected);
4052     viewport.getResidueShading().setConservationApplied(selected);
4053
4054     changeColour(viewport.getGlobalColourScheme());
4055     if (selected)
4056     {
4057       modifyConservation_actionPerformed();
4058     }
4059     else
4060     {
4061       SliderPanel.hideConservationSlider();
4062     }
4063   }
4064
4065   /**
4066    * Action on selecting or deselecting (Colour) Above PID Threshold
4067    */
4068   @Override
4069   public void abovePIDThreshold_actionPerformed(boolean selected)
4070   {
4071     modifyPID.setEnabled(selected);
4072     viewport.setAbovePIDThreshold(selected);
4073     if (!selected)
4074     {
4075       viewport.getResidueShading().setThreshold(0,
4076               viewport.isIgnoreGapsConsensus());
4077     }
4078
4079     changeColour(viewport.getGlobalColourScheme());
4080     if (selected)
4081     {
4082       modifyPID_actionPerformed();
4083     }
4084     else
4085     {
4086       SliderPanel.hidePIDSlider();
4087     }
4088   }
4089
4090   /**
4091    * DOCUMENT ME!
4092    * 
4093    * @param e
4094    *          DOCUMENT ME!
4095    */
4096   @Override
4097   public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
4098   {
4099     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4100     AlignmentSorter.sortByPID(viewport.getAlignment(),
4101             viewport.getAlignment().getSequenceAt(0));
4102     addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
4103             viewport.getAlignment()));
4104     alignPanel.paintAlignment(true, false);
4105   }
4106
4107   /**
4108    * DOCUMENT ME!
4109    * 
4110    * @param e
4111    *          DOCUMENT ME!
4112    */
4113   @Override
4114   public void sortIDMenuItem_actionPerformed(ActionEvent e)
4115   {
4116     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4117     AlignmentSorter.sortByID(viewport.getAlignment());
4118     addHistoryItem(
4119             new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
4120     alignPanel.paintAlignment(true, false);
4121   }
4122
4123   /**
4124    * DOCUMENT ME!
4125    * 
4126    * @param e
4127    *          DOCUMENT ME!
4128    */
4129   @Override
4130   public void sortLengthMenuItem_actionPerformed(ActionEvent e)
4131   {
4132     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4133     AlignmentSorter.sortByLength(viewport.getAlignment());
4134     addHistoryItem(new OrderCommand("Length Sort", oldOrder,
4135             viewport.getAlignment()));
4136     alignPanel.paintAlignment(true, false);
4137   }
4138
4139   /**
4140    * DOCUMENT ME!
4141    * 
4142    * @param e
4143    *          DOCUMENT ME!
4144    */
4145   @Override
4146   public void sortGroupMenuItem_actionPerformed(ActionEvent e)
4147   {
4148     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4149     AlignmentSorter.sortByGroup(viewport.getAlignment());
4150     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4151             viewport.getAlignment()));
4152
4153     alignPanel.paintAlignment(true, false);
4154   }
4155
4156   @Override
4157   public void sortEValueMenuItem_actionPerformed(ActionEvent e)
4158   {
4159     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4160     AlignmentSorter.sortByEValue(viewport.getAlignment());
4161     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4162             viewport.getAlignment()));
4163     alignPanel.paintAlignment(true, false);
4164
4165   }
4166
4167   @Override
4168   public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
4169   {
4170     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4171     AlignmentSorter.sortByBitScore(viewport.getAlignment());
4172     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4173             viewport.getAlignment()));
4174     alignPanel.paintAlignment(true, false);
4175
4176   }
4177   /**
4178    * DOCUMENT ME!
4179    * 
4180    * @param e
4181    *          DOCUMENT ME!
4182    */
4183   @Override
4184   public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
4185   {
4186     new RedundancyPanel(alignPanel, this);
4187   }
4188
4189   /**
4190    * DOCUMENT ME!
4191    * 
4192    * @param e
4193    *          DOCUMENT ME!
4194    */
4195   @Override
4196   public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
4197   {
4198     if ((viewport.getSelectionGroup() == null)
4199             || (viewport.getSelectionGroup().getSize() < 2))
4200     {
4201       JvOptionPane.showInternalMessageDialog(this,
4202               MessageManager.getString(
4203                       "label.you_must_select_least_two_sequences"),
4204               MessageManager.getString("label.invalid_selection"),
4205               JvOptionPane.WARNING_MESSAGE);
4206     }
4207     else
4208     {
4209       JInternalFrame frame = new JInternalFrame();
4210       frame.setContentPane(new PairwiseAlignPanel(viewport));
4211       Desktop.addInternalFrame(frame,
4212               MessageManager.getString("action.pairwise_alignment"), 600,
4213               500);
4214     }
4215   }
4216
4217   @Override
4218   public void autoCalculate_actionPerformed(ActionEvent e)
4219   {
4220     viewport.setAutoCalculateConsensusAndConservation(
4221             autoCalculate.isSelected());
4222     if (viewport.getAutoCalculateConsensusAndConservation())
4223     {
4224       viewport.notifyAlignment();
4225     }
4226   }
4227
4228   @Override
4229   public void sortByTreeOption_actionPerformed(ActionEvent e)
4230   {
4231     viewport.sortByTree = sortByTree.isSelected();
4232   }
4233
4234   @Override
4235   protected void listenToViewSelections_actionPerformed(ActionEvent e)
4236   {
4237     viewport.followSelection = listenToViewSelections.isSelected();
4238   }
4239
4240   /**
4241    * Constructs a tree panel and adds it to the desktop
4242    * 
4243    * @param type
4244    *          tree type (NJ or AV)
4245    * @param modelName
4246    *          name of score model used to compute the tree
4247    * @param options
4248    *          parameters for the distance or similarity calculation
4249    */
4250   void newTreePanel(String type, String modelName,
4251           SimilarityParamsI options)
4252   {
4253     String frameTitle = "";
4254     TreePanel tp;
4255
4256     boolean onSelection = false;
4257     if (viewport.getSelectionGroup() != null
4258             && viewport.getSelectionGroup().getSize() > 0)
4259     {
4260       SequenceGroup sg = viewport.getSelectionGroup();
4261
4262       /* Decide if the selection is a column region */
4263       for (SequenceI _s : sg.getSequences())
4264       {
4265         if (_s.getLength() < sg.getEndRes())
4266         {
4267           JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4268                   MessageManager.getString(
4269                           "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4270                   MessageManager.getString(
4271                           "label.sequences_selection_not_aligned"),
4272                   JvOptionPane.WARNING_MESSAGE);
4273
4274           return;
4275         }
4276       }
4277       onSelection = true;
4278     }
4279     else
4280     {
4281       if (viewport.getAlignment().getHeight() < 2)
4282       {
4283         return;
4284       }
4285     }
4286
4287     tp = new TreePanel(alignPanel, type, modelName, options);
4288     frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
4289
4290     frameTitle += " from ";
4291
4292     if (viewport.getViewName() != null)
4293     {
4294       frameTitle += viewport.getViewName() + " of ";
4295     }
4296
4297     frameTitle += this.title;
4298
4299     Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
4300     Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
4301   }
4302
4303   /**
4304    * DOCUMENT ME!
4305    * 
4306    * @param title
4307    *          DOCUMENT ME!
4308    * @param order
4309    *          DOCUMENT ME!
4310    */
4311   public void addSortByOrderMenuItem(String title,
4312           final AlignmentOrder order)
4313   {
4314     final JMenuItem item = new JMenuItem(MessageManager
4315             .formatMessage("action.by_title_param", new Object[]
4316             { title }));
4317     sort.add(item);
4318     item.addActionListener(new java.awt.event.ActionListener()
4319     {
4320       @Override
4321       public void actionPerformed(ActionEvent e)
4322       {
4323         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4324
4325         // TODO: JBPNote - have to map order entries to curent SequenceI
4326         // pointers
4327         AlignmentSorter.sortBy(viewport.getAlignment(), order);
4328
4329         addHistoryItem(new OrderCommand(order.getName(), oldOrder,
4330                 viewport.getAlignment()));
4331
4332         alignPanel.paintAlignment(true, false);
4333       }
4334     });
4335   }
4336
4337   /**
4338    * Add a new sort by annotation score menu item
4339    * 
4340    * @param sort
4341    *          the menu to add the option to
4342    * @param scoreLabel
4343    *          the label used to retrieve scores for each sequence on the
4344    *          alignment
4345    */
4346   public void addSortByAnnotScoreMenuItem(JMenu sort,
4347           final String scoreLabel)
4348   {
4349     final JMenuItem item = new JMenuItem(scoreLabel);
4350     sort.add(item);
4351     item.addActionListener(new java.awt.event.ActionListener()
4352     {
4353       @Override
4354       public void actionPerformed(ActionEvent e)
4355       {
4356         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4357         AlignmentSorter.sortByAnnotationScore(scoreLabel,
4358                 viewport.getAlignment());// ,viewport.getSelectionGroup());
4359         addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4360                 viewport.getAlignment()));
4361         alignPanel.paintAlignment(true, false);
4362       }
4363     });
4364   }
4365
4366   /**
4367    * last hash for alignment's annotation array - used to minimise cost of
4368    * rebuild.
4369    */
4370   protected int _annotationScoreVectorHash;
4371
4372   /**
4373    * search the alignment and rebuild the sort by annotation score submenu the
4374    * last alignment annotation vector hash is stored to minimize cost of
4375    * rebuilding in subsequence calls.
4376    * 
4377    */
4378   @Override
4379   public void buildSortByAnnotationScoresMenu()
4380   {
4381     if (viewport.getAlignment().getAlignmentAnnotation() == null)
4382     {
4383       return;
4384     }
4385
4386     if (viewport.getAlignment().getAlignmentAnnotation()
4387             .hashCode() == _annotationScoreVectorHash)
4388     {
4389       return;
4390     }
4391
4392     sortByAnnotScore.removeAll();
4393     Set<String> scoreSorts = new HashSet<>();
4394     for (SequenceI sqa : viewport.getAlignment().getSequences())
4395     {
4396       AlignmentAnnotation[] anns = sqa.getAnnotation();
4397       for (int i = 0; anns != null && i < anns.length; i++)
4398       {
4399         AlignmentAnnotation aa = anns[i];
4400         if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4401         {
4402           scoreSorts.add(aa.label);
4403         }
4404       }
4405     }
4406     for (String label : scoreSorts)
4407     {
4408       addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4409     }
4410     sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4411
4412     _annotationScoreVectorHash = viewport.getAlignment()
4413             .getAlignmentAnnotation().hashCode();
4414   }
4415
4416   /**
4417    * Enable (or, if desired, make visible) the By Tree 
4418    * submenu only if it has at least one element (or will have).
4419    * 
4420    */
4421   @Override
4422   protected void enableSortMenuOptions()
4423   {
4424     List<TreePanel> treePanels = getTreePanels();
4425     sortByTreeMenu.setEnabled(!treePanels.isEmpty());
4426   }
4427   
4428   /**
4429    * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4430    * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4431    * call. Listeners are added to remove the menu item when the treePanel is
4432    * closed, and adjust the tree leaf to sequence mapping when the alignment is
4433    * modified.
4434    */
4435   @Override
4436   public void buildTreeSortMenu()
4437   {
4438     sortByTreeMenu.removeAll();
4439
4440     List<TreePanel> treePanels = getTreePanels();
4441
4442     for (final TreePanel tp : treePanels)
4443     {
4444       final JMenuItem item = new JMenuItem(tp.getTitle());
4445       item.addActionListener(new java.awt.event.ActionListener()
4446       {
4447         @Override
4448         public void actionPerformed(ActionEvent e)
4449         {
4450           tp.sortByTree_actionPerformed();
4451           addHistoryItem(tp.sortAlignmentIn(alignPanel));
4452
4453         }
4454       });
4455
4456       sortByTreeMenu.add(item);
4457     }
4458   }
4459
4460   private List<TreePanel> getTreePanels()
4461   {
4462     List<Component> comps = PaintRefresher.components
4463             .get(viewport.getSequenceSetId());
4464     List<TreePanel> treePanels = new ArrayList<>();
4465     for (Component comp : comps)
4466     {
4467       if (comp instanceof TreePanel)
4468       {
4469         treePanels.add((TreePanel) comp);
4470       }
4471     }
4472     return treePanels;
4473   }
4474   public boolean sortBy(AlignmentOrder alorder, String undoname)
4475   {
4476     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4477     AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4478     if (undoname != null)
4479     {
4480       addHistoryItem(new OrderCommand(undoname, oldOrder,
4481               viewport.getAlignment()));
4482     }
4483     alignPanel.paintAlignment(true, false);
4484     return true;
4485   }
4486
4487   /**
4488    * Work out whether the whole set of sequences or just the selected set will
4489    * be submitted for multiple alignment.
4490    * 
4491    */
4492   public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4493   {
4494     // Now, check we have enough sequences
4495     AlignmentView msa = null;
4496
4497     if ((viewport.getSelectionGroup() != null)
4498             && (viewport.getSelectionGroup().getSize() > 1))
4499     {
4500       // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4501       // some common interface!
4502       /*
4503        * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4504        * SequenceI[sz = seqs.getSize(false)];
4505        * 
4506        * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4507        * seqs.getSequenceAt(i); }
4508        */
4509       msa = viewport.getAlignmentView(true);
4510     }
4511     else if (viewport.getSelectionGroup() != null
4512             && viewport.getSelectionGroup().getSize() == 1)
4513     {
4514       int option = JvOptionPane.showConfirmDialog(this,
4515               MessageManager.getString("warn.oneseq_msainput_selection"),
4516               MessageManager.getString("label.invalid_selection"),
4517               JvOptionPane.OK_CANCEL_OPTION);
4518       if (option == JvOptionPane.OK_OPTION)
4519       {
4520         msa = viewport.getAlignmentView(false);
4521       }
4522     }
4523     else
4524     {
4525       msa = viewport.getAlignmentView(false);
4526     }
4527     return msa;
4528   }
4529
4530   /**
4531    * Decides what is submitted to a secondary structure prediction service: the
4532    * first sequence in the alignment, or in the current selection, or, if the
4533    * alignment is 'aligned' (ie padded with gaps), then the currently selected
4534    * region or the whole alignment. (where the first sequence in the set is the
4535    * one that the prediction will be for).
4536    */
4537   public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4538   {
4539     AlignmentView seqs = null;
4540
4541     if ((viewport.getSelectionGroup() != null)
4542             && (viewport.getSelectionGroup().getSize() > 0))
4543     {
4544       seqs = viewport.getAlignmentView(true);
4545     }
4546     else
4547     {
4548       seqs = viewport.getAlignmentView(false);
4549     }
4550     // limit sequences - JBPNote in future - could spawn multiple prediction
4551     // jobs
4552     // TODO: viewport.getAlignment().isAligned is a global state - the local
4553     // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4554     if (!viewport.getAlignment().isAligned(false))
4555     {
4556       seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4557       // TODO: if seqs.getSequences().length>1 then should really have warned
4558       // user!
4559
4560     }
4561     return seqs;
4562   }
4563
4564   /**
4565    * DOCUMENT ME!
4566    * 
4567    * @param e
4568    *          DOCUMENT ME!
4569    */
4570   @Override
4571   protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4572   {
4573     // Pick the tree file
4574     JalviewFileChooser chooser = new JalviewFileChooser(
4575             Cache.getProperty("LAST_DIRECTORY"));
4576     chooser.setFileView(new JalviewFileView());
4577     chooser.setDialogTitle(
4578             MessageManager.getString("label.select_newick_like_tree_file"));
4579     chooser.setToolTipText(
4580             MessageManager.getString("label.load_tree_file"));
4581
4582     chooser.setResponseHandler(0, new Runnable()
4583     {
4584       @Override
4585       public void run()
4586       {
4587         String filePath = chooser.getSelectedFile().getPath();
4588         Cache.setProperty("LAST_DIRECTORY", filePath);
4589         NewickFile fin = null;
4590         try
4591         {
4592           fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4593                   DataSourceType.FILE));
4594           viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4595         } catch (Exception ex)
4596         {
4597           JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4598                   ex.getMessage(),
4599                   MessageManager
4600                           .getString("label.problem_reading_tree_file"),
4601                   JvOptionPane.WARNING_MESSAGE);
4602           ex.printStackTrace();
4603         }
4604         if (fin != null && fin.hasWarningMessage())
4605         {
4606           JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4607                   fin.getWarningMessage(),
4608                   MessageManager.getString(
4609                           "label.possible_problem_with_tree_file"),
4610                   JvOptionPane.WARNING_MESSAGE);
4611         }
4612       }
4613     });
4614     chooser.showOpenDialog(this);
4615   }
4616
4617   public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4618   {
4619     return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4620   }
4621
4622   public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4623           int h, int x, int y)
4624   {
4625     return showNewickTree(nf, treeTitle, null, w, h, x, y);
4626   }
4627
4628   /**
4629    * Add a treeviewer for the tree extracted from a Newick file object to the
4630    * current alignment view
4631    * 
4632    * @param nf
4633    *          the tree
4634    * @param title
4635    *          tree viewer title
4636    * @param input
4637    *          Associated alignment input data (or null)
4638    * @param w
4639    *          width
4640    * @param h
4641    *          height
4642    * @param x
4643    *          position
4644    * @param y
4645    *          position
4646    * @return TreePanel handle
4647    */
4648   public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4649           AlignmentView input, int w, int h, int x, int y)
4650   {
4651     TreePanel tp = null;
4652
4653     try
4654     {
4655       nf.parse();
4656
4657       if (nf.getTree() != null)
4658       {
4659         tp = new TreePanel(alignPanel, nf, treeTitle, input);
4660
4661         Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4662         if (dim == null)
4663         {
4664           dim = new Dimension(w, h);
4665         }
4666         else
4667         {
4668           // no offset, either
4669           x = 0;
4670         }
4671         tp.setSize(dim.width, dim.height);
4672
4673         if (x > 0 && y > 0)
4674         {
4675           tp.setLocation(x, y);
4676         }
4677
4678         Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4679       }
4680     } catch (Exception ex)
4681     {
4682       ex.printStackTrace();
4683     }
4684
4685     return tp;
4686   }
4687
4688   private WebServicesMenuManager slivkaMenu = new WebServicesMenuManager("slivka", this);
4689   private WebServicesMenuManager ebiMenu = new WebServicesMenuManager("job dispatcher", this);
4690   private WebServicesMenuManager jpred4Menu = new WebServicesMenuManager("jpred4", this);
4691
4692   /**
4693    * Schedule the web services menu rebuild to the event dispatch thread.
4694    */
4695   public void buildWebServicesMenu()
4696   {
4697     SwingUtilities.invokeLater(() -> {
4698       Console.info("Rebuiling WS menu");
4699       webService.removeAll();
4700       if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
4701       {
4702         Console.info("Building web service menu for slivka");
4703         SlivkaWSDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
4704         slivkaMenu.setServices(discoverer);
4705         slivkaMenu.setInProgress(discoverer.isRunning());
4706         slivkaMenu.setNoServices(discoverer.isDone() && !discoverer.hasServices());
4707         webService.add(slivkaMenu.getMenu());
4708       }
4709       if (Cache.getDefault("SHOW_EBI_SERVICES", true))
4710       {
4711         Console.info("Building web services menu for jobs dispatcher");
4712         JobDispatcherWSDiscoverer discoverer = JobDispatcherWSDiscoverer.getInstance();
4713         ebiMenu.setServices(discoverer);
4714         ebiMenu.setInProgress(discoverer.isRunning());
4715         ebiMenu.setNoServices(discoverer.isDone() && !discoverer.hasServices());
4716         webService.add(ebiMenu.getMenu());
4717       }
4718       if (Cache.getDefault("SHOW_JPRED4_SERVICES", true))
4719       {
4720         Console.info("Building web services menu for jpred4");
4721         JPred4WSDiscoverer discoverer = JPred4WSDiscoverer.getInstance();
4722         jpred4Menu.setServices(discoverer);
4723         jpred4Menu.setInProgress(discoverer.isRunning());
4724         jpred4Menu.setNoServices(discoverer.isDone() && !discoverer.hasServices());
4725         webService.add(jpred4Menu.getMenu());
4726       }
4727       if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4728       {
4729         WSDiscovererI jws2servs = Jws2Discoverer.getInstance();
4730         JMenu submenu = new JMenu("JABAWS");
4731         buildLegacyWebServicesMenu(submenu);
4732         buildWebServicesMenu(jws2servs, submenu);
4733         webService.add(submenu);
4734       }
4735       build_urlServiceMenu(webService);
4736       build_fetchdbmenu(webService);
4737     });
4738   }
4739
4740   private void buildLegacyWebServicesMenu(JMenu menu)
4741   {
4742     JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
4743     if (Discoverer.getServices() != null && Discoverer.getServices().size() > 0) 
4744     {
4745       var secstrpred = Discoverer.getServices().get("SecStrPred");
4746       if (secstrpred != null) 
4747       {
4748         for (ext.vamsas.ServiceHandle sh : secstrpred) 
4749         {
4750           var menuProvider = Discoverer.getServiceClient(sh);
4751           menuProvider.attachWSMenuEntry(secstrmenu, this);
4752         }
4753       }
4754     }
4755     menu.add(secstrmenu);
4756   }
4757
4758   /**
4759    * Constructs the web services menu for the given discoverer under the
4760    * specified menu. This method must be called on the EDT
4761    * 
4762    * @param discoverer
4763    *          the discoverer used to build the menu
4764    * @param menu
4765    *          parent component which the elements will be attached to
4766    */
4767   private void buildWebServicesMenu(WSDiscovererI discoverer, JMenu menu)
4768   {
4769     if (discoverer.hasServices())
4770     {
4771       PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
4772               discoverer.getServices(), sv -> buildWebServicesMenu(), menu,
4773               this, null);
4774     }
4775     if (discoverer.isRunning())
4776     {
4777       JMenuItem item = new JMenuItem("Service discovery in progress.");
4778       item.setEnabled(false);
4779       menu.add(item);
4780     }
4781     else if (!discoverer.hasServices())
4782     {
4783       JMenuItem item = new JMenuItem("No services available.");
4784       item.setEnabled(false);
4785       menu.add(item);
4786     }
4787   }
4788
4789   /**
4790    * construct any groupURL type service menu entries.
4791    * 
4792    * @param webService
4793    */
4794   protected void build_urlServiceMenu(JMenu webService)
4795   {
4796     // TODO: remove this code when 2.7 is released
4797     // DEBUG - alignmentView
4798     /*
4799      * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4800      * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4801      * 
4802      *  public void actionPerformed(ActionEvent e) {
4803      * jalview.datamodel.AlignmentView
4804      * .testSelectionViews(af.viewport.getAlignment(),
4805      * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4806      * 
4807      * }); webService.add(testAlView);
4808      */
4809     // TODO: refactor to RestClient discoverer and merge menu entries for
4810     // rest-style services with other types of analysis/calculation service
4811     // SHmmr test client - still being implemented.
4812     // DEBUG - alignmentView
4813
4814     for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4815             .getRestClients())
4816     {
4817       client.attachWSMenuEntry(
4818               JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4819               this);
4820     }
4821   }
4822
4823   /**
4824    * Searches the alignment sequences for xRefs and builds the Show
4825    * Cross-References menu (formerly called Show Products), with database
4826    * sources for which cross-references are found (protein sources for a
4827    * nucleotide alignment and vice versa)
4828    * 
4829    * @return true if Show Cross-references menu should be enabled
4830    */
4831   public boolean canShowProducts()
4832   {
4833     SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4834     AlignmentI dataset = viewport.getAlignment().getDataset();
4835
4836     showProducts.removeAll();
4837     final boolean dna = viewport.getAlignment().isNucleotide();
4838
4839     if (seqs == null || seqs.length == 0)
4840     {
4841       // nothing to see here.
4842       return false;
4843     }
4844
4845     boolean showp = false;
4846     try
4847     {
4848       List<String> ptypes = new CrossRef(seqs, dataset)
4849               .findXrefSourcesForSequences(dna);
4850
4851       for (final String source : ptypes)
4852       {
4853         showp = true;
4854         final AlignFrame af = this;
4855         JMenuItem xtype = new JMenuItem(source);
4856         xtype.addActionListener(new ActionListener()
4857         {
4858           @Override
4859           public void actionPerformed(ActionEvent e)
4860           {
4861             showProductsFor(af.viewport.getSequenceSelection(), dna,
4862                     source);
4863           }
4864         });
4865         showProducts.add(xtype);
4866       }
4867       showProducts.setVisible(showp);
4868       showProducts.setEnabled(showp);
4869     } catch (Exception e)
4870     {
4871       Console.warn(
4872               "canShowProducts threw an exception - please report to help@jalview.org",
4873               e);
4874       return false;
4875     }
4876     return showp;
4877   }
4878
4879   /**
4880    * Finds and displays cross-references for the selected sequences (protein
4881    * products for nucleotide sequences, dna coding sequences for peptides).
4882    * 
4883    * @param sel
4884    *          the sequences to show cross-references for
4885    * @param dna
4886    *          true if from a nucleotide alignment (so showing proteins)
4887    * @param source
4888    *          the database to show cross-references for
4889    */
4890   protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4891           final String source)
4892   {
4893     new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4894             .start();
4895   }
4896
4897   /**
4898    * Construct and display a new frame containing the translation of this
4899    * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4900    */
4901   @Override
4902   public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4903   {
4904     AlignmentI al = null;
4905     try
4906     {
4907       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4908
4909       al = dna.translateCdna(codeTable);
4910     } catch (Exception ex)
4911     {
4912       Console.error("Exception during translation. Please report this !",
4913               ex);
4914       final String msg = MessageManager.getString(
4915               "label.error_when_translating_sequences_submit_bug_report");
4916       final String errorTitle = MessageManager
4917               .getString("label.implementation_error")
4918               + MessageManager.getString("label.translation_failed");
4919       JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4920               errorTitle, JvOptionPane.ERROR_MESSAGE);
4921       return;
4922     }
4923     if (al == null || al.getHeight() == 0)
4924     {
4925       final String msg = MessageManager.getString(
4926               "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4927       final String errorTitle = MessageManager
4928               .getString("label.translation_failed");
4929       JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4930               errorTitle, JvOptionPane.WARNING_MESSAGE);
4931     }
4932     else
4933     {
4934       AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4935       af.setFileFormat(this.currentFileFormat);
4936       final String newTitle = MessageManager
4937               .formatMessage("label.translation_of_params", new Object[]
4938               { this.getTitle(), codeTable.getId() });
4939       af.setTitle(newTitle);
4940       if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4941       {
4942         final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4943         AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4944       }
4945       else
4946       {
4947         Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4948                 DEFAULT_HEIGHT);
4949       }
4950     }
4951   }
4952
4953   /**
4954    * Set the file format
4955    * 
4956    * @param format
4957    */
4958   public void setFileFormat(FileFormatI format)
4959   {
4960     this.currentFileFormat = format;
4961   }
4962
4963   /**
4964    * Try to load a features file onto the alignment.
4965    * 
4966    * @param file
4967    *          contents or path to retrieve file or a File object
4968    * @param sourceType
4969    *          access mode of file (see jalview.io.AlignFile)
4970    * @return true if features file was parsed correctly.
4971    */
4972   public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4973   {
4974     // BH 2018
4975     return avc.parseFeaturesFile(file, sourceType,
4976             Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4977
4978   }
4979
4980   @Override
4981   public void refreshFeatureUI(boolean enableIfNecessary)
4982   {
4983     // note - currently this is only still here rather than in the controller
4984     // because of the featureSettings hard reference that is yet to be
4985     // abstracted
4986     if (enableIfNecessary)
4987     {
4988       viewport.setShowSequenceFeatures(true);
4989       showSeqFeatures.setSelected(true);
4990     }
4991
4992   }
4993
4994   @Override
4995   public void dragEnter(DropTargetDragEvent evt)
4996   {
4997   }
4998
4999   @Override
5000   public void dragExit(DropTargetEvent evt)
5001   {
5002   }
5003
5004   @Override
5005   public void dragOver(DropTargetDragEvent evt)
5006   {
5007   }
5008
5009   @Override
5010   public void dropActionChanged(DropTargetDragEvent evt)
5011   {
5012   }
5013
5014   @Override
5015   public void drop(DropTargetDropEvent evt)
5016   {
5017     // JAL-1552 - acceptDrop required before getTransferable call for
5018     // Java's Transferable for native dnd
5019     evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5020     Transferable t = evt.getTransferable();
5021
5022     final List<Object> files = new ArrayList<>();
5023     List<DataSourceType> protocols = new ArrayList<>();
5024
5025     try
5026     {
5027       Desktop.transferFromDropTarget(files, protocols, evt, t);
5028       if (files.size() > 0)
5029       {
5030         new Thread(new Runnable()
5031         {
5032
5033           @Override
5034           public void run()
5035           {
5036             loadDroppedFiles(files, protocols, evt, t);
5037           }
5038         }).start();
5039       }
5040     } catch (Exception e)
5041     {
5042       e.printStackTrace();
5043     }
5044   }
5045
5046   protected void loadDroppedFiles(List<Object> files,
5047           List<DataSourceType> protocols, DropTargetDropEvent evt,
5048           Transferable t)
5049   {
5050     try
5051     {
5052       // check to see if any of these files have names matching sequences
5053       // in
5054       // the alignment
5055       SequenceIdMatcher idm = new SequenceIdMatcher(
5056               viewport.getAlignment().getSequencesArray());
5057       /**
5058        * Object[] { String,SequenceI}
5059        */
5060       ArrayList<Object[]> filesmatched = new ArrayList<>();
5061       ArrayList<Object> filesnotmatched = new ArrayList<>();
5062       for (int i = 0; i < files.size(); i++)
5063       {
5064         // BH 2018
5065         Object fileObj = files.get(i);
5066         String fileName = fileObj.toString();
5067         String pdbfn = "";
5068         DataSourceType protocol = (fileObj instanceof File
5069                 ? DataSourceType.FILE
5070                 : FormatAdapter.checkProtocol(fileName));
5071         if (protocol == DataSourceType.FILE)
5072         {
5073           File file;
5074           if (fileObj instanceof File)
5075           {
5076             file = (File) fileObj;
5077             Platform.cacheFileData(file);
5078           }
5079           else
5080           {
5081             file = new File(fileName);
5082           }
5083           pdbfn = file.getName();
5084         }
5085         else if (protocol == DataSourceType.URL)
5086         {
5087           URL url = new URL(fileName);
5088           pdbfn = url.getFile();
5089         }
5090         if (pdbfn.length() > 0)
5091         {
5092           // attempt to find a match in the alignment
5093           SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5094           int l = 0, c = pdbfn.indexOf(".");
5095           while (mtch == null && c != -1)
5096           {
5097             do
5098             {
5099               l = c;
5100             } while ((c = pdbfn.indexOf(".", l)) > l);
5101             if (l > -1)
5102             {
5103               pdbfn = pdbfn.substring(0, l);
5104             }
5105             mtch = idm.findAllIdMatches(pdbfn);
5106           }
5107           if (mtch != null)
5108           {
5109             FileFormatI type;
5110             try
5111             {
5112               type = new IdentifyFile().identify(fileObj, protocol);
5113             } catch (Exception ex)
5114             {
5115               type = null;
5116             }
5117             if (type != null && type.isStructureFile())
5118             {
5119               filesmatched.add(new Object[] { fileObj, protocol, mtch });
5120               continue;
5121             }
5122           }
5123           // File wasn't named like one of the sequences or wasn't a PDB
5124           // file.
5125           filesnotmatched.add(fileObj);
5126         }
5127       }
5128       int assocfiles = 0;
5129       if (filesmatched.size() > 0)
5130       {
5131         boolean autoAssociate = Cache
5132                 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
5133         if (!autoAssociate)
5134         {
5135           String msg = MessageManager.formatMessage(
5136                   "label.automatically_associate_structure_files_with_sequences_same_name",
5137                   new Object[]
5138                   { Integer.valueOf(filesmatched.size()).toString() });
5139           String ttl = MessageManager.getString(
5140                   "label.automatically_associate_structure_files_by_name");
5141           int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
5142                   JvOptionPane.YES_NO_OPTION);
5143           autoAssociate = choice == JvOptionPane.YES_OPTION;
5144         }
5145         if (autoAssociate)
5146         {
5147           for (Object[] fm : filesmatched)
5148           {
5149             // try and associate
5150             // TODO: may want to set a standard ID naming formalism for
5151             // associating PDB files which have no IDs.
5152             for (SequenceI toassoc : (SequenceI[]) fm[2])
5153             {
5154               PDBEntry pe = AssociatePdbFileWithSeq.associatePdbWithSeq(
5155                       fm[0].toString(), (DataSourceType) fm[1], toassoc,
5156                       false);
5157               if (pe != null)
5158               {
5159                 System.err.println("Associated file : " + (fm[0].toString())
5160                         + " with " + toassoc.getDisplayId(true));
5161                 assocfiles++;
5162               }
5163
5164             }
5165             // TODO: do we need to update overview ? only if features are
5166             // shown I guess
5167             alignPanel.paintAlignment(true, false);
5168           }
5169         }
5170         else
5171         {
5172           /*
5173            * add declined structures as sequences
5174            */
5175           for (Object[] o : filesmatched)
5176           {
5177             filesnotmatched.add(o[0]);
5178           }
5179         }
5180       }
5181       if (filesnotmatched.size() > 0)
5182       {
5183         if (assocfiles > 0 && (Cache
5184                 .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
5185                 || JvOptionPane.showConfirmDialog(this,
5186                         "<html>" + MessageManager.formatMessage(
5187                                 "label.ignore_unmatched_dropped_files_info",
5188                                 new Object[]
5189                                 { Integer.valueOf(filesnotmatched.size())
5190                                         .toString() })
5191                                 + "</html>",
5192                         MessageManager.getString(
5193                                 "label.ignore_unmatched_dropped_files"),
5194                         JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
5195         {
5196           return;
5197         }
5198         for (Object fn : filesnotmatched)
5199         {
5200           loadJalviewDataFile(fn, null, null, null);
5201         }
5202
5203       }
5204     } catch (Exception ex)
5205     {
5206       ex.printStackTrace();
5207     }
5208   }
5209
5210   /**
5211    * Attempt to load a "dropped" file or URL string, by testing in turn for
5212    * <ul>
5213    * <li>an Annotation file</li>
5214    * <li>a JNet file</li>
5215    * <li>a features file</li>
5216    * <li>else try to interpret as an alignment file</li>
5217    * </ul>
5218    * 
5219    * @param file
5220    *          either a filename or a URL string.
5221    * @throws InterruptedException
5222    * @throws IOException
5223    */
5224   public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5225           FileFormatI format, SequenceI assocSeq)
5226   {
5227     // BH 2018 was String file
5228     try
5229     {
5230       if (sourceType == null)
5231       {
5232         sourceType = FormatAdapter.checkProtocol(file);
5233       }
5234       // if the file isn't identified, or not positively identified as some
5235       // other filetype (PFAM is default unidentified alignment file type) then
5236       // try to parse as annotation.
5237       boolean isAnnotation = (format == null
5238               || FileFormat.Pfam.equals(format))
5239                       ? new AnnotationFile().annotateAlignmentView(viewport,
5240                               file, sourceType)
5241                       : false;
5242
5243       if (!isAnnotation)
5244       {
5245         // first see if its a T-COFFEE score file
5246         TCoffeeScoreFile tcf = null;
5247         try
5248         {
5249           tcf = new TCoffeeScoreFile(file, sourceType);
5250           if (tcf.isValid())
5251           {
5252             if (tcf.annotateAlignment(viewport.getAlignment(), true))
5253             {
5254               buildColourMenu();
5255               changeColour(
5256                       new TCoffeeColourScheme(viewport.getAlignment()));
5257               isAnnotation = true;
5258               setStatus(MessageManager.getString(
5259                       "label.successfully_pasted_tcoffee_scores_to_alignment"));
5260             }
5261             else
5262             {
5263               // some problem - if no warning its probable that the ID matching
5264               // process didn't work
5265               JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
5266                       tcf.getWarningMessage() == null
5267                               ? MessageManager.getString(
5268                                       "label.check_file_matches_sequence_ids_alignment")
5269                               : tcf.getWarningMessage(),
5270                       MessageManager.getString(
5271                               "label.problem_reading_tcoffee_score_file"),
5272                       JvOptionPane.WARNING_MESSAGE);
5273             }
5274           }
5275           else
5276           {
5277             tcf = null;
5278           }
5279         } catch (Exception x)
5280         {
5281           Console.debug(
5282                   "Exception when processing data source as T-COFFEE score file",
5283                   x);
5284           tcf = null;
5285         }
5286         if (tcf == null)
5287         {
5288           // try to see if its a JNet 'concise' style annotation file *before*
5289           // we
5290           // try to parse it as a features file
5291           if (format == null)
5292           {
5293             format = new IdentifyFile().identify(file, sourceType);
5294           }
5295           if (FileFormat.ScoreMatrix == format)
5296           {
5297             ScoreMatrixFile sm = new ScoreMatrixFile(
5298                     new FileParse(file, sourceType));
5299             sm.parse();
5300             // todo: i18n this message
5301             setStatus(MessageManager.formatMessage(
5302                     "label.successfully_loaded_matrix",
5303                     sm.getMatrixName()));
5304           }
5305           else if (FileFormat.Jnet.equals(format))
5306           {
5307             JPredFile predictions = new JPredFile(file, sourceType);
5308             new JnetAnnotationMaker();
5309             JnetAnnotationMaker.add_annotation(predictions,
5310                     viewport.getAlignment(), 0, false);
5311             viewport.getAlignment().setupJPredAlignment();
5312             isAnnotation = true;
5313           }
5314           // else if (IdentifyFile.FeaturesFile.equals(format))
5315           else if (FileFormat.Features.equals(format))
5316           {
5317             if (parseFeaturesFile(file, sourceType))
5318             {
5319               SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5320               if (splitFrame != null)
5321               {
5322                 splitFrame.repaint();
5323               }
5324               else
5325               {
5326                 alignPanel.paintAlignment(true, true);
5327               }
5328             }
5329           }
5330           else
5331           {
5332             new FileLoader().LoadFile(viewport, file, sourceType, format);
5333           }
5334         }
5335       }
5336       if (isAnnotation)
5337       {
5338
5339         updateForAnnotations();
5340       }
5341     } catch (Exception ex)
5342     {
5343       ex.printStackTrace();
5344     } catch (OutOfMemoryError oom)
5345     {
5346       try
5347       {
5348         System.gc();
5349       } catch (Exception x)
5350       {
5351       }
5352       new OOMWarning(
5353               "loading data "
5354                       + (sourceType != null
5355                               ? (sourceType == DataSourceType.PASTE
5356                                       ? "from clipboard."
5357                                       : "using " + sourceType + " from "
5358                                               + file)
5359                               : ".")
5360                       + (format != null
5361                               ? "(parsing as '" + format + "' file)"
5362                               : ""),
5363               oom, Desktop.getDesktopPane());
5364     }
5365   }
5366
5367   /**
5368    * Do all updates necessary after an annotation file such as jnet. Also called
5369    * from Jalview.loadAppletParams for "annotations", "jnetFile"
5370    */
5371
5372   public void updateForAnnotations()
5373   {
5374     alignPanel.adjustAnnotationHeight();
5375     viewport.updateSequenceIdColours();
5376     buildSortByAnnotationScoresMenu();
5377     alignPanel.paintAlignment(true, true);
5378   }
5379
5380   /**
5381    * Change the display state for the given feature groups -- Added by BH from
5382    * JalviewLite
5383    * 
5384    * @param groups
5385    *          list of group strings
5386    * @param state
5387    *          visible or invisible
5388    */
5389
5390   public void setFeatureGroupState(String[] groups, boolean state)
5391   {
5392     jalview.api.FeatureRenderer fr = null;
5393     viewport.setShowSequenceFeatures(true);
5394     if (alignPanel != null
5395             && (fr = alignPanel.getFeatureRenderer()) != null)
5396     {
5397
5398       fr.setGroupVisibility(Arrays.asList(groups), state);
5399       alignPanel.getSeqPanel().seqCanvas.repaint();
5400       if (alignPanel.overviewPanel != null)
5401       {
5402         alignPanel.overviewPanel.updateOverviewImage();
5403       }
5404     }
5405   }
5406
5407   /**
5408    * Method invoked by the ChangeListener on the tabbed pane, in other words
5409    * when a different tabbed pane is selected by the user or programmatically.
5410    */
5411   @Override
5412   public void tabSelectionChanged(int index)
5413   {
5414     if (index > -1)
5415     {
5416       alignPanel = alignPanels.get(index);
5417       viewport = alignPanel.av;
5418       avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5419       setMenusFromViewport(viewport);
5420       if (featureSettings != null && featureSettings.isOpen()
5421               && featureSettings.fr.getViewport() != viewport)
5422       {
5423         if (viewport.isShowSequenceFeatures())
5424         {
5425           // refresh the featureSettings to reflect UI change
5426           showFeatureSettingsUI();
5427         }
5428         else
5429         {
5430           // close feature settings for this view.
5431           featureSettings.close();
5432         }
5433       }
5434
5435     }
5436
5437     /*
5438      * 'focus' any colour slider that is open to the selected viewport
5439      */
5440     if (viewport.getConservationSelected())
5441     {
5442       SliderPanel.setConservationSlider(alignPanel,
5443               viewport.getResidueShading(), alignPanel.getViewName());
5444     }
5445     else
5446     {
5447       SliderPanel.hideConservationSlider();
5448     }
5449     if (viewport.getAbovePIDThreshold())
5450     {
5451       SliderPanel.setPIDSliderSource(alignPanel,
5452               viewport.getResidueShading(), alignPanel.getViewName());
5453     }
5454     else
5455     {
5456       SliderPanel.hidePIDSlider();
5457     }
5458
5459     /*
5460      * If there is a frame linked to this one in a SplitPane, switch it to the
5461      * same view tab index. No infinite recursion of calls should happen, since
5462      * tabSelectionChanged() should not get invoked on setting the selected
5463      * index to an unchanged value. Guard against setting an invalid index
5464      * before the new view peer tab has been created.
5465      */
5466     final AlignViewportI peer = viewport.getCodingComplement();
5467     if (peer != null)
5468     {
5469       AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5470               .getAlignPanel().alignFrame;
5471       if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5472       {
5473         linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5474       }
5475     }
5476   }
5477
5478   /**
5479    * On right mouse click on view tab, prompt for and set new view name.
5480    */
5481   @Override
5482   public void tabbedPane_mousePressed(MouseEvent e)
5483   {
5484     if (e.isPopupTrigger())
5485     {
5486       String msg = MessageManager.getString("label.enter_view_name");
5487       String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5488       String reply = JvOptionPane.showInputDialog(msg, ttl);
5489
5490       if (reply != null)
5491       {
5492         viewport.setViewName(reply);
5493         // TODO warn if reply is in getExistingViewNames()?
5494         tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5495       }
5496     }
5497   }
5498
5499   public AlignViewport getCurrentView()
5500   {
5501     return viewport;
5502   }
5503
5504   /**
5505    * Open the dialog for regex description parsing.
5506    */
5507   @Override
5508   protected void extractScores_actionPerformed(ActionEvent e)
5509   {
5510     ParseProperties pp = new jalview.analysis.ParseProperties(
5511             viewport.getAlignment());
5512     // TODO: verify regex and introduce GUI dialog for version 2.5
5513     // if (pp.getScoresFromDescription("col", "score column ",
5514     // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5515     // true)>0)
5516     if (pp.getScoresFromDescription("description column",
5517             "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5518     {
5519       buildSortByAnnotationScoresMenu();
5520     }
5521   }
5522
5523   /*
5524    * (non-Javadoc)
5525    * 
5526    * @see
5527    * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5528    * )
5529    */
5530   @Override
5531   protected void showDbRefs_actionPerformed(ActionEvent e)
5532   {
5533     viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5534   }
5535
5536   /*
5537    * (non-Javadoc)
5538    * 
5539    * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5540    * ActionEvent)
5541    */
5542   @Override
5543   protected void showNpFeats_actionPerformed(ActionEvent e)
5544   {
5545     viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5546   }
5547
5548   /**
5549    * find the viewport amongst the tabs in this alignment frame and close that
5550    * tab
5551    * 
5552    * @param av
5553    */
5554   public boolean closeView(AlignViewportI av)
5555   {
5556     if (viewport == av)
5557     {
5558       this.closeMenuItem_actionPerformed(false);
5559       return true;
5560     }
5561     Component[] comp = tabbedPane.getComponents();
5562     for (int i = 0; comp != null && i < comp.length; i++)
5563     {
5564       if (comp[i] instanceof AlignmentPanel)
5565       {
5566         if (((AlignmentPanel) comp[i]).av == av)
5567         {
5568           // close the view.
5569           closeView((AlignmentPanel) comp[i]);
5570           return true;
5571         }
5572       }
5573     }
5574     return false;
5575   }
5576
5577   protected void build_fetchdbmenu(JMenu webService)
5578   {
5579     // Temporary hack - DBRef Fetcher always top level ws entry.
5580     // TODO We probably want to store a sequence database checklist in
5581     // preferences and have checkboxes.. rather than individual sources selected
5582     // here
5583     final JMenu rfetch = new JMenu(
5584             MessageManager.getString("action.fetch_db_references"));
5585     rfetch.setToolTipText(MessageManager.getString(
5586             "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5587     webService.add(rfetch);
5588
5589     final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5590             MessageManager.getString("option.trim_retrieved_seqs"));
5591     trimrs.setToolTipText(
5592             MessageManager.getString("label.trim_retrieved_sequences"));
5593     trimrs.setSelected(
5594             Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5595     trimrs.addActionListener(new ActionListener()
5596     {
5597       @Override
5598       public void actionPerformed(ActionEvent e)
5599       {
5600         trimrs.setSelected(trimrs.isSelected());
5601         Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5602                 Boolean.valueOf(trimrs.isSelected()).toString());
5603       }
5604     });
5605     rfetch.add(trimrs);
5606     JMenuItem fetchr = new JMenuItem(
5607             MessageManager.getString("label.standard_databases"));
5608     fetchr.setToolTipText(
5609             MessageManager.getString("label.fetch_embl_uniprot"));
5610     fetchr.addActionListener(new ActionListener()
5611     {
5612
5613       @Override
5614       public void actionPerformed(ActionEvent e)
5615       {
5616         new Thread(new Runnable()
5617         {
5618           @Override
5619           public void run()
5620           {
5621             boolean isNucleotide = alignPanel.alignFrame.getViewport()
5622                     .getAlignment().isNucleotide();
5623             DBRefFetcher dbRefFetcher = new DBRefFetcher(
5624                     alignPanel.av.getSequenceSelection(),
5625                     alignPanel.alignFrame, null,
5626                     alignPanel.alignFrame.featureSettings, isNucleotide);
5627             dbRefFetcher.addListener(new FetchFinishedListenerI()
5628             {
5629               @Override
5630               public void finished()
5631               {
5632
5633                 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5634                         .getFeatureSettingsModels())
5635                 {
5636
5637                   alignPanel.av.mergeFeaturesStyle(srcSettings);
5638                 }
5639                 AlignFrame.this.setMenusForViewport();
5640               }
5641             });
5642             dbRefFetcher.fetchDBRefs(false);
5643           }
5644         }).start();
5645
5646       }
5647
5648     });
5649     rfetch.add(fetchr);
5650     new Thread(new Runnable()
5651     {
5652       @Override
5653       public void run()
5654       {
5655         // ??
5656         // final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5657         // .getSequenceFetcherSingleton();
5658         javax.swing.SwingUtilities.invokeLater(new Runnable()
5659         {
5660           @Override
5661           public void run()
5662           {
5663             jalview.ws.SequenceFetcher sf = jalview.ws.SequenceFetcher
5664                     .getInstance();
5665             String[] dbclasses = sf.getNonAlignmentSources();
5666             List<DbSourceProxy> otherdb;
5667             JMenu dfetch = new JMenu();
5668             JMenu ifetch = new JMenu();
5669             JMenuItem fetchr = null;
5670             int comp = 0, icomp = 0, mcomp = 15;
5671             String mname = null;
5672             int dbi = 0;
5673             for (String dbclass : dbclasses)
5674             {
5675               otherdb = sf.getSourceProxy(dbclass);
5676               // add a single entry for this class, or submenu allowing 'fetch
5677               // all' or pick one
5678               if (otherdb == null || otherdb.size() < 1)
5679               {
5680                 continue;
5681               }
5682               if (mname == null)
5683               {
5684                 mname = "From " + dbclass;
5685               }
5686               if (otherdb.size() == 1)
5687               {
5688                 DbSourceProxy src = otherdb.get(0);
5689                 DbSourceProxy[] dassource = new DbSourceProxy[] { src };
5690                 fetchr = new JMenuItem(src.getDbSource());
5691                 fetchr.addActionListener(new ActionListener()
5692                 {
5693
5694                   @Override
5695                   public void actionPerformed(ActionEvent e)
5696                   {
5697                     new Thread(new Runnable()
5698                     {
5699
5700                       @Override
5701                       public void run()
5702                       {
5703                         boolean isNucleotide = alignPanel.alignFrame
5704                                 .getViewport().getAlignment()
5705                                 .isNucleotide();
5706                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5707                                 alignPanel.av.getSequenceSelection(),
5708                                 alignPanel.alignFrame, dassource,
5709                                 alignPanel.alignFrame.featureSettings,
5710                                 isNucleotide);
5711                         dbRefFetcher
5712                                 .addListener(new FetchFinishedListenerI()
5713                                 {
5714                                   @Override
5715                                   public void finished()
5716                                   {
5717                                     FeatureSettingsModelI srcSettings = dassource[0]
5718                                             .getFeatureColourScheme();
5719                                     alignPanel.av.mergeFeaturesStyle(
5720                                             srcSettings);
5721                                     AlignFrame.this.setMenusForViewport();
5722                                   }
5723                                 });
5724                         dbRefFetcher.fetchDBRefs(false);
5725                       }
5726                     }).start();
5727                   }
5728
5729                 });
5730                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5731                         MessageManager.formatMessage(
5732                                 "label.fetch_retrieve_from", new Object[]
5733                                 { src.getDbName() })));
5734                 dfetch.add(fetchr);
5735                 comp++;
5736               }
5737               else
5738               {
5739                 final DbSourceProxy[] dassource = otherdb
5740                         .toArray(new DbSourceProxy[0]);
5741                 // fetch all entry
5742                 DbSourceProxy src = otherdb.get(0);
5743                 fetchr = new JMenuItem(MessageManager
5744                         .formatMessage("label.fetch_all_param", new Object[]
5745                         { src.getDbSource() }));
5746                 fetchr.addActionListener(new ActionListener()
5747                 {
5748                   @Override
5749                   public void actionPerformed(ActionEvent e)
5750                   {
5751                     new Thread(new Runnable()
5752                     {
5753
5754                       @Override
5755                       public void run()
5756                       {
5757                         boolean isNucleotide = alignPanel.alignFrame
5758                                 .getViewport().getAlignment()
5759                                 .isNucleotide();
5760                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5761                                 alignPanel.av.getSequenceSelection(),
5762                                 alignPanel.alignFrame, dassource,
5763                                 alignPanel.alignFrame.featureSettings,
5764                                 isNucleotide);
5765                         dbRefFetcher
5766                                 .addListener(new FetchFinishedListenerI()
5767                                 {
5768                                   @Override
5769                                   public void finished()
5770                                   {
5771                                     AlignFrame.this.setMenusForViewport();
5772                                   }
5773                                 });
5774                         dbRefFetcher.fetchDBRefs(false);
5775                       }
5776                     }).start();
5777                   }
5778                 });
5779
5780                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5781                         MessageManager.formatMessage(
5782                                 "label.fetch_retrieve_from_all_sources",
5783                                 new Object[]
5784                                 { Integer.valueOf(otherdb.size())
5785                                         .toString(),
5786                                     src.getDbSource(), src.getDbName() })));
5787                 dfetch.add(fetchr);
5788                 comp++;
5789                 // and then build the rest of the individual menus
5790                 ifetch = new JMenu(MessageManager.formatMessage(
5791                         "label.source_from_db_source", new Object[]
5792                         { src.getDbSource() }));
5793                 icomp = 0;
5794                 String imname = null;
5795                 int i = 0;
5796                 for (DbSourceProxy sproxy : otherdb)
5797                 {
5798                   String dbname = sproxy.getDbName();
5799                   String sname = dbname.length() > 5
5800                           ? dbname.substring(0, 5) + "..."
5801                           : dbname;
5802                   String msname = dbname.length() > 10
5803                           ? dbname.substring(0, 10) + "..."
5804                           : dbname;
5805                   if (imname == null)
5806                   {
5807                     imname = MessageManager
5808                             .formatMessage("label.from_msname", new Object[]
5809                             { sname });
5810                   }
5811                   fetchr = new JMenuItem(msname);
5812                   final DbSourceProxy[] dassrc = { sproxy };
5813                   fetchr.addActionListener(new ActionListener()
5814                   {
5815
5816                     @Override
5817                     public void actionPerformed(ActionEvent e)
5818                     {
5819                       new Thread(new Runnable()
5820                       {
5821
5822                         @Override
5823                         public void run()
5824                         {
5825                           boolean isNucleotide = alignPanel.alignFrame
5826                                   .getViewport().getAlignment()
5827                                   .isNucleotide();
5828                           DBRefFetcher dbRefFetcher = new DBRefFetcher(
5829                                   alignPanel.av.getSequenceSelection(),
5830                                   alignPanel.alignFrame, dassrc,
5831                                   alignPanel.alignFrame.featureSettings,
5832                                   isNucleotide);
5833                           dbRefFetcher
5834                                   .addListener(new FetchFinishedListenerI()
5835                                   {
5836                                     @Override
5837                                     public void finished()
5838                                     {
5839                                       AlignFrame.this.setMenusForViewport();
5840                                     }
5841                                   });
5842                           dbRefFetcher.fetchDBRefs(false);
5843                         }
5844                       }).start();
5845                     }
5846
5847                   });
5848                   fetchr.setToolTipText(
5849                           "<html>" + MessageManager.formatMessage(
5850                                   "label.fetch_retrieve_from", new Object[]
5851                                   { dbname }));
5852                   ifetch.add(fetchr);
5853                   ++i;
5854                   if (++icomp >= mcomp || i == (otherdb.size()))
5855                   {
5856                     ifetch.setText(MessageManager.formatMessage(
5857                             "label.source_to_target", imname, sname));
5858                     dfetch.add(ifetch);
5859                     ifetch = new JMenu();
5860                     imname = null;
5861                     icomp = 0;
5862                     comp++;
5863                   }
5864                 }
5865               }
5866               ++dbi;
5867               if (comp >= mcomp || dbi >= (dbclasses.length))
5868               {
5869                 dfetch.setText(MessageManager.formatMessage(
5870                         "label.source_to_target", mname, dbclass));
5871                 rfetch.add(dfetch);
5872                 dfetch = new JMenu();
5873                 mname = null;
5874                 comp = 0;
5875               }
5876             }
5877           }
5878         });
5879       }
5880     }).start();
5881
5882   }
5883
5884   /**
5885    * Left justify the whole alignment.
5886    */
5887   @Override
5888   protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5889   {
5890     viewport.getAlignment().justify(false);
5891     viewport.notifyAlignment();
5892   }
5893
5894   /**
5895    * Right justify the whole alignment.
5896    */
5897   @Override
5898   protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5899   {
5900     viewport.getAlignment().justify(true);
5901     viewport.notifyAlignment();
5902   }
5903
5904   @Override
5905   public void setShowSeqFeatures(boolean b)
5906   {
5907     showSeqFeatures.setSelected(b);
5908     viewport.setShowSequenceFeatures(b);
5909   }
5910
5911   /*
5912    * (non-Javadoc)
5913    * 
5914    * @see
5915    * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5916    * awt.event.ActionEvent)
5917    */
5918   @Override
5919   protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5920   {
5921     viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5922     alignPanel.paintAlignment(false, false);
5923   }
5924
5925   /*
5926    * (non-Javadoc)
5927    * 
5928    * @see
5929    * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5930    * .ActionEvent)
5931    */
5932   @Override
5933   protected void showGroupConsensus_actionPerformed(ActionEvent e)
5934   {
5935     viewport.setShowGroupConsensus(showGroupConsensus.getState());
5936     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5937
5938   }
5939
5940   /*
5941    * (non-Javadoc)
5942    * 
5943    * @see
5944    * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5945    * .event.ActionEvent)
5946    */
5947   @Override
5948   protected void showGroupConservation_actionPerformed(ActionEvent e)
5949   {
5950     viewport.setShowGroupConservation(showGroupConservation.getState());
5951     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5952   }
5953
5954   /*
5955    * (non-Javadoc)
5956    * 
5957    * @see
5958    * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5959    * .event.ActionEvent)
5960    */
5961   @Override
5962   protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5963   {
5964     viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5965     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5966   }
5967
5968   /*
5969    * (non-Javadoc)
5970    * 
5971    * @see
5972    * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5973    * .event.ActionEvent)
5974    */
5975   @Override
5976   protected void showSequenceLogo_actionPerformed(ActionEvent e)
5977   {
5978     viewport.setShowSequenceLogo(showSequenceLogo.getState());
5979     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5980   }
5981
5982   @Override
5983   protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5984   {
5985     showSequenceLogo.setState(true);
5986     viewport.setShowSequenceLogo(true);
5987     viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5988     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5989   }
5990
5991   @Override
5992   protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5993   {
5994     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5995   }
5996
5997   /*
5998    * (non-Javadoc)
5999    * 
6000    * @see
6001    * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
6002    * .event.ActionEvent)
6003    */
6004   @Override
6005   protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
6006   {
6007     if (avc.makeGroupsFromSelection())
6008     {
6009       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
6010       alignPanel.updateAnnotation();
6011       alignPanel.paintAlignment(true,
6012               viewport.needToUpdateStructureViews());
6013     }
6014   }
6015
6016   public void clearAlignmentSeqRep()
6017   {
6018     // TODO refactor alignmentseqrep to controller
6019     if (viewport.getAlignment().hasSeqrep())
6020     {
6021       viewport.getAlignment().setSeqrep(null);
6022       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
6023       alignPanel.updateAnnotation();
6024       alignPanel.paintAlignment(true, true);
6025     }
6026   }
6027
6028   @Override
6029   protected void createGroup_actionPerformed(ActionEvent e)
6030   {
6031     if (avc.createGroup())
6032     {
6033       if (applyAutoAnnotationSettings.isSelected())
6034       {
6035         alignPanel.updateAnnotation(true, false);
6036       }
6037       alignPanel.alignmentChanged();
6038     }
6039   }
6040
6041   @Override
6042   protected void unGroup_actionPerformed(ActionEvent e)
6043   {
6044     if (avc.unGroup())
6045     {
6046       alignPanel.alignmentChanged();
6047     }
6048   }
6049
6050   /**
6051    * make the given alignmentPanel the currently selected tab
6052    * 
6053    * @param alignmentPanel
6054    */
6055   public void setDisplayedView(AlignmentPanel alignmentPanel)
6056   {
6057     if (!viewport.getSequenceSetId()
6058             .equals(alignmentPanel.av.getSequenceSetId()))
6059     {
6060       throw new Error(MessageManager.getString(
6061               "error.implementation_error_cannot_show_view_alignment_frame"));
6062     }
6063     if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
6064             .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
6065     {
6066       tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
6067     }
6068   }
6069
6070   /**
6071    * Action on selection of menu options to Show or Hide annotations.
6072    * 
6073    * @param visible
6074    * @param forSequences
6075    *          update sequence-related annotations
6076    * @param forAlignment
6077    *          update non-sequence-related annotations
6078    */
6079   @Override
6080   protected void setAnnotationsVisibility(boolean visible,
6081           boolean forSequences, boolean forAlignment)
6082   {
6083     AlignmentAnnotation[] anns = alignPanel.getAlignment()
6084             .getAlignmentAnnotation();
6085     if (anns == null)
6086     {
6087       return;
6088     }
6089     for (AlignmentAnnotation aa : anns)
6090     {
6091       /*
6092        * don't display non-positional annotations on an alignment
6093        */
6094       if (aa.annotations == null)
6095       {
6096         continue;
6097       }
6098       boolean apply = (aa.sequenceRef == null && forAlignment)
6099               || (aa.sequenceRef != null && forSequences);
6100       if (apply)
6101       {
6102         aa.visible = visible;
6103       }
6104     }
6105     alignPanel.validateAnnotationDimensions(true);
6106     alignPanel.alignmentChanged();
6107   }
6108
6109   /**
6110    * Store selected annotation sort order for the view and repaint.
6111    */
6112   @Override
6113   protected void sortAnnotations_actionPerformed()
6114   {
6115     this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
6116     this.alignPanel.av
6117             .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
6118     alignPanel.paintAlignment(false, false);
6119   }
6120
6121   /**
6122    * 
6123    * @return alignment panels in this alignment frame
6124    */
6125   public List<? extends AlignmentViewPanel> getAlignPanels()
6126   {
6127     // alignPanels is never null
6128     // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
6129     return alignPanels;
6130   }
6131
6132   /**
6133    * Open a new alignment window, with the cDNA associated with this (protein)
6134    * alignment, aligned as is the protein.
6135    */
6136   protected void viewAsCdna_actionPerformed()
6137   {
6138     // TODO no longer a menu action - refactor as required
6139     final AlignmentI alignment = getViewport().getAlignment();
6140     List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6141     if (mappings == null)
6142     {
6143       return;
6144     }
6145     List<SequenceI> cdnaSeqs = new ArrayList<>();
6146     for (SequenceI aaSeq : alignment.getSequences())
6147     {
6148       for (AlignedCodonFrame acf : mappings)
6149       {
6150         SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6151         if (dnaSeq != null)
6152         {
6153           /*
6154            * There is a cDNA mapping for this protein sequence - add to new
6155            * alignment. It will share the same dataset sequence as other mapped
6156            * cDNA (no new mappings need to be created).
6157            */
6158           final Sequence newSeq = new Sequence(dnaSeq);
6159           newSeq.setDatasetSequence(dnaSeq);
6160           cdnaSeqs.add(newSeq);
6161         }
6162       }
6163     }
6164     if (cdnaSeqs.size() == 0)
6165     {
6166       // show a warning dialog no mapped cDNA
6167       return;
6168     }
6169     AlignmentI cdna = new Alignment(
6170             cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
6171     GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6172             AlignFrame.DEFAULT_HEIGHT);
6173     cdna.alignAs(alignment);
6174     String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6175             + this.title;
6176     Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
6177             AlignFrame.DEFAULT_HEIGHT);
6178   }
6179
6180   /**
6181    * Set visibility of dna/protein complement view (available when shown in a
6182    * split frame).
6183    * 
6184    * @param show
6185    */
6186   @Override
6187   protected void showComplement_actionPerformed(boolean show)
6188   {
6189     SplitContainerI sf = getSplitViewContainer();
6190     if (sf != null)
6191     {
6192       sf.setComplementVisible(this, show);
6193     }
6194   }
6195
6196   /**
6197    * Generate the reverse (optionally complemented) of the selected sequences,
6198    * and add them to the alignment
6199    */
6200   @Override
6201   protected void showReverse_actionPerformed(boolean complement)
6202   {
6203     AlignmentI al = null;
6204     try
6205     {
6206       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
6207       al = dna.reverseCdna(complement);
6208       viewport.addAlignment(al, "");
6209       addHistoryItem(new EditCommand(
6210               MessageManager.getString("label.add_sequences"), Action.PASTE,
6211               al.getSequencesArray(), 0, al.getWidth(),
6212               viewport.getAlignment()));
6213     } catch (Exception ex)
6214     {
6215       System.err.println(ex.getMessage());
6216       return;
6217     }
6218   }
6219
6220   /**
6221    * Try to run a script in the Groovy console, having first ensured that this
6222    * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
6223    * be targeted at this alignment.
6224    */
6225   @Override
6226   protected void runGroovy_actionPerformed()
6227   {
6228     Jalview.setCurrentAlignFrame(this);
6229     groovy.ui.Console console = Desktop.getGroovyConsole();
6230     if (console != null)
6231     {
6232       try
6233       {
6234         console.runScript();
6235       } catch (Exception ex)
6236       {
6237         System.err.println((ex.toString()));
6238         JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
6239                 MessageManager.getString("label.couldnt_run_groovy_script"),
6240                 MessageManager.getString("label.groovy_support_failed"),
6241                 JvOptionPane.ERROR_MESSAGE);
6242       }
6243     }
6244     else
6245     {
6246       System.err.println("Can't run Groovy script as console not found");
6247     }
6248   }
6249
6250   /**
6251    * Hides columns containing (or not containing) a specified feature, provided
6252    * that would not leave all columns hidden
6253    * 
6254    * @param featureType
6255    * @param columnsContaining
6256    * @return
6257    */
6258   public boolean hideFeatureColumns(String featureType,
6259           boolean columnsContaining)
6260   {
6261     boolean notForHiding = avc.markColumnsContainingFeatures(
6262             columnsContaining, false, false, featureType);
6263     if (notForHiding)
6264     {
6265       if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6266               false, featureType))
6267       {
6268         getViewport().hideSelectedColumns();
6269         return true;
6270       }
6271     }
6272     return false;
6273   }
6274
6275   @Override
6276   protected void selectHighlightedColumns_actionPerformed(
6277           ActionEvent actionEvent)
6278   {
6279     // include key modifier check in case user selects from menu
6280     avc.markHighlightedColumns(
6281             (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6282             (actionEvent.getModifiers() & (ActionEvent.META_MASK
6283                     | ActionEvent.CTRL_MASK)) != 0);
6284   }
6285
6286   /**
6287    * Rebuilds the Colour menu, including any user-defined colours which have
6288    * been loaded either on startup or during the session
6289    */
6290   public void buildColourMenu()
6291   {
6292     colourMenu.removeAll();
6293
6294     colourMenu.add(applyToAllGroups);
6295     colourMenu.add(textColour);
6296     colourMenu.addSeparator();
6297
6298     ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6299             viewport.getAlignment(), false);
6300
6301     colourMenu.add(annotationColour);
6302     bg.add(annotationColour);
6303     colourMenu.addSeparator();
6304     colourMenu.add(conservationMenuItem);
6305     colourMenu.add(modifyConservation);
6306     colourMenu.add(abovePIDThreshold);
6307     colourMenu.add(modifyPID);
6308
6309     ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6310     ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6311   }
6312
6313   /**
6314    * Open a dialog (if not already open) that allows the user to select and
6315    * calculate PCA or Tree analysis
6316    */
6317   protected void openTreePcaDialog()
6318   {
6319     if (alignPanel.getCalculationDialog() == null)
6320     {
6321       new CalculationChooser(AlignFrame.this);
6322     }
6323   }
6324
6325   /**
6326    * Sets the status of the HMMER menu
6327    */
6328   public void updateHMMERStatus()
6329   {
6330     hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
6331   }
6332   @Override
6333   protected void loadVcf_actionPerformed()
6334   {
6335     JalviewFileChooser chooser = new JalviewFileChooser(
6336             Cache.getProperty("LAST_DIRECTORY"));
6337     chooser.setFileView(new JalviewFileView());
6338     chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6339     chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6340     final AlignFrame us = this;
6341     chooser.setResponseHandler(0, new Runnable()
6342     {
6343       @Override
6344       public void run()
6345       {
6346         String choice = chooser.getSelectedFile().getPath();
6347         Cache.setProperty("LAST_DIRECTORY", choice);
6348         SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6349         new VCFLoader(choice).loadVCF(seqs, us);
6350       }
6351     });
6352     chooser.showOpenDialog(null);
6353
6354   }
6355
6356   private Rectangle lastFeatureSettingsBounds = null;
6357
6358   @Override
6359   public void setFeatureSettingsGeometry(Rectangle bounds)
6360   {
6361     lastFeatureSettingsBounds = bounds;
6362   }
6363
6364   @Override
6365   public Rectangle getFeatureSettingsGeometry()
6366   {
6367     return lastFeatureSettingsBounds;
6368   }
6369
6370   public void scrollTo(int row, int column)
6371   {
6372     alignPanel.getSeqPanel().scrollTo(row, column);
6373   }
6374
6375   public void scrollToRow(int row)
6376   {
6377     alignPanel.getSeqPanel().scrollToRow(row);
6378   }
6379
6380   public void scrollToColumn(int column)
6381   {
6382     alignPanel.getSeqPanel().scrollToColumn(column);
6383   }
6384
6385   /**
6386    * BH 2019 from JalviewLite
6387    * 
6388    * get sequence feature groups that are hidden or shown
6389    * 
6390    * @param visible
6391    *          true is visible
6392    * @return list
6393    */
6394
6395   public String[] getFeatureGroupsOfState(boolean visible)
6396   {
6397     jalview.api.FeatureRenderer fr = null;
6398     if (alignPanel != null
6399             && (fr = alignPanel.getFeatureRenderer()) != null)
6400     {
6401       List<String> gps = fr.getGroups(visible);
6402       String[] _gps = gps.toArray(new String[gps.size()]);
6403       return _gps;
6404     }
6405     return null;
6406   }
6407
6408   /**
6409    * 
6410    * @return list of feature groups on the view
6411    */
6412
6413   public String[] getFeatureGroups()
6414   {
6415     jalview.api.FeatureRenderer fr = null;
6416     if (alignPanel != null
6417             && (fr = alignPanel.getFeatureRenderer()) != null)
6418     {
6419       List<String> gps = fr.getFeatureGroups();
6420       String[] _gps = gps.toArray(new String[gps.size()]);
6421       return _gps;
6422     }
6423     return null;
6424   }
6425
6426   public void select(SequenceGroup sel, ColumnSelection csel,
6427           HiddenColumns hidden)
6428   {
6429     alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
6430   }
6431
6432   public int getID()
6433   {
6434     return id;
6435   }
6436
6437   static class PrintThread extends Thread
6438   {
6439     AlignmentPanel ap;
6440
6441     public PrintThread(AlignmentPanel ap)
6442     {
6443       this.ap = ap;
6444     }
6445
6446     static PageFormat pf;
6447
6448     @Override
6449     public void run()
6450     {
6451       PrinterJob printJob = PrinterJob.getPrinterJob();
6452
6453       if (pf != null)
6454       {
6455         printJob.setPrintable(ap, pf);
6456       }
6457       else
6458       {
6459         printJob.setPrintable(ap);
6460       }
6461
6462       if (printJob.printDialog())
6463       {
6464         try
6465         {
6466           printJob.print();
6467         } catch (Exception PrintException)
6468         {
6469           PrintException.printStackTrace();
6470         }
6471       }
6472     }
6473   }
6474 }