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