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