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