JAL-3848 reinstate Fetch DB References submenu
[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       build_fetchdbmenu(webService);
4662     });
4663   }
4664
4665   private void buildLegacyWebServicesMenu(JMenu menu)
4666   {
4667     JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
4668     if (Discoverer.getServices() != null && Discoverer.getServices().size() > 0) 
4669     {
4670       var secstrpred = Discoverer.getServices().get("SecStrPred");
4671       if (secstrpred != null) 
4672       {
4673         for (ext.vamsas.ServiceHandle sh : secstrpred) 
4674         {
4675           var menuProvider = Discoverer.getServiceClient(sh);
4676           menuProvider.attachWSMenuEntry(secstrmenu, this);
4677         }
4678       }
4679     }
4680     menu.add(secstrmenu);
4681   }
4682
4683   /**
4684    * Constructs the web services menu for the given discoverer under the
4685    * specified menu. This method must be called on the EDT
4686    * 
4687    * @param discoverer
4688    *          the discoverer used to build the menu
4689    * @param menu
4690    *          parent component which the elements will be attached to
4691    */
4692   private void buildWebServicesMenu(WSDiscovererI discoverer, JMenu menu)
4693   {
4694     if (discoverer.hasServices())
4695     {
4696       PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
4697               discoverer.getServices(), sv -> buildWebServicesMenu(), menu,
4698               this, null);
4699     }
4700     if (discoverer.isRunning())
4701     {
4702       JMenuItem item = new JMenuItem("Service discovery in progress.");
4703       item.setEnabled(false);
4704       menu.add(item);
4705     }
4706     else if (!discoverer.hasServices())
4707     {
4708       JMenuItem item = new JMenuItem("No services available.");
4709       item.setEnabled(false);
4710       menu.add(item);
4711     }
4712   }
4713
4714   /**
4715    * construct any groupURL type service menu entries.
4716    * 
4717    * @param webService
4718    */
4719
4720   protected void build_urlServiceMenu(JMenu webService)
4721   {
4722     // TODO: remove this code when 2.7 is released
4723     // DEBUG - alignmentView
4724     /*
4725      * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4726      * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4727      * 
4728      *  public void actionPerformed(ActionEvent e) {
4729      * jalview.datamodel.AlignmentView
4730      * .testSelectionViews(af.viewport.getAlignment(),
4731      * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4732      * 
4733      * }); webService.add(testAlView);
4734      */
4735     // TODO: refactor to RestClient discoverer and merge menu entries for
4736     // rest-style services with other types of analysis/calculation service
4737     // SHmmr test client - still being implemented.
4738     // DEBUG - alignmentView
4739
4740     for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4741             .getRestClients())
4742     {
4743       client.attachWSMenuEntry(
4744               JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4745               this);
4746     }
4747   }
4748
4749   /**
4750    * Searches the alignment sequences for xRefs and builds the Show
4751    * Cross-References menu (formerly called Show Products), with database
4752    * sources for which cross-references are found (protein sources for a
4753    * nucleotide alignment and vice versa)
4754    * 
4755    * @return true if Show Cross-references menu should be enabled
4756    */
4757
4758   public boolean canShowProducts()
4759   {
4760     SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4761     AlignmentI dataset = viewport.getAlignment().getDataset();
4762
4763     showProducts.removeAll();
4764     final boolean dna = viewport.getAlignment().isNucleotide();
4765
4766     if (seqs == null || seqs.length == 0)
4767     {
4768       // nothing to see here.
4769       return false;
4770     }
4771
4772     boolean showp = false;
4773     try
4774     {
4775       List<String> ptypes = new CrossRef(seqs, dataset)
4776               .findXrefSourcesForSequences(dna);
4777
4778       for (final String source : ptypes)
4779       {
4780         showp = true;
4781         final AlignFrame af = this;
4782         JMenuItem xtype = new JMenuItem(source);
4783         xtype.addActionListener(new ActionListener()
4784         {
4785
4786           @Override
4787           public void actionPerformed(ActionEvent e)
4788           {
4789             showProductsFor(af.viewport.getSequenceSelection(), dna,
4790                     source);
4791           }
4792         });
4793         showProducts.add(xtype);
4794       }
4795       showProducts.setVisible(showp);
4796       showProducts.setEnabled(showp);
4797     } catch (Exception e)
4798     {
4799       Cache.log.warn(
4800               "canShowProducts threw an exception - please report to help@jalview.org",
4801               e);
4802       return false;
4803     }
4804     return showp;
4805   }
4806
4807   /**
4808    * Finds and displays cross-references for the selected sequences (protein
4809    * products for nucleotide sequences, dna coding sequences for peptides).
4810    * 
4811    * @param sel
4812    *          the sequences to show cross-references for
4813    * @param dna
4814    *          true if from a nucleotide alignment (so showing proteins)
4815    * @param source
4816    *          the database to show cross-references for
4817    */
4818
4819   protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4820           final String source)
4821   {
4822     new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4823             .start();
4824   }
4825
4826   /**
4827    * Construct and display a new frame containing the translation of this
4828    * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4829    */
4830
4831   @Override
4832   public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4833   {
4834     AlignmentI al = null;
4835     try
4836     {
4837       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4838
4839       al = dna.translateCdna(codeTable);
4840     } catch (Exception ex)
4841     {
4842       jalview.bin.Cache.log.error(
4843               "Exception during translation. Please report this !", ex);
4844       final String msg = MessageManager.getString(
4845               "label.error_when_translating_sequences_submit_bug_report");
4846       final String errorTitle = MessageManager
4847               .getString("label.implementation_error")
4848               + MessageManager.getString("label.translation_failed");
4849       JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4850               errorTitle, JvOptionPane.ERROR_MESSAGE);
4851       return;
4852     }
4853     if (al == null || al.getHeight() == 0)
4854     {
4855       final String msg = MessageManager.getString(
4856               "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4857       final String errorTitle = MessageManager
4858               .getString("label.translation_failed");
4859       JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4860               errorTitle, JvOptionPane.WARNING_MESSAGE);
4861     }
4862     else
4863     {
4864       AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4865       af.setFileFormat(this.currentFileFormat);
4866       final String newTitle = MessageManager
4867               .formatMessage("label.translation_of_params", new Object[]
4868               { this.getTitle(), codeTable.getId() });
4869       af.setTitle(newTitle);
4870       if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4871       {
4872         final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4873         AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4874       }
4875       else
4876       {
4877         Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4878                 DEFAULT_HEIGHT);
4879       }
4880     }
4881   }
4882
4883   /**
4884    * Set the file format
4885    * 
4886    * @param format
4887    */
4888
4889   public void setFileFormat(FileFormatI format)
4890   {
4891     this.currentFileFormat = format;
4892   }
4893
4894   /**
4895    * Try to load a features file onto the alignment.
4896    * 
4897    * @param file
4898    *          contents or path to retrieve file or a File object
4899    * @param sourceType
4900    *          access mode of file (see jalview.io.AlignFile)
4901    * @return true if features file was parsed correctly.
4902    */
4903
4904   public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4905   {
4906     // BH 2018
4907     return avc.parseFeaturesFile(file, sourceType,
4908             Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4909
4910   }
4911
4912   @Override
4913   public void refreshFeatureUI(boolean enableIfNecessary)
4914   {
4915     // note - currently this is only still here rather than in the controller
4916     // because of the featureSettings hard reference that is yet to be
4917     // abstracted
4918     if (enableIfNecessary)
4919     {
4920       viewport.setShowSequenceFeatures(true);
4921       showSeqFeatures.setSelected(true);
4922     }
4923
4924   }
4925
4926   @Override
4927   public void dragEnter(DropTargetDragEvent evt)
4928   {
4929   }
4930
4931   @Override
4932   public void dragExit(DropTargetEvent evt)
4933   {
4934   }
4935
4936   @Override
4937   public void dragOver(DropTargetDragEvent evt)
4938   {
4939   }
4940
4941   @Override
4942   public void dropActionChanged(DropTargetDragEvent evt)
4943   {
4944   }
4945
4946   @Override
4947   public void drop(DropTargetDropEvent evt)
4948   {
4949     // JAL-1552 - acceptDrop required before getTransferable call for
4950     // Java's Transferable for native dnd
4951     evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4952     Transferable t = evt.getTransferable();
4953
4954     final List<Object> files = new ArrayList<>();
4955     List<DataSourceType> protocols = new ArrayList<>();
4956
4957     try
4958     {
4959       Desktop.transferFromDropTarget(files, protocols, evt, t);
4960       if (files.size() > 0)
4961       {
4962         new Thread(new Runnable()
4963         {
4964
4965           @Override
4966           public void run()
4967           {
4968             loadDroppedFiles(files, protocols, evt, t);
4969           }
4970         }).start();
4971       }
4972     } catch (Exception e)
4973     {
4974       e.printStackTrace();
4975     }
4976   }
4977
4978   protected void loadDroppedFiles(List<Object> files,
4979           List<DataSourceType> protocols, DropTargetDropEvent evt,
4980           Transferable t)
4981   {
4982     try
4983     {
4984       // check to see if any of these files have names matching sequences
4985       // in
4986       // the alignment
4987       SequenceIdMatcher idm = new SequenceIdMatcher(
4988               viewport.getAlignment().getSequencesArray());
4989       /**
4990        * Object[] { String,SequenceI}
4991        */
4992       ArrayList<Object[]> filesmatched = new ArrayList<>();
4993       ArrayList<Object> filesnotmatched = new ArrayList<>();
4994       for (int i = 0; i < files.size(); i++)
4995       {
4996         // BH 2018
4997         Object fileObj = files.get(i);
4998         String fileName = fileObj.toString();
4999         String pdbfn = "";
5000         DataSourceType protocol = (fileObj instanceof File
5001                 ? DataSourceType.FILE
5002                 : FormatAdapter.checkProtocol(fileName));
5003         if (protocol == DataSourceType.FILE)
5004         {
5005           File file;
5006           if (fileObj instanceof File)
5007           {
5008             file = (File) fileObj;
5009             Platform.cacheFileData(file);
5010           }
5011           else
5012           {
5013             file = new File(fileName);
5014           }
5015           pdbfn = file.getName();
5016         }
5017         else if (protocol == DataSourceType.URL)
5018         {
5019           URL url = new URL(fileName);
5020           pdbfn = url.getFile();
5021         }
5022         if (pdbfn.length() > 0)
5023         {
5024           // attempt to find a match in the alignment
5025           SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5026           int l = 0, c = pdbfn.indexOf(".");
5027           while (mtch == null && c != -1)
5028           {
5029             do
5030             {
5031               l = c;
5032             } while ((c = pdbfn.indexOf(".", l)) > l);
5033             if (l > -1)
5034             {
5035               pdbfn = pdbfn.substring(0, l);
5036             }
5037             mtch = idm.findAllIdMatches(pdbfn);
5038           }
5039           if (mtch != null)
5040           {
5041             FileFormatI type;
5042             try
5043             {
5044               type = new IdentifyFile().identify(fileObj, protocol);
5045             } catch (Exception ex)
5046             {
5047               type = null;
5048             }
5049             if (type != null && type.isStructureFile())
5050             {
5051               filesmatched.add(new Object[] { fileObj, protocol, mtch });
5052               continue;
5053             }
5054           }
5055           // File wasn't named like one of the sequences or wasn't a PDB
5056           // file.
5057           filesnotmatched.add(fileObj);
5058         }
5059       }
5060       int assocfiles = 0;
5061       if (filesmatched.size() > 0)
5062       {
5063         boolean autoAssociate = Cache
5064                 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
5065         if (!autoAssociate)
5066         {
5067           String msg = MessageManager.formatMessage(
5068                   "label.automatically_associate_structure_files_with_sequences_same_name",
5069                   new Object[]
5070                   { Integer.valueOf(filesmatched.size()).toString() });
5071           String ttl = MessageManager.getString(
5072                   "label.automatically_associate_structure_files_by_name");
5073           int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
5074                   JvOptionPane.YES_NO_OPTION);
5075           autoAssociate = choice == JvOptionPane.YES_OPTION;
5076         }
5077         if (autoAssociate)
5078         {
5079           for (Object[] fm : filesmatched)
5080           {
5081             // try and associate
5082             // TODO: may want to set a standard ID naming formalism for
5083             // associating PDB files which have no IDs.
5084             for (SequenceI toassoc : (SequenceI[]) fm[2])
5085             {
5086               PDBEntry pe = AssociatePdbFileWithSeq.associatePdbWithSeq(
5087                       fm[0].toString(), (DataSourceType) fm[1], toassoc,
5088                       false);
5089               if (pe != null)
5090               {
5091                 System.err.println("Associated file : " + (fm[0].toString())
5092                         + " with " + toassoc.getDisplayId(true));
5093                 assocfiles++;
5094               }
5095             }
5096             // TODO: do we need to update overview ? only if features are
5097             // shown I guess
5098             alignPanel.paintAlignment(true, false);
5099           }
5100         }
5101         else
5102         {
5103           /*
5104            * add declined structures as sequences
5105            */
5106           for (Object[] o : filesmatched)
5107           {
5108             filesnotmatched.add(o[0]);
5109           }
5110         }
5111       }
5112       if (filesnotmatched.size() > 0)
5113       {
5114         if (assocfiles > 0 && (Cache
5115                 .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
5116                 || JvOptionPane.showConfirmDialog(this,
5117                         "<html>" + MessageManager.formatMessage(
5118                                 "label.ignore_unmatched_dropped_files_info",
5119                                 new Object[]
5120                                 { Integer.valueOf(filesnotmatched.size())
5121                                         .toString() })
5122                                 + "</html>",
5123                         MessageManager.getString(
5124                                 "label.ignore_unmatched_dropped_files"),
5125                         JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
5126         {
5127           return;
5128         }
5129         for (Object fn : filesnotmatched)
5130         {
5131           loadJalviewDataFile(fn, null, null, null);
5132         }
5133
5134       }
5135     } catch (Exception ex)
5136     {
5137       ex.printStackTrace();
5138     }
5139   }
5140
5141   /**
5142    * Attempt to load a "dropped" file or URL string, by testing in turn for
5143    * <ul>
5144    * <li>an Annotation file</li>
5145    * <li>a JNet file</li>
5146    * <li>a features file</li>
5147    * <li>else try to interpret as an alignment file</li>
5148    * </ul>
5149    * 
5150    * @param file
5151    *          either a filename or a URL string.
5152    * @throws InterruptedException
5153    * @throws IOException
5154    */
5155
5156   public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5157           FileFormatI format, SequenceI assocSeq)
5158   {
5159     // BH 2018 was String file
5160     try
5161     {
5162       if (sourceType == null)
5163       {
5164         sourceType = FormatAdapter.checkProtocol(file);
5165       }
5166       // if the file isn't identified, or not positively identified as some
5167       // other filetype (PFAM is default unidentified alignment file type) then
5168       // try to parse as annotation.
5169       boolean isAnnotation = (format == null
5170               || FileFormat.Pfam.equals(format))
5171                       ? new AnnotationFile().annotateAlignmentView(viewport,
5172                               file, sourceType)
5173                       : false;
5174
5175       if (!isAnnotation)
5176       {
5177         // first see if its a T-COFFEE score file
5178         TCoffeeScoreFile tcf = null;
5179         try
5180         {
5181           tcf = new TCoffeeScoreFile(file, sourceType);
5182           if (tcf.isValid())
5183           {
5184             if (tcf.annotateAlignment(viewport.getAlignment(), true))
5185             {
5186               buildColourMenu();
5187               changeColour(
5188                       new TCoffeeColourScheme(viewport.getAlignment()));
5189               isAnnotation = true;
5190               setStatus(MessageManager.getString(
5191                       "label.successfully_pasted_tcoffee_scores_to_alignment"));
5192             }
5193             else
5194             {
5195               // some problem - if no warning its probable that the ID matching
5196               // process didn't work
5197               JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
5198                       tcf.getWarningMessage() == null
5199                               ? MessageManager.getString(
5200                                       "label.check_file_matches_sequence_ids_alignment")
5201                               : tcf.getWarningMessage(),
5202                       MessageManager.getString(
5203                               "label.problem_reading_tcoffee_score_file"),
5204                       JvOptionPane.WARNING_MESSAGE);
5205             }
5206           }
5207           else
5208           {
5209             tcf = null;
5210           }
5211         } catch (Exception x)
5212         {
5213           Cache.log.debug(
5214                   "Exception when processing data source as T-COFFEE score file",
5215                   x);
5216           tcf = null;
5217         }
5218         if (tcf == null)
5219         {
5220           // try to see if its a JNet 'concise' style annotation file *before*
5221           // we
5222           // try to parse it as a features file
5223           if (format == null)
5224           {
5225             format = new IdentifyFile().identify(file, sourceType);
5226           }
5227           if (FileFormat.ScoreMatrix == format)
5228           {
5229             ScoreMatrixFile sm = new ScoreMatrixFile(
5230                     new FileParse(file, sourceType));
5231             sm.parse();
5232             // todo: i18n this message
5233             setStatus(MessageManager.formatMessage(
5234                     "label.successfully_loaded_matrix",
5235                     sm.getMatrixName()));
5236           }
5237           else if (FileFormat.Jnet.equals(format))
5238           {
5239             JPredFile predictions = new JPredFile(file, sourceType);
5240             new JnetAnnotationMaker();
5241             JnetAnnotationMaker.add_annotation(predictions,
5242                     viewport.getAlignment(), 0, false);
5243             viewport.getAlignment().setupJPredAlignment();
5244             isAnnotation = true;
5245           }
5246           // else if (IdentifyFile.FeaturesFile.equals(format))
5247           else if (FileFormat.Features.equals(format))
5248           {
5249             if (parseFeaturesFile(file, sourceType))
5250             {
5251               SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5252               if (splitFrame != null)
5253               {
5254                 splitFrame.repaint();
5255               }
5256               else
5257               {
5258                 alignPanel.paintAlignment(true, true);
5259               }
5260             }
5261           }
5262           else
5263           {
5264             new FileLoader().LoadFile(viewport, file, sourceType, format);
5265           }
5266         }
5267       }
5268       if (isAnnotation)
5269       {
5270         updateForAnnotations();
5271       }
5272     } catch (Exception ex)
5273     {
5274       ex.printStackTrace();
5275     } catch (OutOfMemoryError oom)
5276     {
5277       try
5278       {
5279         System.gc();
5280       } catch (Exception x)
5281       {
5282       }
5283       new OOMWarning(
5284               "loading data "
5285                       + (sourceType != null
5286                               ? (sourceType == DataSourceType.PASTE
5287                                       ? "from clipboard."
5288                                       : "using " + sourceType + " from "
5289                                               + file)
5290                               : ".")
5291                       + (format != null
5292                               ? "(parsing as '" + format + "' file)"
5293                               : ""),
5294               oom, Desktop.getDesktopPane());
5295     }
5296   }
5297
5298   /**
5299    * Do all updates necessary after an annotation file such as jnet. Also called
5300    * from Jalview.loadAppletParams for "annotations", "jnetFile"
5301    */
5302
5303   public void updateForAnnotations()
5304   {
5305     alignPanel.adjustAnnotationHeight();
5306     viewport.updateSequenceIdColours();
5307     buildSortByAnnotationScoresMenu();
5308     alignPanel.paintAlignment(true, true);
5309   }
5310
5311   /**
5312    * Change the display state for the given feature groups -- Added by BH from
5313    * JalviewLite
5314    * 
5315    * @param groups
5316    *          list of group strings
5317    * @param state
5318    *          visible or invisible
5319    */
5320
5321   public void setFeatureGroupState(String[] groups, boolean state)
5322   {
5323     jalview.api.FeatureRenderer fr = null;
5324     viewport.setShowSequenceFeatures(true);
5325     if (alignPanel != null
5326             && (fr = alignPanel.getFeatureRenderer()) != null)
5327     {
5328
5329       fr.setGroupVisibility(Arrays.asList(groups), state);
5330       alignPanel.getSeqPanel().seqCanvas.repaint();
5331       if (alignPanel.overviewPanel != null)
5332       {
5333         alignPanel.overviewPanel.updateOverviewImage();
5334       }
5335     }
5336   }
5337
5338   /**
5339    * Method invoked by the ChangeListener on the tabbed pane, in other words
5340    * when a different tabbed pane is selected by the user or programmatically.
5341    */
5342
5343   @Override
5344   public void tabSelectionChanged(int index)
5345   {
5346     if (index > -1)
5347     {
5348       alignPanel = alignPanels.get(index);
5349       viewport = alignPanel.av;
5350       avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5351       setMenusFromViewport(viewport);
5352       if (featureSettings != null && featureSettings.isOpen()
5353               && featureSettings.fr.getViewport() != viewport)
5354       {
5355         if (viewport.isShowSequenceFeatures())
5356         {
5357           // refresh the featureSettings to reflect UI change
5358           showFeatureSettingsUI();
5359         }
5360         else
5361         {
5362           // close feature settings for this view.
5363           featureSettings.close();
5364         }
5365       }
5366
5367     }
5368
5369     /*
5370      * 'focus' any colour slider that is open to the selected viewport
5371      */
5372     if (viewport.getConservationSelected())
5373     {
5374       SliderPanel.setConservationSlider(alignPanel,
5375               viewport.getResidueShading(), alignPanel.getViewName());
5376     }
5377     else
5378     {
5379       SliderPanel.hideConservationSlider();
5380     }
5381     if (viewport.getAbovePIDThreshold())
5382     {
5383       SliderPanel.setPIDSliderSource(alignPanel,
5384               viewport.getResidueShading(), alignPanel.getViewName());
5385     }
5386     else
5387     {
5388       SliderPanel.hidePIDSlider();
5389     }
5390
5391     /*
5392      * If there is a frame linked to this one in a SplitPane, switch it to the
5393      * same view tab index. No infinite recursion of calls should happen, since
5394      * tabSelectionChanged() should not get invoked on setting the selected
5395      * index to an unchanged value. Guard against setting an invalid index
5396      * before the new view peer tab has been created.
5397      */
5398     final AlignViewportI peer = viewport.getCodingComplement();
5399     if (peer != null)
5400     {
5401       AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5402               .getAlignPanel().alignFrame;
5403       if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5404       {
5405         linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5406       }
5407     }
5408   }
5409
5410   /**
5411    * On right mouse click on view tab, prompt for and set new view name.
5412    */
5413
5414   @Override
5415   public void tabbedPane_mousePressed(MouseEvent e)
5416   {
5417     if (e.isPopupTrigger())
5418     {
5419       String msg = MessageManager.getString("label.enter_view_name");
5420       String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5421       String reply = JvOptionPane.showInputDialog(msg, ttl);
5422
5423       if (reply != null)
5424       {
5425         viewport.setViewName(reply);
5426         // TODO warn if reply is in getExistingViewNames()?
5427         tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5428       }
5429     }
5430   }
5431
5432   public AlignViewport getCurrentView()
5433   {
5434     return viewport;
5435   }
5436
5437   /**
5438    * Open the dialog for regex description parsing.
5439    */
5440
5441   @Override
5442   protected void extractScores_actionPerformed(ActionEvent e)
5443   {
5444     ParseProperties pp = new jalview.analysis.ParseProperties(
5445             viewport.getAlignment());
5446     // TODO: verify regex and introduce GUI dialog for version 2.5
5447     // if (pp.getScoresFromDescription("col", "score column ",
5448     // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5449     // true)>0)
5450     if (pp.getScoresFromDescription("description column",
5451             "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5452     {
5453       buildSortByAnnotationScoresMenu();
5454     }
5455   }
5456
5457   /*
5458    * (non-Javadoc)
5459    * 
5460    * @see
5461    * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5462    * )
5463    */
5464
5465   @Override
5466   protected void showDbRefs_actionPerformed(ActionEvent e)
5467   {
5468     viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5469   }
5470
5471   /*
5472    * (non-Javadoc)
5473    * 
5474    * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5475    * ActionEvent)
5476    */
5477
5478   @Override
5479   protected void showNpFeats_actionPerformed(ActionEvent e)
5480   {
5481     viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5482   }
5483
5484   /**
5485    * find the viewport amongst the tabs in this alignment frame and close that
5486    * tab
5487    * 
5488    * @param av
5489    */
5490
5491   public boolean closeView(AlignViewportI av)
5492   {
5493     if (viewport == av)
5494     {
5495       this.closeMenuItem_actionPerformed(false);
5496       return true;
5497     }
5498     Component[] comp = tabbedPane.getComponents();
5499     for (int i = 0; comp != null && i < comp.length; i++)
5500     {
5501       if (comp[i] instanceof AlignmentPanel)
5502       {
5503         if (((AlignmentPanel) comp[i]).av == av)
5504         {
5505           // close the view.
5506           closeView((AlignmentPanel) comp[i]);
5507           return true;
5508         }
5509       }
5510     }
5511     return false;
5512   }
5513
5514   protected void build_fetchdbmenu(JMenu webService)
5515   {
5516     // Temporary hack - DBRef Fetcher always top level ws entry.
5517     // TODO We probably want to store a sequence database checklist in
5518     // preferences and have checkboxes.. rather than individual sources selected
5519     // here
5520     final JMenu rfetch = new JMenu(
5521             MessageManager.getString("action.fetch_db_references"));
5522     rfetch.setToolTipText(MessageManager.getString(
5523             "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5524     webService.add(rfetch);
5525
5526     final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5527             MessageManager.getString("option.trim_retrieved_seqs"));
5528     trimrs.setToolTipText(
5529             MessageManager.getString("label.trim_retrieved_sequences"));
5530     trimrs.setSelected(
5531             Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5532     trimrs.addActionListener(new ActionListener()
5533     {
5534
5535       @Override
5536       public void actionPerformed(ActionEvent e)
5537       {
5538         trimrs.setSelected(trimrs.isSelected());
5539         Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5540                 Boolean.valueOf(trimrs.isSelected()).toString());
5541       }
5542     });
5543     rfetch.add(trimrs);
5544     JMenuItem fetchr = new JMenuItem(
5545             MessageManager.getString("label.standard_databases"));
5546     fetchr.setToolTipText(
5547             MessageManager.getString("label.fetch_embl_uniprot"));
5548     fetchr.addActionListener(new ActionListener()
5549     {
5550
5551       @Override
5552       public void actionPerformed(ActionEvent e)
5553       {
5554         new Thread(new Runnable()
5555         {
5556
5557           @Override
5558           public void run()
5559           {
5560             boolean isNucleotide = alignPanel.alignFrame.getViewport()
5561                     .getAlignment().isNucleotide();
5562             DBRefFetcher dbRefFetcher = new DBRefFetcher(
5563                     alignPanel.av.getSequenceSelection(),
5564                     alignPanel.alignFrame, null,
5565                     alignPanel.alignFrame.featureSettings, isNucleotide);
5566             dbRefFetcher.addListener(new FetchFinishedListenerI()
5567             {
5568
5569               @Override
5570               public void finished()
5571               {
5572
5573                 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5574                         .getFeatureSettingsModels())
5575                 {
5576
5577                   alignPanel.av.mergeFeaturesStyle(srcSettings);
5578                 }
5579                 AlignFrame.this.setMenusForViewport();
5580               }
5581             });
5582             dbRefFetcher.fetchDBRefs(false);
5583           }
5584         }).start();
5585
5586       }
5587
5588     });
5589     rfetch.add(fetchr);
5590     new Thread(new Runnable()
5591     {
5592
5593       @Override
5594       public void run()
5595       {
5596         // ??
5597         // final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5598         // .getSequenceFetcherSingleton();
5599         javax.swing.SwingUtilities.invokeLater(new Runnable()
5600         {
5601
5602           @Override
5603           public void run()
5604           {
5605             jalview.ws.SequenceFetcher sf = jalview.ws.SequenceFetcher
5606                     .getInstance();
5607             String[] dbclasses = sf.getNonAlignmentSources();
5608             List<DbSourceProxy> otherdb;
5609             JMenu dfetch = new JMenu();
5610             JMenu ifetch = new JMenu();
5611             JMenuItem fetchr = null;
5612             int comp = 0, icomp = 0, mcomp = 15;
5613             String mname = null;
5614             int dbi = 0;
5615             for (String dbclass : dbclasses)
5616             {
5617               otherdb = sf.getSourceProxy(dbclass);
5618               // add a single entry for this class, or submenu allowing 'fetch
5619               // all' or pick one
5620               if (otherdb == null || otherdb.size() < 1)
5621               {
5622                 continue;
5623               }
5624               if (mname == null)
5625               {
5626                 mname = "From " + dbclass;
5627               }
5628               if (otherdb.size() == 1)
5629               {
5630                 DbSourceProxy src = otherdb.get(0);
5631                 DbSourceProxy[] dassource = new DbSourceProxy[] { src };
5632                 fetchr = new JMenuItem(src.getDbSource());
5633                 fetchr.addActionListener(new ActionListener()
5634                 {
5635
5636                   @Override
5637                   public void actionPerformed(ActionEvent e)
5638                   {
5639                     new Thread(new Runnable()
5640                     {
5641
5642                       @Override
5643                       public void run()
5644                       {
5645                         boolean isNucleotide = alignPanel.alignFrame
5646                                 .getViewport().getAlignment()
5647                                 .isNucleotide();
5648                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5649                                 alignPanel.av.getSequenceSelection(),
5650                                 alignPanel.alignFrame, dassource,
5651                                 alignPanel.alignFrame.featureSettings,
5652                                 isNucleotide);
5653                         dbRefFetcher
5654                                 .addListener(new FetchFinishedListenerI()
5655                                 {
5656
5657                                   @Override
5658                                   public void finished()
5659                                   {
5660                                     FeatureSettingsModelI srcSettings = dassource[0]
5661                                             .getFeatureColourScheme();
5662                                     alignPanel.av.mergeFeaturesStyle(
5663                                             srcSettings);
5664                                     AlignFrame.this.setMenusForViewport();
5665                                   }
5666                                 });
5667                         dbRefFetcher.fetchDBRefs(false);
5668                       }
5669                     }).start();
5670                   }
5671
5672                 });
5673                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5674                         MessageManager.formatMessage(
5675                                 "label.fetch_retrieve_from", new Object[]
5676                                 { src.getDbName() })));
5677                 dfetch.add(fetchr);
5678                 comp++;
5679               }
5680               else
5681               {
5682                 final DbSourceProxy[] dassource = otherdb
5683                         .toArray(new DbSourceProxy[0]);
5684                 // fetch all entry
5685                 DbSourceProxy src = otherdb.get(0);
5686                 fetchr = new JMenuItem(MessageManager
5687                         .formatMessage("label.fetch_all_param", new Object[]
5688                         { src.getDbSource() }));
5689                 fetchr.addActionListener(new ActionListener()
5690                 {
5691
5692                   @Override
5693                   public void actionPerformed(ActionEvent e)
5694                   {
5695                     new Thread(new Runnable()
5696                     {
5697
5698                       @Override
5699                       public void run()
5700                       {
5701                         boolean isNucleotide = alignPanel.alignFrame
5702                                 .getViewport().getAlignment()
5703                                 .isNucleotide();
5704                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5705                                 alignPanel.av.getSequenceSelection(),
5706                                 alignPanel.alignFrame, dassource,
5707                                 alignPanel.alignFrame.featureSettings,
5708                                 isNucleotide);
5709                         dbRefFetcher
5710                                 .addListener(new FetchFinishedListenerI()
5711                                 {
5712
5713                                   @Override
5714                                   public void finished()
5715                                   {
5716                                     AlignFrame.this.setMenusForViewport();
5717                                   }
5718                                 });
5719                         dbRefFetcher.fetchDBRefs(false);
5720                       }
5721                     }).start();
5722                   }
5723                 });
5724
5725                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5726                         MessageManager.formatMessage(
5727                                 "label.fetch_retrieve_from_all_sources",
5728                                 new Object[]
5729                                 { Integer.valueOf(otherdb.size())
5730                                         .toString(),
5731                                     src.getDbSource(), src.getDbName() })));
5732                 dfetch.add(fetchr);
5733                 comp++;
5734                 // and then build the rest of the individual menus
5735                 ifetch = new JMenu(MessageManager.formatMessage(
5736                         "label.source_from_db_source", new Object[]
5737                         { src.getDbSource() }));
5738                 icomp = 0;
5739                 String imname = null;
5740                 int i = 0;
5741                 for (DbSourceProxy sproxy : otherdb)
5742                 {
5743                   String dbname = sproxy.getDbName();
5744                   String sname = dbname.length() > 5
5745                           ? dbname.substring(0, 5) + "..."
5746                           : dbname;
5747                   String msname = dbname.length() > 10
5748                           ? dbname.substring(0, 10) + "..."
5749                           : dbname;
5750                   if (imname == null)
5751                   {
5752                     imname = MessageManager
5753                             .formatMessage("label.from_msname", new Object[]
5754                             { sname });
5755                   }
5756                   fetchr = new JMenuItem(msname);
5757                   final DbSourceProxy[] dassrc = { sproxy };
5758                   fetchr.addActionListener(new ActionListener()
5759                   {
5760
5761                     @Override
5762                     public void actionPerformed(ActionEvent e)
5763                     {
5764                       new Thread(new Runnable()
5765                       {
5766
5767                         @Override
5768                         public void run()
5769                         {
5770                           boolean isNucleotide = alignPanel.alignFrame
5771                                   .getViewport().getAlignment()
5772                                   .isNucleotide();
5773                           DBRefFetcher dbRefFetcher = new DBRefFetcher(
5774                                   alignPanel.av.getSequenceSelection(),
5775                                   alignPanel.alignFrame, dassrc,
5776                                   alignPanel.alignFrame.featureSettings,
5777                                   isNucleotide);
5778                           dbRefFetcher
5779                                   .addListener(new FetchFinishedListenerI()
5780                                   {
5781
5782                                     @Override
5783                                     public void finished()
5784                                     {
5785                                       AlignFrame.this.setMenusForViewport();
5786                                     }
5787                                   });
5788                           dbRefFetcher.fetchDBRefs(false);
5789                         }
5790                       }).start();
5791                     }
5792
5793                   });
5794                   fetchr.setToolTipText(
5795                           "<html>" + MessageManager.formatMessage(
5796                                   "label.fetch_retrieve_from", new Object[]
5797                                   { dbname }));
5798                   ifetch.add(fetchr);
5799                   ++i;
5800                   if (++icomp >= mcomp || i == (otherdb.size()))
5801                   {
5802                     ifetch.setText(MessageManager.formatMessage(
5803                             "label.source_to_target", imname, sname));
5804                     dfetch.add(ifetch);
5805                     ifetch = new JMenu();
5806                     imname = null;
5807                     icomp = 0;
5808                     comp++;
5809                   }
5810                 }
5811               }
5812               ++dbi;
5813               if (comp >= mcomp || dbi >= (dbclasses.length))
5814               {
5815                 dfetch.setText(MessageManager.formatMessage(
5816                         "label.source_to_target", mname, dbclass));
5817                 rfetch.add(dfetch);
5818                 dfetch = new JMenu();
5819                 mname = null;
5820                 comp = 0;
5821               }
5822             }
5823           }
5824         });
5825       }
5826     }).start();
5827
5828   }
5829
5830   /**
5831    * Left justify the whole alignment.
5832    */
5833
5834   @Override
5835   protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5836   {
5837     viewport.getAlignment().justify(false);
5838     viewport.notifyAlignment();
5839   }
5840
5841   /**
5842    * Right justify the whole alignment.
5843    */
5844
5845   @Override
5846   protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5847   {
5848     viewport.getAlignment().justify(true);
5849     viewport.notifyAlignment();
5850   }
5851
5852   @Override
5853   public void setShowSeqFeatures(boolean b)
5854   {
5855     showSeqFeatures.setSelected(b);
5856     viewport.setShowSequenceFeatures(b);
5857   }
5858
5859   /*
5860    * (non-Javadoc)
5861    * 
5862    * @see
5863    * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5864    * awt.event.ActionEvent)
5865    */
5866
5867   @Override
5868   protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5869   {
5870     viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5871     alignPanel.paintAlignment(false, false);
5872   }
5873
5874   /*
5875    * (non-Javadoc)
5876    * 
5877    * @see
5878    * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5879    * .ActionEvent)
5880    */
5881
5882   @Override
5883   protected void showGroupConsensus_actionPerformed(ActionEvent e)
5884   {
5885     viewport.setShowGroupConsensus(showGroupConsensus.getState());
5886     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5887
5888   }
5889
5890   /*
5891    * (non-Javadoc)
5892    * 
5893    * @see
5894    * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5895    * .event.ActionEvent)
5896    */
5897
5898   @Override
5899   protected void showGroupConservation_actionPerformed(ActionEvent e)
5900   {
5901     viewport.setShowGroupConservation(showGroupConservation.getState());
5902     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5903   }
5904
5905   /*
5906    * (non-Javadoc)
5907    * 
5908    * @see
5909    * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5910    * .event.ActionEvent)
5911    */
5912
5913   @Override
5914   protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5915   {
5916     viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5917     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5918   }
5919
5920   /*
5921    * (non-Javadoc)
5922    * 
5923    * @see
5924    * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5925    * .event.ActionEvent)
5926    */
5927
5928   @Override
5929   protected void showSequenceLogo_actionPerformed(ActionEvent e)
5930   {
5931     viewport.setShowSequenceLogo(showSequenceLogo.getState());
5932     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5933   }
5934
5935   @Override
5936   protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5937   {
5938     showSequenceLogo.setState(true);
5939     viewport.setShowSequenceLogo(true);
5940     viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5941     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5942   }
5943
5944   @Override
5945   protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5946   {
5947     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5948   }
5949
5950   /*
5951    * (non-Javadoc)
5952    * 
5953    * @see
5954    * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5955    * .event.ActionEvent)
5956    */
5957
5958   @Override
5959   protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5960   {
5961     if (avc.makeGroupsFromSelection())
5962     {
5963       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5964       alignPanel.updateAnnotation();
5965       alignPanel.paintAlignment(true,
5966               viewport.needToUpdateStructureViews());
5967     }
5968   }
5969
5970   public void clearAlignmentSeqRep()
5971   {
5972     // TODO refactor alignmentseqrep to controller
5973     if (viewport.getAlignment().hasSeqrep())
5974     {
5975       viewport.getAlignment().setSeqrep(null);
5976       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5977       alignPanel.updateAnnotation();
5978       alignPanel.paintAlignment(true, true);
5979     }
5980   }
5981
5982   @Override
5983   protected void createGroup_actionPerformed(ActionEvent e)
5984   {
5985     if (avc.createGroup())
5986     {
5987       if (applyAutoAnnotationSettings.isSelected())
5988       {
5989         alignPanel.updateAnnotation(true, false);
5990       }
5991       alignPanel.alignmentChanged();
5992     }
5993   }
5994
5995   @Override
5996   protected void unGroup_actionPerformed(ActionEvent e)
5997   {
5998     if (avc.unGroup())
5999     {
6000       alignPanel.alignmentChanged();
6001     }
6002   }
6003
6004   /**
6005    * make the given alignmentPanel the currently selected tab
6006    * 
6007    * @param alignmentPanel
6008    */
6009
6010   public void setDisplayedView(AlignmentPanel alignmentPanel)
6011   {
6012     if (!viewport.getSequenceSetId()
6013             .equals(alignmentPanel.av.getSequenceSetId()))
6014     {
6015       throw new Error(MessageManager.getString(
6016               "error.implementation_error_cannot_show_view_alignment_frame"));
6017     }
6018     if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
6019             .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
6020     {
6021       tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
6022     }
6023   }
6024
6025   /**
6026    * Action on selection of menu options to Show or Hide annotations.
6027    * 
6028    * @param visible
6029    * @param forSequences
6030    *          update sequence-related annotations
6031    * @param forAlignment
6032    *          update non-sequence-related annotations
6033    */
6034
6035   @Override
6036   protected void setAnnotationsVisibility(boolean visible,
6037           boolean forSequences, boolean forAlignment)
6038   {
6039     AlignmentAnnotation[] anns = alignPanel.getAlignment()
6040             .getAlignmentAnnotation();
6041     if (anns == null)
6042     {
6043       return;
6044     }
6045     for (AlignmentAnnotation aa : anns)
6046     {
6047       /*
6048        * don't display non-positional annotations on an alignment
6049        */
6050       if (aa.annotations == null)
6051       {
6052         continue;
6053       }
6054       boolean apply = (aa.sequenceRef == null && forAlignment)
6055               || (aa.sequenceRef != null && forSequences);
6056       if (apply)
6057       {
6058         aa.visible = visible;
6059       }
6060     }
6061     alignPanel.validateAnnotationDimensions(true);
6062     alignPanel.alignmentChanged();
6063   }
6064
6065   /**
6066    * Store selected annotation sort order for the view and repaint.
6067    */
6068
6069   @Override
6070   protected void sortAnnotations_actionPerformed()
6071   {
6072     this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
6073     this.alignPanel.av
6074             .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
6075     alignPanel.paintAlignment(false, false);
6076   }
6077
6078   /**
6079    * 
6080    * @return alignment panels in this alignment frame
6081    */
6082
6083   public List<? extends AlignmentViewPanel> getAlignPanels()
6084   {
6085     // alignPanels is never null
6086     // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
6087     return alignPanels;
6088   }
6089
6090   /**
6091    * Open a new alignment window, with the cDNA associated with this (protein)
6092    * alignment, aligned as is the protein.
6093    */
6094
6095   protected void viewAsCdna_actionPerformed()
6096   {
6097     // TODO no longer a menu action - refactor as required
6098     final AlignmentI alignment = getViewport().getAlignment();
6099     List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6100     if (mappings == null)
6101     {
6102       return;
6103     }
6104     List<SequenceI> cdnaSeqs = new ArrayList<>();
6105     for (SequenceI aaSeq : alignment.getSequences())
6106     {
6107       for (AlignedCodonFrame acf : mappings)
6108       {
6109         SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6110         if (dnaSeq != null)
6111         {
6112           /*
6113            * There is a cDNA mapping for this protein sequence - add to new
6114            * alignment. It will share the same dataset sequence as other mapped
6115            * cDNA (no new mappings need to be created).
6116            */
6117           final Sequence newSeq = new Sequence(dnaSeq);
6118           newSeq.setDatasetSequence(dnaSeq);
6119           cdnaSeqs.add(newSeq);
6120         }
6121       }
6122     }
6123     if (cdnaSeqs.size() == 0)
6124     {
6125       // show a warning dialog no mapped cDNA
6126       return;
6127     }
6128     AlignmentI cdna = new Alignment(
6129             cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
6130     GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6131             AlignFrame.DEFAULT_HEIGHT);
6132     cdna.alignAs(alignment);
6133     String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6134             + this.title;
6135     Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
6136             AlignFrame.DEFAULT_HEIGHT);
6137   }
6138
6139   /**
6140    * Set visibility of dna/protein complement view (available when shown in a
6141    * split frame).
6142    * 
6143    * @param show
6144    */
6145
6146   @Override
6147   protected void showComplement_actionPerformed(boolean show)
6148   {
6149     SplitContainerI sf = getSplitViewContainer();
6150     if (sf != null)
6151     {
6152       sf.setComplementVisible(this, show);
6153     }
6154   }
6155
6156   /**
6157    * Generate the reverse (optionally complemented) of the selected sequences,
6158    * and add them to the alignment
6159    */
6160
6161   @Override
6162   protected void showReverse_actionPerformed(boolean complement)
6163   {
6164     AlignmentI al = null;
6165     try
6166     {
6167       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
6168       al = dna.reverseCdna(complement);
6169       viewport.addAlignment(al, "");
6170       addHistoryItem(new EditCommand(
6171               MessageManager.getString("label.add_sequences"), Action.PASTE,
6172               al.getSequencesArray(), 0, al.getWidth(),
6173               viewport.getAlignment()));
6174     } catch (Exception ex)
6175     {
6176       System.err.println(ex.getMessage());
6177       return;
6178     }
6179   }
6180
6181   /**
6182    * Try to run a script in the Groovy console, having first ensured that this
6183    * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
6184    * be targeted at this alignment.
6185    */
6186
6187   @Override
6188   protected void runGroovy_actionPerformed()
6189   {
6190     Jalview.setCurrentAlignFrame(this);
6191     groovy.ui.Console console = Desktop.getGroovyConsole();
6192     if (console != null)
6193     {
6194       try
6195       {
6196         console.runScript();
6197       } catch (Exception ex)
6198       {
6199         System.err.println((ex.toString()));
6200         JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
6201                 MessageManager.getString("label.couldnt_run_groovy_script"),
6202                 MessageManager.getString("label.groovy_support_failed"),
6203                 JvOptionPane.ERROR_MESSAGE);
6204       }
6205     }
6206     else
6207     {
6208       System.err.println("Can't run Groovy script as console not found");
6209     }
6210   }
6211
6212   /**
6213    * Hides columns containing (or not containing) a specified feature, provided
6214    * that would not leave all columns hidden
6215    * 
6216    * @param featureType
6217    * @param columnsContaining
6218    * @return
6219    */
6220
6221   public boolean hideFeatureColumns(String featureType,
6222           boolean columnsContaining)
6223   {
6224     boolean notForHiding = avc.markColumnsContainingFeatures(
6225             columnsContaining, false, false, featureType);
6226     if (notForHiding)
6227     {
6228       if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6229               false, featureType))
6230       {
6231         getViewport().hideSelectedColumns();
6232         return true;
6233       }
6234     }
6235     return false;
6236   }
6237
6238   @Override
6239   protected void selectHighlightedColumns_actionPerformed(
6240           ActionEvent actionEvent)
6241   {
6242     // include key modifier check in case user selects from menu
6243     avc.markHighlightedColumns(
6244             (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6245             (actionEvent.getModifiers() & (ActionEvent.META_MASK
6246                     | ActionEvent.CTRL_MASK)) != 0);
6247   }
6248
6249   /**
6250    * Rebuilds the Colour menu, including any user-defined colours which have
6251    * been loaded either on startup or during the session
6252    */
6253
6254   public void buildColourMenu()
6255   {
6256     colourMenu.removeAll();
6257
6258     colourMenu.add(applyToAllGroups);
6259     colourMenu.add(textColour);
6260     colourMenu.addSeparator();
6261
6262     ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6263             viewport.getAlignment(), false);
6264
6265     colourMenu.add(annotationColour);
6266     bg.add(annotationColour);
6267     colourMenu.addSeparator();
6268     colourMenu.add(conservationMenuItem);
6269     colourMenu.add(modifyConservation);
6270     colourMenu.add(abovePIDThreshold);
6271     colourMenu.add(modifyPID);
6272
6273     ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6274     ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6275   }
6276
6277   /**
6278    * Open a dialog (if not already open) that allows the user to select and
6279    * calculate PCA or Tree analysis
6280    */
6281
6282   protected void openTreePcaDialog()
6283   {
6284     if (alignPanel.getCalculationDialog() == null)
6285     {
6286       new CalculationChooser(AlignFrame.this);
6287     }
6288   }
6289
6290   /**
6291    * Sets the status of the HMMER menu
6292    */
6293   public void updateHMMERStatus()
6294   {
6295     hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
6296   }
6297
6298   @Override
6299   protected void loadVcf_actionPerformed()
6300   {
6301     JalviewFileChooser chooser = new JalviewFileChooser(
6302             Cache.getProperty("LAST_DIRECTORY"));
6303     chooser.setFileView(new JalviewFileView());
6304     chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6305     chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6306     final AlignFrame us = this;
6307     chooser.setResponseHandler(0, new Runnable()
6308     {
6309
6310       @Override
6311       public void run()
6312       {
6313         String choice = chooser.getSelectedFile().getPath();
6314         Cache.setProperty("LAST_DIRECTORY", choice);
6315         SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6316         new VCFLoader(choice).loadVCF(seqs, us);
6317       }
6318     });
6319     chooser.showOpenDialog(null);
6320
6321   }
6322
6323   private Rectangle lastFeatureSettingsBounds = null;
6324
6325   @Override
6326   public void setFeatureSettingsGeometry(Rectangle bounds)
6327   {
6328     lastFeatureSettingsBounds = bounds;
6329   }
6330
6331   @Override
6332   public Rectangle getFeatureSettingsGeometry()
6333   {
6334     return lastFeatureSettingsBounds;
6335   }
6336
6337   public void scrollTo(int row, int column)
6338   {
6339     alignPanel.getSeqPanel().scrollTo(row, column);
6340   }
6341
6342   public void scrollToRow(int row)
6343   {
6344     alignPanel.getSeqPanel().scrollToRow(row);
6345   }
6346
6347   public void scrollToColumn(int column)
6348   {
6349     alignPanel.getSeqPanel().scrollToColumn(column);
6350   }
6351
6352   /**
6353    * BH 2019 from JalviewLite
6354    * 
6355    * get sequence feature groups that are hidden or shown
6356    * 
6357    * @param visible
6358    *          true is visible
6359    * @return list
6360    */
6361
6362   public String[] getFeatureGroupsOfState(boolean visible)
6363   {
6364     jalview.api.FeatureRenderer fr = null;
6365     if (alignPanel != null
6366             && (fr = alignPanel.getFeatureRenderer()) != null)
6367     {
6368       List<String> gps = fr.getGroups(visible);
6369       String[] _gps = gps.toArray(new String[gps.size()]);
6370       return _gps;
6371     }
6372     return null;
6373   }
6374
6375   /**
6376    * 
6377    * @return list of feature groups on the view
6378    */
6379
6380   public String[] getFeatureGroups()
6381   {
6382     jalview.api.FeatureRenderer fr = null;
6383     if (alignPanel != null
6384             && (fr = alignPanel.getFeatureRenderer()) != null)
6385     {
6386       List<String> gps = fr.getFeatureGroups();
6387       String[] _gps = gps.toArray(new String[gps.size()]);
6388       return _gps;
6389     }
6390     return null;
6391   }
6392
6393   public void select(SequenceGroup sel, ColumnSelection csel,
6394           HiddenColumns hidden)
6395   {
6396     alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
6397   }
6398
6399   public int getID()
6400   {
6401     return id;
6402   }
6403
6404   static class PrintThread extends Thread
6405   {
6406     AlignmentPanel ap;
6407
6408     public PrintThread(AlignmentPanel ap)
6409     {
6410       this.ap = ap;
6411     }
6412
6413     static PageFormat pf;
6414
6415     @Override
6416     public void run()
6417     {
6418       PrinterJob printJob = PrinterJob.getPrinterJob();
6419
6420       if (pf != null)
6421       {
6422         printJob.setPrintable(ap, pf);
6423       }
6424       else
6425       {
6426         printJob.setPrintable(ap);
6427       }
6428
6429       if (printJob.printDialog())
6430       {
6431         try
6432         {
6433           printJob.print();
6434         } catch (Exception PrintException)
6435         {
6436           PrintException.printStackTrace();
6437         }
6438       }
6439     }
6440   }
6441 }
6442