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