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