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