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