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