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