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