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