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