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