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