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