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