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