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