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