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