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