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