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