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