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