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