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