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