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