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