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