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