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