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