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