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