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