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