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