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