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