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