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