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