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