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