01aa9b057e514e8f045d2c7d780a220779bd975f
[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     final OverviewPanel overview = new OverviewPanel(alignPanel);
3389     frame.setContentPane(overview);
3390     Desktop.addInternalFrame(frame, MessageManager
3391             .formatMessage("label.overview_params", new Object[]
3392             { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3393             true, true, "overview");
3394     frame.pack();
3395     frame.setLayer(JLayeredPane.PALETTE_LAYER);
3396     frame.addInternalFrameListener(
3397             new javax.swing.event.InternalFrameAdapter()
3398             {
3399               @Override
3400               public void internalFrameClosed(
3401                       javax.swing.event.InternalFrameEvent evt)
3402               {
3403                 overview.dispose();
3404                 alignPanel.setOverviewPanel(null);
3405               }
3406             });
3407     if (getKeyListeners().length > 0)
3408     {
3409       frame.addKeyListener(getKeyListeners()[0]);
3410     }
3411
3412     alignPanel.setOverviewPanel(overview);
3413   }
3414
3415   @Override
3416   public void textColour_actionPerformed()
3417   {
3418     new TextColourChooser().chooseColour(alignPanel, null);
3419   }
3420
3421   /*
3422    * public void covariationColour_actionPerformed() {
3423    * changeColour(new
3424    * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3425    * ()[0])); }
3426    */
3427   @Override
3428   public void annotationColour_actionPerformed()
3429   {
3430     new AnnotationColourChooser(viewport, alignPanel);
3431   }
3432
3433   @Override
3434   public void annotationColumn_actionPerformed(ActionEvent e)
3435   {
3436     new AnnotationColumnChooser(viewport, alignPanel);
3437   }
3438
3439   /**
3440    * Action on the user checking or unchecking the option to apply the selected
3441    * colour scheme to all groups. If unchecked, groups may have their own
3442    * independent colour schemes.
3443    * 
3444    * @param selected
3445    */
3446   @Override
3447   public void applyToAllGroups_actionPerformed(boolean selected)
3448   {
3449     viewport.setColourAppliesToAllGroups(selected);
3450   }
3451
3452   /**
3453    * Action on user selecting a colour from the colour menu
3454    * 
3455    * @param name
3456    *          the name (not the menu item label!) of the colour scheme
3457    */
3458   @Override
3459   public void changeColour_actionPerformed(String name)
3460   {
3461     /*
3462      * 'User Defined' opens a panel to configure or load a
3463      * user-defined colour scheme
3464      */
3465     if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3466     {
3467       new UserDefinedColours(alignPanel);
3468       return;
3469     }
3470
3471     /*
3472      * otherwise set the chosen colour scheme (or null for 'None')
3473      */
3474     ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3475             viewport,
3476             viewport.getAlignment(), viewport.getHiddenRepSequences());
3477     changeColour(cs);
3478   }
3479
3480   /**
3481    * Actions on setting or changing the alignment colour scheme
3482    * 
3483    * @param cs
3484    */
3485   @Override
3486   public void changeColour(ColourSchemeI cs)
3487   {
3488     // TODO: pull up to controller method
3489     ColourMenuHelper.setColourSelected(colourMenu, cs);
3490
3491     viewport.setGlobalColourScheme(cs);
3492
3493     alignPanel.paintAlignment(true, true);
3494   }
3495
3496   /**
3497    * Show the PID threshold slider panel
3498    */
3499   @Override
3500   protected void modifyPID_actionPerformed()
3501   {
3502     SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3503             alignPanel.getViewName());
3504     SliderPanel.showPIDSlider();
3505   }
3506
3507   /**
3508    * Show the Conservation slider panel
3509    */
3510   @Override
3511   protected void modifyConservation_actionPerformed()
3512   {
3513     SliderPanel.setConservationSlider(alignPanel,
3514             viewport.getResidueShading(), alignPanel.getViewName());
3515     SliderPanel.showConservationSlider();
3516   }
3517
3518   /**
3519    * Action on selecting or deselecting (Colour) By Conservation
3520    */
3521   @Override
3522   public void conservationMenuItem_actionPerformed(boolean selected)
3523   {
3524     modifyConservation.setEnabled(selected);
3525     viewport.setConservationSelected(selected);
3526     viewport.getResidueShading().setConservationApplied(selected);
3527
3528     changeColour(viewport.getGlobalColourScheme());
3529     if (selected)
3530     {
3531       modifyConservation_actionPerformed();
3532     }
3533     else
3534     {
3535       SliderPanel.hideConservationSlider();
3536     }
3537   }
3538
3539   /**
3540    * Action on selecting or deselecting (Colour) Above PID Threshold
3541    */
3542   @Override
3543   public void abovePIDThreshold_actionPerformed(boolean selected)
3544   {
3545     modifyPID.setEnabled(selected);
3546     viewport.setAbovePIDThreshold(selected);
3547     if (!selected)
3548     {
3549       viewport.getResidueShading().setThreshold(0,
3550               viewport.isIgnoreGapsConsensus());
3551     }
3552
3553     changeColour(viewport.getGlobalColourScheme());
3554     if (selected)
3555     {
3556       modifyPID_actionPerformed();
3557     }
3558     else
3559     {
3560       SliderPanel.hidePIDSlider();
3561     }
3562   }
3563
3564   /**
3565    * DOCUMENT ME!
3566    * 
3567    * @param e
3568    *          DOCUMENT ME!
3569    */
3570   @Override
3571   public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3572   {
3573     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3574     AlignmentSorter.sortByPID(viewport.getAlignment(),
3575             viewport.getAlignment().getSequenceAt(0));
3576     addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3577             viewport.getAlignment()));
3578     alignPanel.paintAlignment(true, false);
3579   }
3580
3581   /**
3582    * DOCUMENT ME!
3583    * 
3584    * @param e
3585    *          DOCUMENT ME!
3586    */
3587   @Override
3588   public void sortIDMenuItem_actionPerformed(ActionEvent e)
3589   {
3590     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3591     AlignmentSorter.sortByID(viewport.getAlignment());
3592     addHistoryItem(
3593             new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3594     alignPanel.paintAlignment(true, false);
3595   }
3596
3597   /**
3598    * DOCUMENT ME!
3599    * 
3600    * @param e
3601    *          DOCUMENT ME!
3602    */
3603   @Override
3604   public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3605   {
3606     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3607     AlignmentSorter.sortByLength(viewport.getAlignment());
3608     addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3609             viewport.getAlignment()));
3610     alignPanel.paintAlignment(true, false);
3611   }
3612
3613   /**
3614    * DOCUMENT ME!
3615    * 
3616    * @param e
3617    *          DOCUMENT ME!
3618    */
3619   @Override
3620   public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3621   {
3622     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3623     AlignmentSorter.sortByGroup(viewport.getAlignment());
3624     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3625             viewport.getAlignment()));
3626
3627     alignPanel.paintAlignment(true, false);
3628   }
3629
3630   /**
3631    * DOCUMENT ME!
3632    * 
3633    * @param e
3634    *          DOCUMENT ME!
3635    */
3636   @Override
3637   public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3638   {
3639     new RedundancyPanel(alignPanel, this);
3640   }
3641
3642   /**
3643    * DOCUMENT ME!
3644    * 
3645    * @param e
3646    *          DOCUMENT ME!
3647    */
3648   @Override
3649   public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3650   {
3651     if ((viewport.getSelectionGroup() == null)
3652             || (viewport.getSelectionGroup().getSize() < 2))
3653     {
3654       JvOptionPane.showInternalMessageDialog(this,
3655               MessageManager.getString(
3656                       "label.you_must_select_least_two_sequences"),
3657               MessageManager.getString("label.invalid_selection"),
3658               JvOptionPane.WARNING_MESSAGE);
3659     }
3660     else
3661     {
3662       JInternalFrame frame = new JInternalFrame();
3663       frame.setContentPane(new PairwiseAlignPanel(viewport));
3664       Desktop.addInternalFrame(frame,
3665               MessageManager.getString("action.pairwise_alignment"), 600,
3666               500);
3667     }
3668   }
3669
3670   @Override
3671   public void autoCalculate_actionPerformed(ActionEvent e)
3672   {
3673     viewport.setAutoCalculateConsensusAndConservation(autoCalculate.isSelected());
3674     if (viewport.getAutoCalculateConsensusAndConservation())
3675     {
3676       viewport.firePropertyChange("alignment", null,
3677               viewport.getAlignment().getSequences());
3678     }
3679   }
3680
3681   @Override
3682   public void sortByTreeOption_actionPerformed(ActionEvent e)
3683   {
3684     viewport.sortByTree = sortByTree.isSelected();
3685   }
3686
3687   @Override
3688   protected void listenToViewSelections_actionPerformed(ActionEvent e)
3689   {
3690     viewport.followSelection = listenToViewSelections.isSelected();
3691   }
3692
3693   /**
3694    * Constructs a tree panel and adds it to the desktop
3695    * 
3696    * @param type
3697    *          tree type (NJ or AV)
3698    * @param modelName
3699    *          name of score model used to compute the tree
3700    * @param options
3701    *          parameters for the distance or similarity calculation
3702    */
3703   void newTreePanel(String type, String modelName,
3704           SimilarityParamsI options)
3705   {
3706     String frameTitle = "";
3707     TreePanel tp;
3708
3709     boolean onSelection = false;
3710     if (viewport.getSelectionGroup() != null
3711             && viewport.getSelectionGroup().getSize() > 0)
3712     {
3713       SequenceGroup sg = viewport.getSelectionGroup();
3714
3715       /* Decide if the selection is a column region */
3716       for (SequenceI _s : sg.getSequences())
3717       {
3718         if (_s.getLength() < sg.getEndRes())
3719         {
3720           JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
3721                   MessageManager.getString(
3722                           "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3723                   MessageManager.getString(
3724                           "label.sequences_selection_not_aligned"),
3725                   JvOptionPane.WARNING_MESSAGE);
3726
3727           return;
3728         }
3729       }
3730       onSelection = true;
3731     }
3732     else
3733     {
3734       if (viewport.getAlignment().getHeight() < 2)
3735       {
3736         return;
3737       }
3738     }
3739
3740     tp = new TreePanel(alignPanel, type, modelName, options);
3741     frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3742
3743     frameTitle += " from ";
3744
3745     if (viewport.getViewName() != null)
3746     {
3747       frameTitle += viewport.getViewName() + " of ";
3748     }
3749
3750     frameTitle += this.title;
3751
3752     Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3753   }
3754
3755   /**
3756    * DOCUMENT ME!
3757    * 
3758    * @param title
3759    *          DOCUMENT ME!
3760    * @param order
3761    *          DOCUMENT ME!
3762    */
3763   public void addSortByOrderMenuItem(String title,
3764           final AlignmentOrder order)
3765   {
3766     final JMenuItem item = new JMenuItem(MessageManager
3767             .formatMessage("action.by_title_param", new Object[]
3768             { title }));
3769     sort.add(item);
3770     item.addActionListener(new java.awt.event.ActionListener()
3771     {
3772       @Override
3773       public void actionPerformed(ActionEvent e)
3774       {
3775         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3776
3777         // TODO: JBPNote - have to map order entries to curent SequenceI
3778         // pointers
3779         AlignmentSorter.sortBy(viewport.getAlignment(), order);
3780
3781         addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3782                 viewport.getAlignment()));
3783
3784         alignPanel.paintAlignment(true, false);
3785       }
3786     });
3787   }
3788
3789   /**
3790    * Add a new sort by annotation score menu item
3791    * 
3792    * @param sort
3793    *          the menu to add the option to
3794    * @param scoreLabel
3795    *          the label used to retrieve scores for each sequence on the
3796    *          alignment
3797    */
3798   public void addSortByAnnotScoreMenuItem(JMenu sort,
3799           final String scoreLabel)
3800   {
3801     final JMenuItem item = new JMenuItem(scoreLabel);
3802     sort.add(item);
3803     item.addActionListener(new java.awt.event.ActionListener()
3804     {
3805       @Override
3806       public void actionPerformed(ActionEvent e)
3807       {
3808         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3809         AlignmentSorter.sortByAnnotationScore(scoreLabel,
3810                 viewport.getAlignment());// ,viewport.getSelectionGroup());
3811         addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3812                 viewport.getAlignment()));
3813         alignPanel.paintAlignment(true, false);
3814       }
3815     });
3816   }
3817
3818   /**
3819    * last hash for alignment's annotation array - used to minimise cost of
3820    * rebuild.
3821    */
3822   protected int _annotationScoreVectorHash;
3823
3824   /**
3825    * search the alignment and rebuild the sort by annotation score submenu the
3826    * last alignment annotation vector hash is stored to minimize cost of
3827    * rebuilding in subsequence calls.
3828    * 
3829    */
3830   @Override
3831   public void buildSortByAnnotationScoresMenu()
3832   {
3833     if (viewport.getAlignment().getAlignmentAnnotation() == null)
3834     {
3835       return;
3836     }
3837
3838     if (viewport.getAlignment().getAlignmentAnnotation()
3839             .hashCode() != _annotationScoreVectorHash)
3840     {
3841       sortByAnnotScore.removeAll();
3842       // almost certainly a quicker way to do this - but we keep it simple
3843       Hashtable<String, String> scoreSorts = new Hashtable<>();
3844       AlignmentAnnotation aann[];
3845       for (SequenceI sqa : viewport.getAlignment().getSequences())
3846       {
3847         aann = sqa.getAnnotation();
3848         for (int i = 0; aann != null && i < aann.length; i++)
3849         {
3850           if (aann[i].hasScore() && aann[i].sequenceRef != null)
3851           {
3852             scoreSorts.put(aann[i].label, aann[i].label);
3853           }
3854         }
3855       }
3856       Enumeration<String> labels = scoreSorts.keys();
3857       while (labels.hasMoreElements())
3858       {
3859         addSortByAnnotScoreMenuItem(sortByAnnotScore,
3860                 labels.nextElement());
3861       }
3862       sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3863       scoreSorts.clear();
3864
3865       _annotationScoreVectorHash = viewport.getAlignment()
3866               .getAlignmentAnnotation().hashCode();
3867     }
3868   }
3869
3870   /**
3871    * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3872    * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3873    * call. Listeners are added to remove the menu item when the treePanel is
3874    * closed, and adjust the tree leaf to sequence mapping when the alignment is
3875    * modified.
3876    */
3877   @Override
3878   public void buildTreeSortMenu()
3879   {
3880     sortByTreeMenu.removeAll();
3881
3882     List<Component> comps = PaintRefresher.components
3883             .get(viewport.getSequenceSetId());
3884     List<TreePanel> treePanels = new ArrayList<>();
3885     for (Component comp : comps)
3886     {
3887       if (comp instanceof TreePanel)
3888       {
3889         treePanels.add((TreePanel) comp);
3890       }
3891     }
3892
3893     if (treePanels.size() < 1)
3894     {
3895       sortByTreeMenu.setVisible(false);
3896       return;
3897     }
3898
3899     sortByTreeMenu.setVisible(true);
3900
3901     for (final TreePanel tp : treePanels)
3902     {
3903       final JMenuItem item = new JMenuItem(tp.getTitle());
3904       item.addActionListener(new java.awt.event.ActionListener()
3905       {
3906         @Override
3907         public void actionPerformed(ActionEvent e)
3908         {
3909           tp.sortByTree_actionPerformed();
3910           addHistoryItem(tp.sortAlignmentIn(alignPanel));
3911
3912         }
3913       });
3914
3915       sortByTreeMenu.add(item);
3916     }
3917   }
3918
3919   public boolean sortBy(AlignmentOrder alorder, String undoname)
3920   {
3921     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3922     AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3923     if (undoname != null)
3924     {
3925       addHistoryItem(new OrderCommand(undoname, oldOrder,
3926               viewport.getAlignment()));
3927     }
3928     alignPanel.paintAlignment(true, false);
3929     return true;
3930   }
3931
3932   /**
3933    * Work out whether the whole set of sequences or just the selected set will
3934    * be submitted for multiple alignment.
3935    * 
3936    */
3937   public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3938   {
3939     // Now, check we have enough sequences
3940     AlignmentView msa = null;
3941
3942     if ((viewport.getSelectionGroup() != null)
3943             && (viewport.getSelectionGroup().getSize() > 1))
3944     {
3945       // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3946       // some common interface!
3947       /*
3948        * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3949        * SequenceI[sz = seqs.getSize(false)];
3950        * 
3951        * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3952        * seqs.getSequenceAt(i); }
3953        */
3954       msa = viewport.getAlignmentView(true);
3955     }
3956     else if (viewport.getSelectionGroup() != null
3957             && viewport.getSelectionGroup().getSize() == 1)
3958     {
3959       int option = JvOptionPane.showConfirmDialog(this,
3960               MessageManager.getString("warn.oneseq_msainput_selection"),
3961               MessageManager.getString("label.invalid_selection"),
3962               JvOptionPane.OK_CANCEL_OPTION);
3963       if (option == JvOptionPane.OK_OPTION)
3964       {
3965         msa = viewport.getAlignmentView(false);
3966       }
3967     }
3968     else
3969     {
3970       msa = viewport.getAlignmentView(false);
3971     }
3972     return msa;
3973   }
3974
3975   /**
3976    * Decides what is submitted to a secondary structure prediction service: the
3977    * first sequence in the alignment, or in the current selection, or, if the
3978    * alignment is 'aligned' (ie padded with gaps), then the currently selected
3979    * region or the whole alignment. (where the first sequence in the set is the
3980    * one that the prediction will be for).
3981    */
3982   public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3983   {
3984     AlignmentView seqs = null;
3985
3986     if ((viewport.getSelectionGroup() != null)
3987             && (viewport.getSelectionGroup().getSize() > 0))
3988     {
3989       seqs = viewport.getAlignmentView(true);
3990     }
3991     else
3992     {
3993       seqs = viewport.getAlignmentView(false);
3994     }
3995     // limit sequences - JBPNote in future - could spawn multiple prediction
3996     // jobs
3997     // TODO: viewport.getAlignment().isAligned is a global state - the local
3998     // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3999     if (!viewport.getAlignment().isAligned(false))
4000     {
4001       seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4002       // TODO: if seqs.getSequences().length>1 then should really have warned
4003       // user!
4004
4005     }
4006     return seqs;
4007   }
4008
4009   /**
4010    * DOCUMENT ME!
4011    * 
4012    * @param e
4013    *          DOCUMENT ME!
4014    */
4015   @Override
4016   protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4017   {
4018     // Pick the tree file
4019     JalviewFileChooser chooser = new JalviewFileChooser(
4020             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4021     chooser.setFileView(new JalviewFileView());
4022     chooser.setDialogTitle(
4023             MessageManager.getString("label.select_newick_like_tree_file"));
4024     chooser.setToolTipText(
4025             MessageManager.getString("label.load_tree_file"));
4026
4027     chooser.setResponseHandler(0,new Runnable()
4028     {
4029       @Override
4030       public void run()
4031       {
4032         String filePath = chooser.getSelectedFile().getPath();
4033         Cache.setProperty("LAST_DIRECTORY", filePath);
4034         NewickFile fin = null;
4035         try
4036         {
4037           fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4038                   DataSourceType.FILE));
4039           viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4040         } catch (Exception ex)
4041         {
4042           JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), ex.getMessage(),
4043                   MessageManager
4044                           .getString("label.problem_reading_tree_file"),
4045                   JvOptionPane.WARNING_MESSAGE);
4046           ex.printStackTrace();
4047         }
4048         if (fin != null && fin.hasWarningMessage())
4049         {
4050           JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4051                   fin.getWarningMessage(),
4052                   MessageManager.getString(
4053                           "label.possible_problem_with_tree_file"),
4054                   JvOptionPane.WARNING_MESSAGE);
4055         }
4056       }
4057     });
4058     chooser.showOpenDialog(this);
4059   }
4060
4061   public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4062   {
4063     return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4064   }
4065
4066   public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4067           int h, int x, int y)
4068   {
4069     return showNewickTree(nf, treeTitle, null, w, h, x, y);
4070   }
4071
4072   /**
4073    * Add a treeviewer for the tree extracted from a Newick file object to the
4074    * current alignment view
4075    * 
4076    * @param nf
4077    *          the tree
4078    * @param title
4079    *          tree viewer title
4080    * @param input
4081    *          Associated alignment input data (or null)
4082    * @param w
4083    *          width
4084    * @param h
4085    *          height
4086    * @param x
4087    *          position
4088    * @param y
4089    *          position
4090    * @return TreePanel handle
4091    */
4092   public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4093           AlignmentView input, int w, int h, int x, int y)
4094   {
4095     TreePanel tp = null;
4096
4097     try
4098     {
4099       nf.parse();
4100
4101       if (nf.getTree() != null)
4102       {
4103         tp = new TreePanel(alignPanel, nf, treeTitle, input);
4104
4105         tp.setSize(w, h);
4106
4107         if (x > 0 && y > 0)
4108         {
4109           tp.setLocation(x, y);
4110         }
4111
4112         Desktop.addInternalFrame(tp, treeTitle, w, h);
4113       }
4114     } catch (Exception ex)
4115     {
4116       ex.printStackTrace();
4117     }
4118
4119     return tp;
4120   }
4121
4122   private boolean buildingMenu = false;
4123
4124   /**
4125    * Generates menu items and listener event actions for web service clients
4126    * 
4127    */
4128   public void BuildWebServiceMenu()
4129   {
4130     while (buildingMenu)
4131     {
4132       try
4133       {
4134         System.err.println("Waiting for building menu to finish.");
4135         Thread.sleep(10);
4136       } catch (Exception e)
4137       {
4138       }
4139     }
4140     final AlignFrame me = this;
4141     buildingMenu = true;
4142     new Thread(new Runnable()
4143     {
4144       @Override
4145       public void run()
4146       {
4147         final List<JMenuItem> legacyItems = new ArrayList<>();
4148         try
4149         {
4150           // System.err.println("Building ws menu again "
4151           // + Thread.currentThread());
4152           // TODO: add support for context dependent disabling of services based
4153           // on
4154           // alignment and current selection
4155           // TODO: add additional serviceHandle parameter to specify abstract
4156           // handler
4157           // class independently of AbstractName
4158           // TODO: add in rediscovery GUI function to restart discoverer
4159           // TODO: group services by location as well as function and/or
4160           // introduce
4161           // object broker mechanism.
4162           final Vector<JMenu> wsmenu = new Vector<>();
4163           final IProgressIndicator af = me;
4164
4165           /*
4166            * do not i18n these strings - they are hard-coded in class
4167            * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4168            * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4169            */
4170           final JMenu msawsmenu = new JMenu("Alignment");
4171           final JMenu secstrmenu = new JMenu(
4172                   "Secondary Structure Prediction");
4173           final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4174           final JMenu analymenu = new JMenu("Analysis");
4175           final JMenu dismenu = new JMenu("Protein Disorder");
4176           // JAL-940 - only show secondary structure prediction services from
4177           // the legacy server
4178           Hashtable<String, Vector<ServiceHandle>> services = Discoverer
4179                   .getInstance().getServices();
4180           if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4181           // &&
4182           services != null && (services.size() > 0))
4183           {
4184             // TODO: refactor to allow list of AbstractName/Handler bindings to
4185             // be
4186             // stored or retrieved from elsewhere
4187             // No MSAWS used any more:
4188             // Vector msaws = null; // (Vector)
4189             // Discoverer.services.get("MsaWS");
4190             Vector<ServiceHandle> secstrpr = services.get("SecStrPred");
4191             if (secstrpr != null)
4192             {
4193               // Add any secondary structure prediction services
4194               for (int i = 0, j = secstrpr.size(); i < j; i++)
4195               {
4196                 final ext.vamsas.ServiceHandle sh = secstrpr
4197                         .get(i);
4198                 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4199                         .getServiceClient(sh);
4200                 int p = secstrmenu.getItemCount();
4201                 impl.attachWSMenuEntry(secstrmenu, me);
4202                 int q = secstrmenu.getItemCount();
4203                 for (int litm = p; litm < q; litm++)
4204                 {
4205                   legacyItems.add(secstrmenu.getItem(litm));
4206                 }
4207               }
4208             }
4209           }
4210
4211           // Add all submenus in the order they should appear on the web
4212           // services menu
4213           wsmenu.add(msawsmenu);
4214           wsmenu.add(secstrmenu);
4215           wsmenu.add(dismenu);
4216           wsmenu.add(analymenu);
4217           // No search services yet
4218           // wsmenu.add(seqsrchmenu);
4219
4220           javax.swing.SwingUtilities.invokeLater(new Runnable()
4221           {
4222             @Override
4223             public void run()
4224             {
4225               try
4226               {
4227                 webService.removeAll();
4228                 // first, add discovered services onto the webservices menu
4229                 if (wsmenu.size() > 0)
4230                 {
4231                   for (int i = 0, j = wsmenu.size(); i < j; i++)
4232                   {
4233                     webService.add(wsmenu.get(i));
4234                   }
4235                 }
4236                 else
4237                 {
4238                   webService.add(me.webServiceNoServices);
4239                 }
4240                 // TODO: move into separate menu builder class.
4241                 // boolean new_sspred = false;
4242                 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4243                 {
4244                   Jws2Discoverer jws2servs = Jws2Discoverer.getInstance();
4245                   if (jws2servs != null)
4246                   {
4247                     if (jws2servs.hasServices())
4248                     {
4249                       jws2servs.attachWSMenuEntry(webService, me);
4250                       for (Jws2Instance sv : jws2servs.getServices())
4251                       {
4252                         if (sv.description.toLowerCase().contains("jpred"))
4253                         {
4254                           for (JMenuItem jmi : legacyItems)
4255                           {
4256                             jmi.setVisible(false);
4257                           }
4258                         }
4259                       }
4260
4261                     }
4262                     if (jws2servs.isRunning())
4263                     {
4264                       JMenuItem tm = new JMenuItem(
4265                               "Still discovering JABA Services");
4266                       tm.setEnabled(false);
4267                       webService.add(tm);
4268                     }
4269                   }
4270                 }
4271                 build_urlServiceMenu(me.webService);
4272                 build_fetchdbmenu(webService);
4273                 for (JMenu item : wsmenu)
4274                 {
4275                   if (item.getItemCount() == 0)
4276                   {
4277                     item.setEnabled(false);
4278                   }
4279                   else
4280                   {
4281                     item.setEnabled(true);
4282                   }
4283                 }
4284               } catch (Exception e)
4285               {
4286                 Cache.log.debug(
4287                         "Exception during web service menu building process.",
4288                         e);
4289               }
4290             }
4291           });
4292         } catch (Exception e)
4293         {
4294         }
4295         buildingMenu = false;
4296       }
4297     }).start();
4298
4299   }
4300
4301   /**
4302    * construct any groupURL type service menu entries.
4303    * 
4304    * @param webService
4305    */
4306   protected void build_urlServiceMenu(JMenu webService)
4307   {
4308     // TODO: remove this code when 2.7 is released
4309     // DEBUG - alignmentView
4310     /*
4311      * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4312      * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4313      * 
4314      * @Override public void actionPerformed(ActionEvent e) {
4315      * jalview.datamodel.AlignmentView
4316      * .testSelectionViews(af.viewport.getAlignment(),
4317      * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4318      * 
4319      * }); webService.add(testAlView);
4320      */
4321     // TODO: refactor to RestClient discoverer and merge menu entries for
4322     // rest-style services with other types of analysis/calculation service
4323     // SHmmr test client - still being implemented.
4324     // DEBUG - alignmentView
4325
4326     for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4327             .getRestClients())
4328     {
4329       client.attachWSMenuEntry(
4330               JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4331               this);
4332     }
4333   }
4334
4335   /**
4336    * Searches the alignment sequences for xRefs and builds the Show
4337    * Cross-References menu (formerly called Show Products), with database
4338    * sources for which cross-references are found (protein sources for a
4339    * nucleotide alignment and vice versa)
4340    * 
4341    * @return true if Show Cross-references menu should be enabled
4342    */
4343   public boolean canShowProducts()
4344   {
4345     SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4346     AlignmentI dataset = viewport.getAlignment().getDataset();
4347
4348     showProducts.removeAll();
4349     final boolean dna = viewport.getAlignment().isNucleotide();
4350
4351     if (seqs == null || seqs.length == 0)
4352     {
4353       // nothing to see here.
4354       return false;
4355     }
4356
4357     boolean showp = false;
4358     try
4359     {
4360       List<String> ptypes = new CrossRef(seqs, dataset)
4361               .findXrefSourcesForSequences(dna);
4362
4363       for (final String source : ptypes)
4364       {
4365         showp = true;
4366         final AlignFrame af = this;
4367         JMenuItem xtype = new JMenuItem(source);
4368         xtype.addActionListener(new ActionListener()
4369         {
4370           @Override
4371           public void actionPerformed(ActionEvent e)
4372           {
4373             showProductsFor(af.viewport.getSequenceSelection(), dna,
4374                     source);
4375           }
4376         });
4377         showProducts.add(xtype);
4378       }
4379       showProducts.setVisible(showp);
4380       showProducts.setEnabled(showp);
4381     } catch (Exception e)
4382     {
4383       Cache.log.warn(
4384               "canShowProducts threw an exception - please report to help@jalview.org",
4385               e);
4386       return false;
4387     }
4388     return showp;
4389   }
4390
4391   /**
4392    * Finds and displays cross-references for the selected sequences (protein
4393    * products for nucleotide sequences, dna coding sequences for peptides).
4394    * 
4395    * @param sel
4396    *          the sequences to show cross-references for
4397    * @param dna
4398    *          true if from a nucleotide alignment (so showing proteins)
4399    * @param source
4400    *          the database to show cross-references for
4401    */
4402   protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4403           final String source)
4404   {
4405     new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4406             .start();
4407   }
4408
4409   /**
4410    * Construct and display a new frame containing the translation of this
4411    * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4412    */
4413   @Override
4414   public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4415   {
4416     AlignmentI al = null;
4417     try
4418     {
4419       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4420
4421       al = dna.translateCdna(codeTable);
4422     } catch (Exception ex)
4423     {
4424       jalview.bin.Cache.log.error(
4425               "Exception during translation. Please report this !", ex);
4426       final String msg = MessageManager.getString(
4427               "label.error_when_translating_sequences_submit_bug_report");
4428       final String errorTitle = MessageManager
4429               .getString("label.implementation_error")
4430               + MessageManager.getString("label.translation_failed");
4431       JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg, errorTitle,
4432               JvOptionPane.ERROR_MESSAGE);
4433       return;
4434     }
4435     if (al == null || al.getHeight() == 0)
4436     {
4437       final String msg = MessageManager.getString(
4438               "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4439       final String errorTitle = MessageManager
4440               .getString("label.translation_failed");
4441       JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg, errorTitle,
4442               JvOptionPane.WARNING_MESSAGE);
4443     }
4444     else
4445     {
4446       AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4447       af.setFileFormat(this.currentFileFormat);
4448       final String newTitle = MessageManager
4449               .formatMessage("label.translation_of_params", new Object[]
4450               { this.getTitle(), codeTable.getId() });
4451       af.setTitle(newTitle);
4452       if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4453       {
4454         final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4455         AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4456       }
4457       else
4458       {
4459         Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4460                 DEFAULT_HEIGHT);
4461       }
4462     }
4463   }
4464
4465   /**
4466    * Set the file format
4467    * 
4468    * @param format
4469    */
4470   public void setFileFormat(FileFormatI format)
4471   {
4472     this.currentFileFormat = format;
4473   }
4474
4475   /**
4476    * Try to load a features file onto the alignment.
4477    * 
4478    * @param file
4479    *          contents or path to retrieve file or a File object
4480    * @param sourceType
4481    *          access mode of file (see jalview.io.AlignFile)
4482    * @return true if features file was parsed correctly.
4483    */
4484   public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4485   {
4486     // BH 2018
4487     return avc.parseFeaturesFile(file, sourceType,
4488             Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4489
4490   }
4491
4492   @Override
4493   public void refreshFeatureUI(boolean enableIfNecessary)
4494   {
4495     // note - currently this is only still here rather than in the controller
4496     // because of the featureSettings hard reference that is yet to be
4497     // abstracted
4498     if (enableIfNecessary)
4499     {
4500       viewport.setShowSequenceFeatures(true);
4501       showSeqFeatures.setSelected(true);
4502     }
4503
4504   }
4505
4506   @Override
4507   public void dragEnter(DropTargetDragEvent evt)
4508   {
4509   }
4510
4511   @Override
4512   public void dragExit(DropTargetEvent evt)
4513   {
4514   }
4515
4516   @Override
4517   public void dragOver(DropTargetDragEvent evt)
4518   {
4519   }
4520
4521   @Override
4522   public void dropActionChanged(DropTargetDragEvent evt)
4523   {
4524   }
4525
4526   @Override
4527   public void drop(DropTargetDropEvent evt)
4528   {
4529     // JAL-1552 - acceptDrop required before getTransferable call for
4530     // Java's Transferable for native dnd
4531     evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4532     Transferable t = evt.getTransferable();
4533
4534     final AlignFrame thisaf = this;
4535     final List<Object> files = new ArrayList<>();
4536     List<DataSourceType> protocols = new ArrayList<>();
4537
4538     try
4539     {
4540       Desktop.transferFromDropTarget(files, protocols, evt, t);
4541     } catch (Exception e)
4542     {
4543       e.printStackTrace();
4544     }
4545     if (files != null)
4546     {
4547       new Thread(new Runnable()
4548       {
4549         @Override
4550         public void run()
4551         {
4552           try
4553           {
4554             // check to see if any of these files have names matching sequences
4555             // in
4556             // the alignment
4557             SequenceIdMatcher idm = new SequenceIdMatcher(
4558                     viewport.getAlignment().getSequencesArray());
4559             /**
4560              * Object[] { String,SequenceI}
4561              */
4562             ArrayList<Object[]> filesmatched = new ArrayList<>();
4563             ArrayList<Object> filesnotmatched = new ArrayList<>();
4564             for (int i = 0; i < files.size(); i++)
4565             {
4566               // BH 2018
4567               Object file = files.get(i);
4568               String fileName = file.toString();
4569               String pdbfn = "";
4570               DataSourceType protocol = (file instanceof File
4571                       ? DataSourceType.FILE
4572                       : FormatAdapter.checkProtocol(fileName));
4573               if (protocol == DataSourceType.FILE)
4574               {
4575                 File fl;
4576                 if (file instanceof File) {
4577                   fl = (File) file;
4578                   Platform.cacheFileData(fl);
4579                 } else {
4580                   fl = new File(fileName);
4581                 }
4582                 pdbfn = fl.getName();
4583               }
4584               else if (protocol == DataSourceType.URL)
4585               {
4586                 URL url = new URL(fileName);
4587                 pdbfn = url.getFile();
4588               }
4589               if (pdbfn.length() > 0)
4590               {
4591                 // attempt to find a match in the alignment
4592                 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4593                 int l = 0, c = pdbfn.indexOf(".");
4594                 while (mtch == null && c != -1)
4595                 {
4596                   do
4597                   {
4598                     l = c;
4599                   } while ((c = pdbfn.indexOf(".", l)) > l);
4600                   if (l > -1)
4601                   {
4602                     pdbfn = pdbfn.substring(0, l);
4603                   }
4604                   mtch = idm.findAllIdMatches(pdbfn);
4605                 }
4606                 if (mtch != null)
4607                 {
4608                   FileFormatI type;
4609                   try
4610                   {
4611                     type = new IdentifyFile().identify(file, protocol);
4612                   } catch (Exception ex)
4613                   {
4614                     type = null;
4615                   }
4616                   if (type != null && type.isStructureFile())
4617                   {
4618                     filesmatched.add(new Object[] { file, protocol, mtch });
4619                     continue;
4620                   }
4621                 }
4622                 // File wasn't named like one of the sequences or wasn't a PDB
4623                 // file.
4624                 filesnotmatched.add(file);
4625               }
4626             }
4627             int assocfiles = 0;
4628             if (filesmatched.size() > 0)
4629             {
4630               boolean autoAssociate = Cache
4631                       .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
4632               if (!autoAssociate)
4633               {
4634                 String msg = MessageManager.formatMessage(
4635                         "label.automatically_associate_structure_files_with_sequences_same_name",
4636                         new Object[]
4637                         { Integer.valueOf(filesmatched.size())
4638                                 .toString() });
4639                 String ttl = MessageManager.getString(
4640                         "label.automatically_associate_structure_files_by_name");
4641                 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4642                         ttl, JvOptionPane.YES_NO_OPTION);
4643                 autoAssociate = choice == JvOptionPane.YES_OPTION;
4644               }
4645               if (autoAssociate)
4646               {
4647                 for (Object[] fm : filesmatched)
4648                 {
4649                   // try and associate
4650                   // TODO: may want to set a standard ID naming formalism for
4651                   // associating PDB files which have no IDs.
4652                   for (SequenceI toassoc : (SequenceI[]) fm[2])
4653                   {
4654                     PDBEntry pe = AssociatePdbFileWithSeq
4655                             .associatePdbWithSeq(fm[0].toString(),
4656                                     (DataSourceType) fm[1], toassoc, false);
4657                     if (pe != null)
4658                     {
4659                       System.err.println("Associated file : "
4660                               + (fm[0].toString()) + " with "
4661                               + toassoc.getDisplayId(true));
4662                       assocfiles++;
4663                     }
4664                   }
4665                   // TODO: do we need to update overview ? only if features are
4666                   // shown I guess
4667                   alignPanel.paintAlignment(true, false);
4668                 }
4669               }
4670               else
4671               {
4672                 /*
4673                  * add declined structures as sequences
4674                  */
4675                 for (Object[] o : filesmatched)
4676                 {
4677                   filesnotmatched.add(o[0]);
4678                 }
4679               }
4680             }
4681             if (filesnotmatched.size() > 0)
4682             {
4683               if (assocfiles > 0 && (Cache.getDefault(
4684                       "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4685                       || JvOptionPane.showConfirmDialog(thisaf,
4686                               "<html>" + MessageManager.formatMessage(
4687                                       "label.ignore_unmatched_dropped_files_info",
4688                                       new Object[]
4689                                       { Integer.valueOf(
4690                                               filesnotmatched.size())
4691                                               .toString() })
4692                                       + "</html>",
4693                               MessageManager.getString(
4694                                       "label.ignore_unmatched_dropped_files"),
4695                               JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4696               {
4697                 return;
4698               }
4699               for (Object fn : filesnotmatched)
4700               {
4701                 loadJalviewDataFile(fn, null, null, null);
4702               }
4703
4704             }
4705           } catch (Exception ex)
4706           {
4707             ex.printStackTrace();
4708           }
4709         }
4710       }).start();
4711     }
4712   }
4713
4714   /**
4715    * Attempt to load a "dropped" file or URL string, by testing in turn for
4716    * <ul>
4717    * <li>an Annotation file</li>
4718    * <li>a JNet file</li>
4719    * <li>a features file</li>
4720    * <li>else try to interpret as an alignment file</li>
4721    * </ul>
4722    * 
4723    * @param file
4724    *          either a filename or a URL string.
4725    */
4726   public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4727           FileFormatI format, SequenceI assocSeq)
4728   {
4729     // BH 2018 was String file
4730     try
4731     {
4732       if (sourceType == null)
4733       {
4734         sourceType = FormatAdapter.checkProtocol(file);
4735       }
4736       // if the file isn't identified, or not positively identified as some
4737       // other filetype (PFAM is default unidentified alignment file type) then
4738       // try to parse as annotation.
4739       boolean isAnnotation = (format == null
4740               || FileFormat.Pfam.equals(format))
4741                       ? new AnnotationFile().annotateAlignmentView(viewport,
4742                               file, sourceType)
4743                       : false;
4744
4745       if (!isAnnotation)
4746       {
4747         // first see if its a T-COFFEE score file
4748         TCoffeeScoreFile tcf = null;
4749         try
4750         {
4751           tcf = new TCoffeeScoreFile(file, sourceType);
4752           if (tcf.isValid())
4753           {
4754             if (tcf.annotateAlignment(viewport.getAlignment(), true))
4755             {
4756               buildColourMenu();
4757               changeColour(
4758                       new TCoffeeColourScheme(viewport.getAlignment()));
4759               isAnnotation = true;
4760               setStatus(MessageManager.getString(
4761                       "label.successfully_pasted_tcoffee_scores_to_alignment"));
4762             }
4763             else
4764             {
4765               // some problem - if no warning its probable that the ID matching
4766               // process didn't work
4767               JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4768                       tcf.getWarningMessage() == null
4769                               ? MessageManager.getString(
4770                                       "label.check_file_matches_sequence_ids_alignment")
4771                               : tcf.getWarningMessage(),
4772                       MessageManager.getString(
4773                               "label.problem_reading_tcoffee_score_file"),
4774                       JvOptionPane.WARNING_MESSAGE);
4775             }
4776           }
4777           else
4778           {
4779             tcf = null;
4780           }
4781         } catch (Exception x)
4782         {
4783           Cache.log.debug(
4784                   "Exception when processing data source as T-COFFEE score file",
4785                   x);
4786           tcf = null;
4787         }
4788         if (tcf == null)
4789         {
4790           // try to see if its a JNet 'concise' style annotation file *before*
4791           // we
4792           // try to parse it as a features file
4793           if (format == null)
4794           {
4795             format = new IdentifyFile().identify(file, sourceType);
4796           }
4797           if (FileFormat.ScoreMatrix == format)
4798           {
4799             ScoreMatrixFile sm = new ScoreMatrixFile(
4800                     new FileParse(file, sourceType));
4801             sm.parse();
4802             // todo: i18n this message
4803             setStatus(MessageManager.formatMessage(
4804                     "label.successfully_loaded_matrix",
4805                     sm.getMatrixName()));
4806           }
4807           else if (FileFormat.Jnet.equals(format))
4808           {
4809             JPredFile predictions = new JPredFile(file, sourceType);
4810             new JnetAnnotationMaker();
4811             JnetAnnotationMaker.add_annotation(predictions,
4812                     viewport.getAlignment(), 0, false);
4813             viewport.getAlignment().setupJPredAlignment();
4814             isAnnotation = true;
4815           }
4816           // else if (IdentifyFile.FeaturesFile.equals(format))
4817           else if (FileFormat.Features.equals(format))
4818           {
4819             if (parseFeaturesFile(file, sourceType))
4820             {
4821               alignPanel.paintAlignment(true, true);
4822             }
4823           }
4824           else
4825           {
4826             new FileLoader().loadFile(viewport, file, sourceType, format);
4827           }
4828         }
4829       }
4830       if (isAnnotation)
4831       {
4832         updateForAnnotations();
4833       }
4834     } catch (Exception ex)
4835     {
4836       ex.printStackTrace();
4837     } catch (OutOfMemoryError oom)
4838     {
4839       try
4840       {
4841         System.gc();
4842       } catch (Exception x)
4843       {
4844       }
4845       new OOMWarning(
4846               "loading data "
4847                       + (sourceType != null
4848                               ? (sourceType == DataSourceType.PASTE
4849                                       ? "from clipboard."
4850                                       : "using " + sourceType + " from "
4851                                               + file)
4852                               : ".")
4853                       + (format != null
4854                               ? "(parsing as '" + format + "' file)"
4855                               : ""),
4856               oom, Desktop.getDesktopPane());
4857     }
4858   }
4859
4860   /**
4861    * Do all updates necessary after an annotation file such as jnet. Also called
4862    * from Jalview.loadAppletParams for "annotations", "jnetFile"
4863    */
4864   public void updateForAnnotations()
4865   {
4866     alignPanel.adjustAnnotationHeight();
4867     viewport.updateSequenceIdColours();
4868     buildSortByAnnotationScoresMenu();
4869     alignPanel.paintAlignment(true, true);
4870   }
4871
4872   /**
4873    * Method invoked by the ChangeListener on the tabbed pane, in other words
4874    * when a different tabbed pane is selected by the user or programmatically.
4875    */
4876   @Override
4877   public void tabSelectionChanged(int index)
4878   {
4879     if (index > -1)
4880     {
4881       alignPanel = alignPanels.get(index);
4882       viewport = alignPanel.av;
4883       avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4884       setMenusFromViewport(viewport);
4885     }
4886
4887     /*
4888      * 'focus' any colour slider that is open to the selected viewport
4889      */
4890     if (viewport.getConservationSelected())
4891     {
4892       SliderPanel.setConservationSlider(alignPanel,
4893               viewport.getResidueShading(), alignPanel.getViewName());
4894     }
4895     else
4896     {
4897       SliderPanel.hideConservationSlider();
4898     }
4899     if (viewport.getAbovePIDThreshold())
4900     {
4901       SliderPanel.setPIDSliderSource(alignPanel,
4902               viewport.getResidueShading(), alignPanel.getViewName());
4903     }
4904     else
4905     {
4906       SliderPanel.hidePIDSlider();
4907     }
4908
4909     /*
4910      * If there is a frame linked to this one in a SplitPane, switch it to the
4911      * same view tab index. No infinite recursion of calls should happen, since
4912      * tabSelectionChanged() should not get invoked on setting the selected
4913      * index to an unchanged value. Guard against setting an invalid index
4914      * before the new view peer tab has been created.
4915      */
4916     final AlignViewportI peer = viewport.getCodingComplement();
4917     if (peer != null)
4918     {
4919       AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4920               .getAlignPanel().alignFrame;
4921       if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4922       {
4923         linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4924       }
4925     }
4926   }
4927
4928   /**
4929    * On right mouse click on view tab, prompt for and set new view name.
4930    */
4931   @Override
4932   public void tabbedPane_mousePressed(MouseEvent e)
4933   {
4934     if (e.isPopupTrigger())
4935     {
4936       String msg = MessageManager.getString("label.enter_view_name");
4937       String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4938       String reply = JvOptionPane.showInputDialog(msg, ttl);
4939
4940       if (reply != null)
4941       {
4942         viewport.setViewName(reply);
4943         // TODO warn if reply is in getExistingViewNames()?
4944         tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4945       }
4946     }
4947   }
4948
4949   public AlignViewport getCurrentView()
4950   {
4951     return viewport;
4952   }
4953
4954   /**
4955    * Change the display state for the given feature groups -- Added by BH from
4956    * JalviewLite
4957    * 
4958    * @param groups
4959    *          list of group strings
4960    * @param state
4961    *          visible or invisible
4962    */
4963   public void setFeatureGroupState(String[] groups, boolean state)
4964   {
4965     jalview.api.FeatureRenderer fr = null;
4966     viewport.setShowSequenceFeatures(true);
4967     if (alignPanel != null
4968             && (fr = alignPanel.getFeatureRenderer()) != null)
4969     {
4970
4971       fr.setGroupVisibility(Arrays.asList(groups), state);
4972       alignPanel.getSeqPanel().seqCanvas.repaint();
4973       if (alignPanel.overviewPanel != null)
4974       {
4975         alignPanel.overviewPanel.updateOverviewImage();
4976       }
4977     }
4978   }
4979
4980   /**
4981    * Open the dialog for regex description parsing.
4982    */
4983   @Override
4984   protected void extractScores_actionPerformed(ActionEvent e)
4985   {
4986     ParseProperties pp = new jalview.analysis.ParseProperties(
4987             viewport.getAlignment());
4988     // TODO: verify regex and introduce GUI dialog for version 2.5
4989     // if (pp.getScoresFromDescription("col", "score column ",
4990     // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4991     // true)>0)
4992     if (pp.getScoresFromDescription("description column",
4993             "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4994     {
4995       buildSortByAnnotationScoresMenu();
4996     }
4997   }
4998
4999   /*
5000    * (non-Javadoc)
5001    * 
5002    * @see
5003    * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5004    * )
5005    */
5006   @Override
5007   protected void showDbRefs_actionPerformed(ActionEvent e)
5008   {
5009     viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5010   }
5011
5012   /*
5013    * (non-Javadoc)
5014    * 
5015    * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5016    * ActionEvent)
5017    */
5018   @Override
5019   protected void showNpFeats_actionPerformed(ActionEvent e)
5020   {
5021     viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5022   }
5023
5024   /**
5025    * find the viewport amongst the tabs in this alignment frame and close that
5026    * tab
5027    * 
5028    * @param av
5029    */
5030   public boolean closeView(AlignViewportI av)
5031   {
5032     if (viewport == av)
5033     {
5034       this.closeMenuItem_actionPerformed(false);
5035       return true;
5036     }
5037     Component[] comp = tabbedPane.getComponents();
5038     for (int i = 0; comp != null && i < comp.length; i++)
5039     {
5040       if (comp[i] instanceof AlignmentPanel)
5041       {
5042         if (((AlignmentPanel) comp[i]).av == av)
5043         {
5044           // close the view.
5045           closeView((AlignmentPanel) comp[i]);
5046           return true;
5047         }
5048       }
5049     }
5050     return false;
5051   }
5052
5053   protected void build_fetchdbmenu(JMenu webService)
5054   {
5055     // Temporary hack - DBRef Fetcher always top level ws entry.
5056     // TODO We probably want to store a sequence database checklist in
5057     // preferences and have checkboxes.. rather than individual sources selected
5058     // here
5059     final JMenu rfetch = new JMenu(
5060             MessageManager.getString("action.fetch_db_references"));
5061     rfetch.setToolTipText(MessageManager.getString(
5062             "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5063     webService.add(rfetch);
5064
5065     final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5066             MessageManager.getString("option.trim_retrieved_seqs"));
5067     trimrs.setToolTipText(
5068             MessageManager.getString("label.trim_retrieved_sequences"));
5069     trimrs.setSelected(
5070             Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5071     trimrs.addActionListener(new ActionListener()
5072     {
5073       @Override
5074       public void actionPerformed(ActionEvent e)
5075       {
5076         trimrs.setSelected(trimrs.isSelected());
5077         Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5078                 Boolean.valueOf(trimrs.isSelected()).toString());
5079       }
5080     });
5081     rfetch.add(trimrs);
5082     JMenuItem fetchr = new JMenuItem(
5083             MessageManager.getString("label.standard_databases"));
5084     fetchr.setToolTipText(
5085             MessageManager.getString("label.fetch_embl_uniprot"));
5086     fetchr.addActionListener(new ActionListener()
5087     {
5088
5089       @Override
5090       public void actionPerformed(ActionEvent e)
5091       {
5092         new Thread(new Runnable()
5093         {
5094           @Override
5095           public void run()
5096           {
5097             boolean isNucleotide = alignPanel.alignFrame.getViewport()
5098                     .getAlignment().isNucleotide();
5099             DBRefFetcher dbRefFetcher = new DBRefFetcher(
5100                     alignPanel.av.getSequenceSelection(),
5101                     alignPanel.alignFrame, null,
5102                     alignPanel.alignFrame.featureSettings, isNucleotide);
5103             dbRefFetcher.addListener(new FetchFinishedListenerI()
5104             {
5105               @Override
5106               public void finished()
5107               {
5108                 AlignFrame.this.setMenusForViewport();
5109               }
5110             });
5111             dbRefFetcher.fetchDBRefs(false);
5112           }
5113         }).start();
5114
5115       }
5116
5117     });
5118     rfetch.add(fetchr);
5119     new Thread(new Runnable()
5120     {
5121       @Override
5122       public void run()
5123       {
5124         javax.swing.SwingUtilities.invokeLater(new Runnable()
5125         {
5126           @Override
5127           public void run()
5128           {
5129             String[] dbclasses = jalview.ws.SequenceFetcher.getInstance()
5130                     .getNonAlignmentSources();
5131             List<DbSourceProxy> otherdb;
5132             JMenu dfetch = new JMenu();
5133             JMenu ifetch = new JMenu();
5134             JMenuItem fetchr = null;
5135             int comp = 0, icomp = 0, mcomp = 15;
5136             String mname = null;
5137             int dbi = 0;
5138             for (String dbclass : dbclasses)
5139             {
5140               otherdb = jalview.ws.SequenceFetcher.getInstance()
5141                       .getSourceProxy(dbclass);
5142               // add a single entry for this class, or submenu allowing 'fetch
5143               // all' or pick one
5144               if (otherdb == null || otherdb.size() < 1)
5145               {
5146                 continue;
5147               }
5148               if (mname == null)
5149               {
5150                 mname = "From " + dbclass;
5151               }
5152               if (otherdb.size() == 1)
5153               {
5154                 DbSourceProxy src = otherdb.get(0);
5155                 DbSourceProxy[] dassource = new DbSourceProxy[] {
5156                     src };
5157                 fetchr = new JMenuItem(src.getDbSource());
5158                 fetchr.addActionListener(new ActionListener()
5159                 {
5160
5161                   @Override
5162                   public void actionPerformed(ActionEvent e)
5163                   {
5164                     new Thread(new Runnable()
5165                     {
5166
5167                       @Override
5168                       public void run()
5169                       {
5170                         boolean isNucleotide = alignPanel.alignFrame
5171                                 .getViewport().getAlignment()
5172                                 .isNucleotide();
5173                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5174                                 alignPanel.av.getSequenceSelection(),
5175                                 alignPanel.alignFrame, dassource,
5176                                 alignPanel.alignFrame.featureSettings,
5177                                 isNucleotide);
5178                         dbRefFetcher
5179                                 .addListener(new FetchFinishedListenerI()
5180                                 {
5181                                   @Override
5182                                   public void finished()
5183                                   {
5184                                     AlignFrame.this.setMenusForViewport();
5185                                   }
5186                                 });
5187                         dbRefFetcher.fetchDBRefs(false);
5188                       }
5189                     }).start();
5190                   }
5191
5192                 });
5193                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5194                         MessageManager.formatMessage(
5195                                 "label.fetch_retrieve_from", new Object[]
5196                                 { src.getDbName() })));
5197                 dfetch.add(fetchr);
5198                 comp++;
5199               }
5200               else
5201               {
5202                 final DbSourceProxy[] dassource = otherdb
5203                         .toArray(new DbSourceProxy[0]);
5204                 // fetch all entry
5205                 DbSourceProxy src = otherdb.get(0);
5206                 fetchr = new JMenuItem(MessageManager
5207                         .formatMessage("label.fetch_all_param", new Object[]
5208                         { src.getDbSource() }));
5209                 fetchr.addActionListener(new ActionListener()
5210                 {
5211                   @Override
5212                   public void actionPerformed(ActionEvent e)
5213                   {
5214                     new Thread(new Runnable()
5215                     {
5216
5217                       @Override
5218                       public void run()
5219                       {
5220                         boolean isNucleotide = alignPanel.alignFrame
5221                                 .getViewport().getAlignment()
5222                                 .isNucleotide();
5223                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5224                                 alignPanel.av.getSequenceSelection(),
5225                                 alignPanel.alignFrame, dassource,
5226                                 alignPanel.alignFrame.featureSettings,
5227                                 isNucleotide);
5228                         dbRefFetcher
5229                                 .addListener(new FetchFinishedListenerI()
5230                                 {
5231                                   @Override
5232                                   public void finished()
5233                                   {
5234                                     AlignFrame.this.setMenusForViewport();
5235                                   }
5236                                 });
5237                         dbRefFetcher.fetchDBRefs(false);
5238                       }
5239                     }).start();
5240                   }
5241                 });
5242
5243                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5244                         MessageManager.formatMessage(
5245                                 "label.fetch_retrieve_from_all_sources",
5246                                 new Object[]
5247                                 { Integer.valueOf(otherdb.size())
5248                                         .toString(),
5249                                     src.getDbSource(), src.getDbName() })));
5250                 dfetch.add(fetchr);
5251                 comp++;
5252                 // and then build the rest of the individual menus
5253                 ifetch = new JMenu(MessageManager.formatMessage(
5254                         "label.source_from_db_source", new Object[]
5255                         { src.getDbSource() }));
5256                 icomp = 0;
5257                 String imname = null;
5258                 int i = 0;
5259                 for (DbSourceProxy sproxy : otherdb)
5260                 {
5261                   String dbname = sproxy.getDbName();
5262                   String sname = dbname.length() > 5
5263                           ? dbname.substring(0, 5) + "..."
5264                           : dbname;
5265                   String msname = dbname.length() > 10
5266                           ? dbname.substring(0, 10) + "..."
5267                           : dbname;
5268                   if (imname == null)
5269                   {
5270                     imname = MessageManager
5271                             .formatMessage("label.from_msname", new Object[]
5272                             { sname });
5273                   }
5274                   fetchr = new JMenuItem(msname);
5275                   final DbSourceProxy[] dassrc = { sproxy };
5276                   fetchr.addActionListener(new ActionListener()
5277                   {
5278
5279                     @Override
5280                     public void actionPerformed(ActionEvent e)
5281                     {
5282                       new Thread(new Runnable()
5283                       {
5284
5285                         @Override
5286                         public void run()
5287                         {
5288                           boolean isNucleotide = alignPanel.alignFrame
5289                                   .getViewport().getAlignment()
5290                                   .isNucleotide();
5291                           DBRefFetcher dbRefFetcher = new DBRefFetcher(
5292                                   alignPanel.av.getSequenceSelection(),
5293                                   alignPanel.alignFrame, dassrc,
5294                                   alignPanel.alignFrame.featureSettings,
5295                                   isNucleotide);
5296                           dbRefFetcher
5297                                   .addListener(new FetchFinishedListenerI()
5298                                   {
5299                                     @Override
5300                                     public void finished()
5301                                     {
5302                                       AlignFrame.this.setMenusForViewport();
5303                                     }
5304                                   });
5305                           dbRefFetcher.fetchDBRefs(false);
5306                         }
5307                       }).start();
5308                     }
5309
5310                   });
5311                   fetchr.setToolTipText(
5312                           "<html>" + MessageManager.formatMessage(
5313                                   "label.fetch_retrieve_from", new Object[]
5314                                   { dbname }));
5315                   ifetch.add(fetchr);
5316                   ++i;
5317                   if (++icomp >= mcomp || i == (otherdb.size()))
5318                   {
5319                     ifetch.setText(MessageManager.formatMessage(
5320                             "label.source_to_target", imname, sname));
5321                     dfetch.add(ifetch);
5322                     ifetch = new JMenu();
5323                     imname = null;
5324                     icomp = 0;
5325                     comp++;
5326                   }
5327                 }
5328               }
5329               ++dbi;
5330               if (comp >= mcomp || dbi >= (dbclasses.length))
5331               {
5332                 dfetch.setText(MessageManager.formatMessage(
5333                         "label.source_to_target", mname, dbclass));
5334                 rfetch.add(dfetch);
5335                 dfetch = new JMenu();
5336                 mname = null;
5337                 comp = 0;
5338               }
5339             }
5340           }
5341         });
5342       }
5343     }).start();
5344
5345   }
5346
5347   /**
5348    * Left justify the whole alignment.
5349    */
5350   @Override
5351   protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5352   {
5353     AlignmentI al = viewport.getAlignment();
5354     al.justify(false);
5355     viewport.firePropertyChange("alignment", null, al);
5356   }
5357
5358   /**
5359    * Right justify the whole alignment.
5360    */
5361   @Override
5362   protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5363   {
5364     AlignmentI al = viewport.getAlignment();
5365     al.justify(true);
5366     viewport.firePropertyChange("alignment", null, al);
5367   }
5368
5369   @Override
5370   public void setShowSeqFeatures(boolean b)
5371   {
5372     showSeqFeatures.setSelected(b);
5373     viewport.setShowSequenceFeatures(b);
5374   }
5375
5376   /*
5377    * (non-Javadoc)
5378    * 
5379    * @see
5380    * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5381    * awt.event.ActionEvent)
5382    */
5383   @Override
5384   protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5385   {
5386     viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5387     alignPanel.paintAlignment(false, false);
5388   }
5389
5390   /*
5391    * (non-Javadoc)
5392    * 
5393    * @see
5394    * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5395    * .ActionEvent)
5396    */
5397   @Override
5398   protected void showGroupConsensus_actionPerformed(ActionEvent e)
5399   {
5400     viewport.setShowGroupConsensus(showGroupConsensus.getState());
5401     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5402
5403   }
5404
5405   /*
5406    * (non-Javadoc)
5407    * 
5408    * @see
5409    * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5410    * .event.ActionEvent)
5411    */
5412   @Override
5413   protected void showGroupConservation_actionPerformed(ActionEvent e)
5414   {
5415     viewport.setShowGroupConservation(showGroupConservation.getState());
5416     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5417   }
5418
5419   /*
5420    * (non-Javadoc)
5421    * 
5422    * @see
5423    * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5424    * .event.ActionEvent)
5425    */
5426   @Override
5427   protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5428   {
5429     viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5430     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5431   }
5432
5433   /*
5434    * (non-Javadoc)
5435    * 
5436    * @see
5437    * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5438    * .event.ActionEvent)
5439    */
5440   @Override
5441   protected void showSequenceLogo_actionPerformed(ActionEvent e)
5442   {
5443     viewport.setShowSequenceLogo(showSequenceLogo.getState());
5444     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5445   }
5446
5447   @Override
5448   protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5449   {
5450     showSequenceLogo.setState(true);
5451     viewport.setShowSequenceLogo(true);
5452     viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5453     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5454   }
5455
5456   @Override
5457   protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5458   {
5459     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5460   }
5461
5462   /*
5463    * (non-Javadoc)
5464    * 
5465    * @see
5466    * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5467    * .event.ActionEvent)
5468    */
5469   @Override
5470   protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5471   {
5472     if (avc.makeGroupsFromSelection())
5473     {
5474       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5475       alignPanel.updateAnnotation();
5476       alignPanel.paintAlignment(true,
5477               viewport.needToUpdateStructureViews());
5478     }
5479   }
5480
5481   public void clearAlignmentSeqRep()
5482   {
5483     // TODO refactor alignmentseqrep to controller
5484     if (viewport.getAlignment().hasSeqrep())
5485     {
5486       viewport.getAlignment().setSeqrep(null);
5487       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5488       alignPanel.updateAnnotation();
5489       alignPanel.paintAlignment(true, true);
5490     }
5491   }
5492
5493   @Override
5494   protected void createGroup_actionPerformed(ActionEvent e)
5495   {
5496     if (avc.createGroup())
5497     {
5498       if (applyAutoAnnotationSettings.isSelected())
5499       {
5500         alignPanel.updateAnnotation(true, false);
5501       }
5502       alignPanel.alignmentChanged();
5503     }
5504   }
5505
5506   @Override
5507   protected void unGroup_actionPerformed(ActionEvent e)
5508   {
5509     if (avc.unGroup())
5510     {
5511       alignPanel.alignmentChanged();
5512     }
5513   }
5514
5515   /**
5516    * make the given alignmentPanel the currently selected tab
5517    * 
5518    * @param alignmentPanel
5519    */
5520   public void setDisplayedView(AlignmentPanel alignmentPanel)
5521   {
5522     if (!viewport.getSequenceSetId()
5523             .equals(alignmentPanel.av.getSequenceSetId()))
5524     {
5525       throw new Error(MessageManager.getString(
5526               "error.implementation_error_cannot_show_view_alignment_frame"));
5527     }
5528     if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5529             .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5530     {
5531       tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5532     }
5533   }
5534
5535   /**
5536    * Action on selection of menu options to Show or Hide annotations.
5537    * 
5538    * @param visible
5539    * @param forSequences
5540    *          update sequence-related annotations
5541    * @param forAlignment
5542    *          update non-sequence-related annotations
5543    */
5544   @Override
5545   protected void setAnnotationsVisibility(boolean visible,
5546           boolean forSequences, boolean forAlignment)
5547   {
5548     AlignmentAnnotation[] anns = alignPanel.getAlignment()
5549             .getAlignmentAnnotation();
5550     if (anns == null)
5551     {
5552       return;
5553     }
5554     for (AlignmentAnnotation aa : anns)
5555     {
5556       /*
5557        * don't display non-positional annotations on an alignment
5558        */
5559       if (aa.annotations == null)
5560       {
5561         continue;
5562       }
5563       boolean apply = (aa.sequenceRef == null && forAlignment)
5564               || (aa.sequenceRef != null && forSequences);
5565       if (apply)
5566       {
5567         aa.visible = visible;
5568       }
5569     }
5570     alignPanel.validateAnnotationDimensions(true);
5571     alignPanel.alignmentChanged();
5572   }
5573
5574   /**
5575    * Store selected annotation sort order for the view and repaint.
5576    */
5577   @Override
5578   protected void sortAnnotations_actionPerformed()
5579   {
5580     this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5581     this.alignPanel.av
5582             .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5583     alignPanel.paintAlignment(false, false);
5584   }
5585
5586   /**
5587    * 
5588    * @return alignment panels in this alignment frame
5589    */
5590   public List<? extends AlignmentViewPanel> getAlignPanels()
5591   {
5592     // alignPanels is never null
5593     // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5594     return alignPanels;
5595   }
5596
5597   /**
5598    * Open a new alignment window, with the cDNA associated with this (protein)
5599    * alignment, aligned as is the protein.
5600    */
5601   protected void viewAsCdna_actionPerformed()
5602   {
5603     // TODO no longer a menu action - refactor as required
5604     final AlignmentI alignment = getViewport().getAlignment();
5605     List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5606     if (mappings == null)
5607     {
5608       return;
5609     }
5610     List<SequenceI> cdnaSeqs = new ArrayList<>();
5611     for (SequenceI aaSeq : alignment.getSequences())
5612     {
5613       for (AlignedCodonFrame acf : mappings)
5614       {
5615         SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5616         if (dnaSeq != null)
5617         {
5618           /*
5619            * There is a cDNA mapping for this protein sequence - add to new
5620            * alignment. It will share the same dataset sequence as other mapped
5621            * cDNA (no new mappings need to be created).
5622            */
5623           final Sequence newSeq = new Sequence(dnaSeq);
5624           newSeq.setDatasetSequence(dnaSeq);
5625           cdnaSeqs.add(newSeq);
5626         }
5627       }
5628     }
5629     if (cdnaSeqs.size() == 0)
5630     {
5631       // show a warning dialog no mapped cDNA
5632       return;
5633     }
5634     AlignmentI cdna = new Alignment(
5635             cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5636     GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5637             AlignFrame.DEFAULT_HEIGHT);
5638     cdna.alignAs(alignment);
5639     String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5640             + this.title;
5641     Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5642             AlignFrame.DEFAULT_HEIGHT);
5643   }
5644
5645   /**
5646    * Set visibility of dna/protein complement view (available when shown in a
5647    * split frame).
5648    * 
5649    * @param show
5650    */
5651   @Override
5652   protected void showComplement_actionPerformed(boolean show)
5653   {
5654     SplitContainerI sf = getSplitViewContainer();
5655     if (sf != null)
5656     {
5657       sf.setComplementVisible(this, show);
5658     }
5659   }
5660
5661   /**
5662    * Generate the reverse (optionally complemented) of the selected sequences,
5663    * and add them to the alignment
5664    */
5665   @Override
5666   protected void showReverse_actionPerformed(boolean complement)
5667   {
5668     AlignmentI al = null;
5669     try
5670     {
5671       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5672       al = dna.reverseCdna(complement);
5673       viewport.addAlignment(al, "");
5674       addHistoryItem(new EditCommand(
5675               MessageManager.getString("label.add_sequences"), Action.PASTE,
5676               al.getSequencesArray(), 0, al.getWidth(),
5677               viewport.getAlignment()));
5678     } catch (Exception ex)
5679     {
5680       System.err.println(ex.getMessage());
5681       return;
5682     }
5683   }
5684
5685   /**
5686    * Try to run a script in the Groovy console, having first ensured that this
5687    * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5688    * be targeted at this alignment.
5689    */
5690   @Override
5691   protected void runGroovy_actionPerformed()
5692   {
5693     Jalview.setCurrentAlignFrame(this);
5694     groovy.ui.Console console = Desktop.getGroovyConsole();
5695     if (console != null)
5696     {
5697       try
5698       {
5699         console.runScript();
5700       } catch (Exception ex)
5701       {
5702         System.err.println((ex.toString()));
5703         JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
5704                 MessageManager.getString("label.couldnt_run_groovy_script"),
5705                 MessageManager.getString("label.groovy_support_failed"),
5706                 JvOptionPane.ERROR_MESSAGE);
5707       }
5708     }
5709     else
5710     {
5711       System.err.println("Can't run Groovy script as console not found");
5712     }
5713   }
5714
5715   /**
5716    * Hides columns containing (or not containing) a specified feature, provided
5717    * that would not leave all columns hidden
5718    * 
5719    * @param featureType
5720    * @param columnsContaining
5721    * @return
5722    */
5723   public boolean hideFeatureColumns(String featureType,
5724           boolean columnsContaining)
5725   {
5726     boolean notForHiding = avc.markColumnsContainingFeatures(
5727             columnsContaining, false, false, featureType);
5728     if (notForHiding)
5729     {
5730       if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5731               false, featureType))
5732       {
5733         getViewport().hideSelectedColumns();
5734         return true;
5735       }
5736     }
5737     return false;
5738   }
5739
5740   @Override
5741   protected void selectHighlightedColumns_actionPerformed(
5742           ActionEvent actionEvent)
5743   {
5744     // include key modifier check in case user selects from menu
5745     avc.markHighlightedColumns(
5746             (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5747             (actionEvent.getModifiers() & (ActionEvent.META_MASK
5748                     | ActionEvent.CTRL_MASK)) != 0);
5749   }
5750
5751   /**
5752    * Rebuilds the Colour menu, including any user-defined colours which have
5753    * been loaded either on startup or during the session
5754    */
5755   public void buildColourMenu()
5756   {
5757     colourMenu.removeAll();
5758
5759     colourMenu.add(applyToAllGroups);
5760     colourMenu.add(textColour);
5761     colourMenu.addSeparator();
5762
5763     ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5764             viewport.getAlignment(), false);
5765
5766     colourMenu.add(annotationColour);
5767     bg.add(annotationColour);
5768     colourMenu.addSeparator();
5769     colourMenu.add(conservationMenuItem);
5770     colourMenu.add(modifyConservation);
5771     colourMenu.add(abovePIDThreshold);
5772     colourMenu.add(modifyPID);
5773
5774     ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5775     ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5776   }
5777
5778   /**
5779    * Open a dialog (if not already open) that allows the user to select and
5780    * calculate PCA or Tree analysis
5781    */
5782   protected void openTreePcaDialog()
5783   {
5784     if (alignPanel.getCalculationDialog() == null)
5785     {
5786       new CalculationChooser(AlignFrame.this);
5787     }
5788   }
5789
5790   @Override
5791   protected void loadVcf_actionPerformed()
5792   {
5793     JalviewFileChooser chooser = new JalviewFileChooser(
5794             Cache.getProperty("LAST_DIRECTORY"));
5795     chooser.setFileView(new JalviewFileView());
5796     chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5797     chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5798     final AlignFrame us = this;
5799     chooser.setResponseHandler(0, new Runnable()
5800     {
5801       @Override
5802       public void run()
5803       {
5804         String choice = chooser.getSelectedFile().getPath();
5805         Cache.setProperty("LAST_DIRECTORY", choice);
5806         SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5807         new VCFLoader(choice).loadVCF(seqs, us);
5808       }
5809     });
5810     chooser.showOpenDialog(null);
5811
5812   }
5813
5814   /**
5815    * BH 2019 from JalviewLite
5816    * 
5817    * get sequence feature groups that are hidden or shown
5818    * 
5819    * @param visible
5820    *          true is visible
5821    * @return list
5822    */
5823   public String[] getFeatureGroupsOfState(boolean visible)
5824   {
5825     jalview.api.FeatureRenderer fr = null;
5826     if (alignPanel != null
5827             && (fr = alignPanel
5828                     .getFeatureRenderer()) != null)
5829     {
5830       List<String> gps = fr.getGroups(visible);
5831       String[] _gps = gps.toArray(new String[gps.size()]);
5832       return _gps;
5833     }
5834     return null;
5835   }
5836
5837   public void scrollTo(int row, int column)
5838   {
5839     alignPanel.getSeqPanel().scrollTo(row, column);
5840   }
5841
5842   public void scrollToRow(int row)
5843   {
5844     alignPanel.getSeqPanel().scrollToRow(row);
5845   }
5846
5847   public void scrollToColumn(int column)
5848   {
5849     alignPanel.getSeqPanel().scrollToColumn(column);
5850   }
5851
5852   /**
5853    * 
5854    * @return list of feature groups on the view
5855    */
5856   public String[] getFeatureGroups()
5857   {
5858     jalview.api.FeatureRenderer fr = null;
5859     if (alignPanel != null
5860             && (fr = alignPanel.getFeatureRenderer()) != null)
5861     {
5862       List<String> gps = fr.getFeatureGroups();
5863       String[] _gps = gps.toArray(new String[gps.size()]);
5864       return _gps;
5865     }
5866     return null;
5867   }
5868
5869   public void select(SequenceGroup sel, ColumnSelection csel,
5870           HiddenColumns hidden)
5871   {
5872     alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
5873   }
5874
5875 }
5876
5877 class PrintThread extends Thread
5878 {
5879   AlignmentPanel ap;
5880
5881   public PrintThread(AlignmentPanel ap)
5882   {
5883     this.ap = ap;
5884   }
5885
5886   static PageFormat pf;
5887
5888   @Override
5889   public void run()
5890   {
5891     PrinterJob printJob = PrinterJob.getPrinterJob();
5892
5893     if (pf != null)
5894     {
5895       printJob.setPrintable(ap, pf);
5896     }
5897     else
5898     {
5899       printJob.setPrintable(ap);
5900     }
5901
5902     if (printJob.printDialog())
5903     {
5904       try
5905       {
5906         printJob.print();
5907       } catch (Exception PrintException)
5908       {
5909         PrintException.printStackTrace();
5910       }
5911     }
5912   }
5913
5914 }