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