JAL-1713 update from Jalview 2.11.3 develop
[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(null);
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
2918     return newap;
2919   }
2920
2921   /**
2922    * Make a new name for the view, ensuring it is unique within the current
2923    * sequenceSetId. (This used to be essential for Jalview Project archives, but
2924    * these now use viewId. Unique view names are still desirable for usability.)
2925    * 
2926    * @param viewTitle
2927    * @return
2928    */
2929   protected String getNewViewName(String viewTitle)
2930   {
2931     int index = Desktop.getViewCount(viewport.getSequenceSetId());
2932     boolean addFirstIndex = false;
2933     if (viewTitle == null || viewTitle.trim().length() == 0)
2934     {
2935       viewTitle = MessageManager.getString("action.view");
2936       addFirstIndex = true;
2937     }
2938     else
2939     {
2940       index = 1;// we count from 1 if given a specific name
2941     }
2942     String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2943
2944     List<Component> comps = PaintRefresher.components
2945             .get(viewport.getSequenceSetId());
2946
2947     List<String> existingNames = getExistingViewNames(comps);
2948
2949     while (existingNames.contains(newViewName))
2950     {
2951       newViewName = viewTitle + " " + (++index);
2952     }
2953     return newViewName;
2954   }
2955
2956   /**
2957    * Returns a list of distinct view names found in the given list of
2958    * components. View names are held on the viewport of an AlignmentPanel.
2959    * 
2960    * @param comps
2961    * @return
2962    */
2963   protected List<String> getExistingViewNames(List<Component> comps)
2964   {
2965     List<String> existingNames = new ArrayList<>();
2966     for (Component comp : comps)
2967     {
2968       if (comp instanceof AlignmentPanel)
2969       {
2970         AlignmentPanel ap = (AlignmentPanel) comp;
2971         if (!existingNames.contains(ap.av.getViewName()))
2972         {
2973           existingNames.add(ap.av.getViewName());
2974         }
2975       }
2976     }
2977     return existingNames;
2978   }
2979
2980   /**
2981    * Explode tabbed views into separate windows.
2982    */
2983   @Override
2984   public void expandViews_actionPerformed(ActionEvent e)
2985   {
2986     Desktop.explodeViews(this);
2987   }
2988
2989   /**
2990    * Gather views in separate windows back into a tabbed presentation.
2991    */
2992   @Override
2993   public void gatherViews_actionPerformed(ActionEvent e)
2994   {
2995     Desktop.instance.gatherViews(this);
2996   }
2997
2998   /**
2999    * DOCUMENT ME!
3000    * 
3001    * @param e
3002    *          DOCUMENT ME!
3003    */
3004   @Override
3005   public void font_actionPerformed(ActionEvent e)
3006   {
3007     new FontChooser(alignPanel);
3008   }
3009
3010   /**
3011    * DOCUMENT ME!
3012    * 
3013    * @param e
3014    *          DOCUMENT ME!
3015    */
3016   @Override
3017   protected void seqLimit_actionPerformed(ActionEvent e)
3018   {
3019     viewport.setShowJVSuffix(seqLimits.isSelected());
3020
3021     alignPanel.getIdPanel().getIdCanvas()
3022             .setPreferredSize(alignPanel.calculateIdWidth());
3023     alignPanel.paintAlignment(true, false);
3024   }
3025
3026   @Override
3027   public void idRightAlign_actionPerformed(ActionEvent e)
3028   {
3029     viewport.setRightAlignIds(idRightAlign.isSelected());
3030     alignPanel.paintAlignment(false, false);
3031   }
3032
3033   @Override
3034   public void centreColumnLabels_actionPerformed(ActionEvent e)
3035   {
3036     viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3037     alignPanel.paintAlignment(false, false);
3038   }
3039
3040   /*
3041    * (non-Javadoc)
3042    * 
3043    * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3044    */
3045   @Override
3046   protected void followHighlight_actionPerformed()
3047   {
3048     /*
3049      * Set the 'follow' flag on the Viewport (and scroll to position if now
3050      * true).
3051      */
3052     final boolean state = this.followHighlightMenuItem.getState();
3053     viewport.setFollowHighlight(state);
3054     if (state)
3055     {
3056       alignPanel.scrollToPosition(viewport.getSearchResults());
3057     }
3058   }
3059
3060   /**
3061    * DOCUMENT ME!
3062    * 
3063    * @param e
3064    *          DOCUMENT ME!
3065    */
3066   @Override
3067   protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3068   {
3069     viewport.setColourText(colourTextMenuItem.isSelected());
3070     alignPanel.paintAlignment(false, false);
3071   }
3072
3073   /**
3074    * DOCUMENT ME!
3075    * 
3076    * @param e
3077    *          DOCUMENT ME!
3078    */
3079   @Override
3080   public void wrapMenuItem_actionPerformed(ActionEvent e)
3081   {
3082     scaleAbove.setVisible(wrapMenuItem.isSelected());
3083     scaleLeft.setVisible(wrapMenuItem.isSelected());
3084     scaleRight.setVisible(wrapMenuItem.isSelected());
3085     viewport.setWrapAlignment(wrapMenuItem.isSelected());
3086     alignPanel.updateLayout();
3087   }
3088
3089   @Override
3090   public void showAllSeqs_actionPerformed(ActionEvent e)
3091   {
3092     viewport.showAllHiddenSeqs();
3093   }
3094
3095   @Override
3096   public void showAllColumns_actionPerformed(ActionEvent e)
3097   {
3098     viewport.showAllHiddenColumns();
3099     alignPanel.paintAlignment(true, true);
3100     viewport.sendSelection();
3101   }
3102
3103   @Override
3104   public void hideSelSequences_actionPerformed(ActionEvent e)
3105   {
3106     viewport.hideAllSelectedSeqs();
3107   }
3108
3109   /**
3110    * called by key handler and the hide all/show all menu items
3111    * 
3112    * @param toggleSeqs
3113    * @param toggleCols
3114    */
3115   protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3116   {
3117
3118     boolean hide = false;
3119     SequenceGroup sg = viewport.getSelectionGroup();
3120     if (!toggleSeqs && !toggleCols)
3121     {
3122       // Hide everything by the current selection - this is a hack - we do the
3123       // invert and then hide
3124       // first check that there will be visible columns after the invert.
3125       if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3126               && sg.getStartRes() <= sg.getEndRes()))
3127       {
3128         // now invert the sequence set, if required - empty selection implies
3129         // that no hiding is required.
3130         if (sg != null)
3131         {
3132           invertSequenceMenuItem_actionPerformed(null);
3133           sg = viewport.getSelectionGroup();
3134           toggleSeqs = true;
3135
3136         }
3137         viewport.expandColSelection(sg, true);
3138         // finally invert the column selection and get the new sequence
3139         // selection.
3140         invertColSel_actionPerformed(null);
3141         toggleCols = true;
3142       }
3143     }
3144
3145     if (toggleSeqs)
3146     {
3147       if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3148       {
3149         hideSelSequences_actionPerformed(null);
3150         hide = true;
3151       }
3152       else if (!(toggleCols && viewport.hasSelectedColumns()))
3153       {
3154         showAllSeqs_actionPerformed(null);
3155       }
3156     }
3157
3158     if (toggleCols)
3159     {
3160       if (viewport.hasSelectedColumns())
3161       {
3162         hideSelColumns_actionPerformed(null);
3163         if (!toggleSeqs)
3164         {
3165           viewport.setSelectionGroup(sg);
3166         }
3167       }
3168       else if (!hide)
3169       {
3170         showAllColumns_actionPerformed(null);
3171       }
3172     }
3173   }
3174
3175   /*
3176    * (non-Javadoc)
3177    * 
3178    * @see
3179    * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3180    * event.ActionEvent)
3181    */
3182   @Override
3183   public void hideAllButSelection_actionPerformed(ActionEvent e)
3184   {
3185     toggleHiddenRegions(false, false);
3186     viewport.sendSelection();
3187   }
3188
3189   /*
3190    * (non-Javadoc)
3191    * 
3192    * @see
3193    * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3194    * .ActionEvent)
3195    */
3196   @Override
3197   public void hideAllSelection_actionPerformed(ActionEvent e)
3198   {
3199     SequenceGroup sg = viewport.getSelectionGroup();
3200     viewport.expandColSelection(sg, false);
3201     viewport.hideAllSelectedSeqs();
3202     viewport.hideSelectedColumns();
3203     alignPanel.updateLayout();
3204     alignPanel.paintAlignment(true, true);
3205     viewport.sendSelection();
3206   }
3207
3208   /*
3209    * (non-Javadoc)
3210    * 
3211    * @see
3212    * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3213    * ActionEvent)
3214    */
3215   @Override
3216   public void showAllhidden_actionPerformed(ActionEvent e)
3217   {
3218     viewport.showAllHiddenColumns();
3219     viewport.showAllHiddenSeqs();
3220     alignPanel.paintAlignment(true, true);
3221     viewport.sendSelection();
3222   }
3223
3224   @Override
3225   public void hideSelColumns_actionPerformed(ActionEvent e)
3226   {
3227     viewport.hideSelectedColumns();
3228     alignPanel.updateLayout();
3229     alignPanel.paintAlignment(true, true);
3230     viewport.sendSelection();
3231   }
3232
3233   @Override
3234   public void hiddenMarkers_actionPerformed(ActionEvent e)
3235   {
3236     viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3237     repaint();
3238   }
3239
3240   /**
3241    * DOCUMENT ME!
3242    * 
3243    * @param e
3244    *          DOCUMENT ME!
3245    */
3246   @Override
3247   protected void scaleAbove_actionPerformed(ActionEvent e)
3248   {
3249     viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3250     alignPanel.updateLayout();
3251     alignPanel.paintAlignment(true, false);
3252   }
3253
3254   /**
3255    * DOCUMENT ME!
3256    * 
3257    * @param e
3258    *          DOCUMENT ME!
3259    */
3260   @Override
3261   protected void scaleLeft_actionPerformed(ActionEvent e)
3262   {
3263     viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3264     alignPanel.updateLayout();
3265     alignPanel.paintAlignment(true, false);
3266   }
3267
3268   /**
3269    * DOCUMENT ME!
3270    * 
3271    * @param e
3272    *          DOCUMENT ME!
3273    */
3274   @Override
3275   protected void scaleRight_actionPerformed(ActionEvent e)
3276   {
3277     viewport.setScaleRightWrapped(scaleRight.isSelected());
3278     alignPanel.updateLayout();
3279     alignPanel.paintAlignment(true, false);
3280   }
3281
3282   /**
3283    * DOCUMENT ME!
3284    * 
3285    * @param e
3286    *          DOCUMENT ME!
3287    */
3288   @Override
3289   public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3290   {
3291     viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3292     alignPanel.paintAlignment(false, false);
3293   }
3294
3295   /**
3296    * DOCUMENT ME!
3297    * 
3298    * @param e
3299    *          DOCUMENT ME!
3300    */
3301   @Override
3302   public void viewTextMenuItem_actionPerformed(ActionEvent e)
3303   {
3304     viewport.setShowText(viewTextMenuItem.isSelected());
3305     alignPanel.paintAlignment(false, false);
3306   }
3307
3308   /**
3309    * DOCUMENT ME!
3310    * 
3311    * @param e
3312    *          DOCUMENT ME!
3313    */
3314   @Override
3315   protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3316   {
3317     viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3318     alignPanel.paintAlignment(false, false);
3319   }
3320
3321   public FeatureSettings featureSettings;
3322
3323   @Override
3324   public FeatureSettingsControllerI getFeatureSettingsUI()
3325   {
3326     return featureSettings;
3327   }
3328
3329   @Override
3330   public void featureSettings_actionPerformed(ActionEvent e)
3331   {
3332     showFeatureSettingsUI();
3333   }
3334
3335   @Override
3336   public FeatureSettingsControllerI showFeatureSettingsUI()
3337   {
3338     if (featureSettings != null)
3339     {
3340       featureSettings.closeOldSettings();
3341       featureSettings = null;
3342     }
3343     if (!showSeqFeatures.isSelected())
3344     {
3345       // make sure features are actually displayed
3346       showSeqFeatures.setSelected(true);
3347       showSeqFeatures_actionPerformed(null);
3348     }
3349     featureSettings = new FeatureSettings(this);
3350     return featureSettings;
3351   }
3352
3353   /**
3354    * Set or clear 'Show Sequence Features'
3355    * 
3356    * @param evt
3357    *          DOCUMENT ME!
3358    */
3359   @Override
3360   public void showSeqFeatures_actionPerformed(ActionEvent evt)
3361   {
3362     viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3363     alignPanel.paintAlignment(true, true);
3364   }
3365
3366   /**
3367    * Action on toggle of the 'Show annotations' menu item. This shows or hides
3368    * the annotations panel as a whole.
3369    * 
3370    * The options to show/hide all annotations should be enabled when the panel
3371    * is shown, and disabled when the panel is hidden.
3372    * 
3373    * @param e
3374    */
3375   @Override
3376   public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3377   {
3378     final boolean setVisible = annotationPanelMenuItem.isSelected();
3379     viewport.setShowAnnotation(setVisible);
3380     this.showAllSeqAnnotations.setEnabled(setVisible);
3381     this.hideAllSeqAnnotations.setEnabled(setVisible);
3382     this.showAllAlAnnotations.setEnabled(setVisible);
3383     this.hideAllAlAnnotations.setEnabled(setVisible);
3384     alignPanel.updateLayout();
3385   }
3386
3387   @Override
3388   public void alignmentProperties()
3389   {
3390     JComponent pane;
3391     StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3392
3393             .formatAsHtml();
3394     String content = MessageManager.formatMessage("label.html_content",
3395             new Object[]
3396             { contents.toString() });
3397     contents = null;
3398
3399     if (Platform.isJS())
3400     {
3401       JLabel textLabel = new JLabel();
3402       textLabel.setText(content);
3403       textLabel.setBackground(Color.WHITE);
3404
3405       pane = new JPanel(new BorderLayout());
3406       ((JPanel) pane).setOpaque(true);
3407       pane.setBackground(Color.WHITE);
3408       ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3409     }
3410     else
3411     /**
3412      * Java only
3413      * 
3414      * @j2sIgnore
3415      */
3416     {
3417       JEditorPane editPane = new JEditorPane("text/html", "");
3418       editPane.setEditable(false);
3419       editPane.setText(content);
3420       pane = editPane;
3421     }
3422
3423     JInternalFrame frame = new JInternalFrame();
3424
3425     frame.getContentPane().add(new JScrollPane(pane));
3426
3427     Desktop.addInternalFrame(frame, MessageManager
3428             .formatMessage("label.alignment_properties", new Object[]
3429             { getTitle() }), 500, 400);
3430   }
3431
3432   /**
3433    * Opens an Overview panel for the alignment, unless one is open already
3434    * 
3435    * @param e
3436    */
3437   @Override
3438   public void overviewMenuItem_actionPerformed(ActionEvent e)
3439   {
3440     boolean showHiddenRegions = Cache.getDefault(Preferences.SHOW_OV_HIDDEN_AT_START,
3441                 false);
3442     openOverviewPanel(showHiddenRegions);
3443   }
3444
3445   public OverviewPanel openOverviewPanel(boolean showHidden)
3446   {
3447     if (alignPanel.overviewPanel != null)
3448     {
3449       return alignPanel.overviewPanel;
3450     }
3451     JInternalFrame frame = new JInternalFrame();
3452     final OverviewPanel overview = new OverviewPanel(alignPanel, frame, showHidden);
3453     frame.setContentPane(overview);
3454     Desktop.addInternalFrame(frame, "", true, frame.getWidth(), frame.getHeight(),
3455             true, true);
3456     frame.setFrameIcon(null);
3457     frame.pack();
3458     frame.setLayer(JLayeredPane.PALETTE_LAYER);
3459     final AlignmentPanel thePanel = this.alignPanel; 
3460     frame.addInternalFrameListener(
3461             new javax.swing.event.InternalFrameAdapter()
3462             {
3463               @Override
3464               public void internalFrameClosed(
3465                       javax.swing.event.InternalFrameEvent evt)
3466               {
3467                 overview.dispose();
3468                 thePanel.setOverviewPanel(null);
3469               }
3470             });
3471     if (getKeyListeners().length > 0)
3472     {
3473       frame.addKeyListener(getKeyListeners()[0]);
3474     }
3475
3476     alignPanel.setOverviewPanel(overview);
3477     alignPanel.setOverviewTitle(this);
3478     
3479     return overview;
3480   }
3481
3482   @Override
3483   public void textColour_actionPerformed()
3484   {
3485     new TextColourChooser().chooseColour(alignPanel, null);
3486   }
3487
3488   /*
3489    * public void covariationColour_actionPerformed() {
3490    * changeColour(new
3491    * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3492    * ()[0])); }
3493    */
3494   @Override
3495   public void annotationColour_actionPerformed()
3496   {
3497     new AnnotationColourChooser(viewport, alignPanel);
3498   }
3499
3500   @Override
3501   public void annotationColumn_actionPerformed(ActionEvent e)
3502   {
3503     new AnnotationColumnChooser(viewport, alignPanel);
3504   }
3505
3506   /**
3507    * Action on the user checking or unchecking the option to apply the selected
3508    * colour scheme to all groups. If unchecked, groups may have their own
3509    * independent colour schemes.
3510    * 
3511    * @param selected
3512    */
3513   @Override
3514   public void applyToAllGroups_actionPerformed(boolean selected)
3515   {
3516     viewport.setColourAppliesToAllGroups(selected);
3517   }
3518
3519   /**
3520    * Action on user selecting a colour from the colour menu
3521    * 
3522    * @param name
3523    *          the name (not the menu item label!) of the colour scheme
3524    */
3525   @Override
3526   public void changeColour_actionPerformed(String name)
3527   {
3528     /*
3529      * 'User Defined' opens a panel to configure or load a
3530      * user-defined colour scheme
3531      */
3532     if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3533     {
3534       new UserDefinedColours(alignPanel);
3535       return;
3536     }
3537
3538     /*
3539      * otherwise set the chosen colour scheme (or null for 'None')
3540      */
3541     ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3542             viewport, viewport.getAlignment(),
3543             viewport.getHiddenRepSequences());
3544     changeColour(cs);
3545   }
3546
3547   /**
3548    * Actions on setting or changing the alignment colour scheme
3549    * 
3550    * @param cs
3551    */
3552   @Override
3553   public void changeColour(ColourSchemeI cs)
3554   {
3555     // TODO: pull up to controller method
3556     ColourMenuHelper.setColourSelected(colourMenu, cs);
3557
3558     viewport.setGlobalColourScheme(cs);
3559
3560     alignPanel.paintAlignment(true, true);
3561   }
3562
3563   /**
3564    * Show the PID threshold slider panel
3565    */
3566   @Override
3567   protected void modifyPID_actionPerformed()
3568   {
3569     SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3570             alignPanel.getViewName());
3571     SliderPanel.showPIDSlider();
3572   }
3573
3574   /**
3575    * Show the Conservation slider panel
3576    */
3577   @Override
3578   protected void modifyConservation_actionPerformed()
3579   {
3580     SliderPanel.setConservationSlider(alignPanel,
3581             viewport.getResidueShading(), alignPanel.getViewName());
3582     SliderPanel.showConservationSlider();
3583   }
3584
3585   /**
3586    * Action on selecting or deselecting (Colour) By Conservation
3587    */
3588   @Override
3589   public void conservationMenuItem_actionPerformed(boolean selected)
3590   {
3591     modifyConservation.setEnabled(selected);
3592     viewport.setConservationSelected(selected);
3593     viewport.getResidueShading().setConservationApplied(selected);
3594
3595     changeColour(viewport.getGlobalColourScheme());
3596     if (selected)
3597     {
3598       modifyConservation_actionPerformed();
3599     }
3600     else
3601     {
3602       SliderPanel.hideConservationSlider();
3603     }
3604   }
3605
3606   /**
3607    * Action on selecting or deselecting (Colour) Above PID Threshold
3608    */
3609   @Override
3610   public void abovePIDThreshold_actionPerformed(boolean selected)
3611   {
3612     modifyPID.setEnabled(selected);
3613     viewport.setAbovePIDThreshold(selected);
3614     if (!selected)
3615     {
3616       viewport.getResidueShading().setThreshold(0,
3617               viewport.isIgnoreGapsConsensus());
3618     }
3619
3620     changeColour(viewport.getGlobalColourScheme());
3621     if (selected)
3622     {
3623       modifyPID_actionPerformed();
3624     }
3625     else
3626     {
3627       SliderPanel.hidePIDSlider();
3628     }
3629   }
3630
3631   /**
3632    * DOCUMENT ME!
3633    * 
3634    * @param e
3635    *          DOCUMENT ME!
3636    */
3637   @Override
3638   public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3639   {
3640     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3641     AlignmentSorter.sortByPID(viewport.getAlignment(),
3642             viewport.getAlignment().getSequenceAt(0));
3643     addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3644             viewport.getAlignment()));
3645     alignPanel.paintAlignment(true, false);
3646   }
3647
3648   /**
3649    * DOCUMENT ME!
3650    * 
3651    * @param e
3652    *          DOCUMENT ME!
3653    */
3654   @Override
3655   public void sortIDMenuItem_actionPerformed(ActionEvent e)
3656   {
3657     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3658     AlignmentSorter.sortByID(viewport.getAlignment());
3659     addHistoryItem(
3660             new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3661     alignPanel.paintAlignment(true, false);
3662   }
3663
3664   /**
3665    * DOCUMENT ME!
3666    * 
3667    * @param e
3668    *          DOCUMENT ME!
3669    */
3670   @Override
3671   public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3672   {
3673     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3674     AlignmentSorter.sortByLength(viewport.getAlignment());
3675     addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3676             viewport.getAlignment()));
3677     alignPanel.paintAlignment(true, false);
3678   }
3679
3680   /**
3681    * DOCUMENT ME!
3682    * 
3683    * @param e
3684    *          DOCUMENT ME!
3685    */
3686   @Override
3687   public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3688   {
3689     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3690     AlignmentSorter.sortByGroup(viewport.getAlignment());
3691     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3692             viewport.getAlignment()));
3693
3694     alignPanel.paintAlignment(true, false);
3695   }
3696
3697   /**
3698    * DOCUMENT ME!
3699    * 
3700    * @param e
3701    *          DOCUMENT ME!
3702    */
3703   @Override
3704   public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3705   {
3706     new RedundancyPanel(alignPanel, this);
3707   }
3708
3709   /**
3710    * DOCUMENT ME!
3711    * 
3712    * @param e
3713    *          DOCUMENT ME!
3714    */
3715   @Override
3716   public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3717   {
3718     if ((viewport.getSelectionGroup() == null)
3719             || (viewport.getSelectionGroup().getSize() < 2))
3720     {
3721       JvOptionPane.showInternalMessageDialog(this,
3722               MessageManager.getString(
3723                       "label.you_must_select_least_two_sequences"),
3724               MessageManager.getString("label.invalid_selection"),
3725               JvOptionPane.WARNING_MESSAGE);
3726     }
3727     else
3728     {
3729       JInternalFrame frame = new JInternalFrame();
3730       frame.setContentPane(new PairwiseAlignPanel(viewport));
3731       Desktop.addInternalFrame(frame,
3732               MessageManager.getString("action.pairwise_alignment"), 600,
3733               500);
3734     }
3735   }
3736
3737   @Override
3738   public void autoCalculate_actionPerformed(ActionEvent e)
3739   {
3740     viewport.autoCalculateConsensus = autoCalculate.isSelected();
3741     if (viewport.autoCalculateConsensus)
3742     {
3743       viewport.firePropertyChange("alignment", null,
3744               viewport.getAlignment().getSequences());
3745     }
3746   }
3747
3748   @Override
3749   public void sortByTreeOption_actionPerformed(ActionEvent e)
3750   {
3751     viewport.sortByTree = sortByTree.isSelected();
3752   }
3753
3754   @Override
3755   protected void listenToViewSelections_actionPerformed(ActionEvent e)
3756   {
3757     viewport.followSelection = listenToViewSelections.isSelected();
3758   }
3759
3760   /**
3761    * Constructs a tree panel and adds it to the desktop
3762    * 
3763    * @param type
3764    *          tree type (NJ or AV)
3765    * @param modelName
3766    *          name of score model used to compute the tree
3767    * @param options
3768    *          parameters for the distance or similarity calculation
3769    */
3770   void newTreePanel(String type, String modelName,
3771           SimilarityParamsI options)
3772   {
3773     String frameTitle = "";
3774     TreePanel tp;
3775
3776     boolean onSelection = false;
3777     if (viewport.getSelectionGroup() != null
3778             && viewport.getSelectionGroup().getSize() > 0)
3779     {
3780       SequenceGroup sg = viewport.getSelectionGroup();
3781
3782       /* Decide if the selection is a column region */
3783       for (SequenceI _s : sg.getSequences())
3784       {
3785         if (_s.getLength() < sg.getEndRes())
3786         {
3787           JvOptionPane.showMessageDialog(Desktop.desktop,
3788                   MessageManager.getString(
3789                           "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3790                   MessageManager.getString(
3791                           "label.sequences_selection_not_aligned"),
3792                   JvOptionPane.WARNING_MESSAGE);
3793
3794           return;
3795         }
3796       }
3797       onSelection = true;
3798     }
3799     else
3800     {
3801       if (viewport.getAlignment().getHeight() < 2)
3802       {
3803         return;
3804       }
3805     }
3806
3807     tp = new TreePanel(alignPanel, type, modelName, options);
3808     frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3809
3810     frameTitle += " from ";
3811
3812     if (viewport.getViewName() != null)
3813     {
3814       frameTitle += viewport.getViewName() + " of ";
3815     }
3816
3817     frameTitle += this.title;
3818
3819     Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3820   }
3821
3822   /**
3823    * DOCUMENT ME!
3824    * 
3825    * @param title
3826    *          DOCUMENT ME!
3827    * @param order
3828    *          DOCUMENT ME!
3829    */
3830   public void addSortByOrderMenuItem(String title,
3831           final AlignmentOrder order)
3832   {
3833     final JMenuItem item = new JMenuItem(MessageManager
3834             .formatMessage("action.by_title_param", new Object[]
3835             { title }));
3836     sort.add(item);
3837     item.addActionListener(new java.awt.event.ActionListener()
3838     {
3839       @Override
3840       public void actionPerformed(ActionEvent e)
3841       {
3842         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3843
3844         // TODO: JBPNote - have to map order entries to curent SequenceI
3845         // pointers
3846         AlignmentSorter.sortBy(viewport.getAlignment(), order);
3847
3848         addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3849                 viewport.getAlignment()));
3850
3851         alignPanel.paintAlignment(true, false);
3852       }
3853     });
3854   }
3855
3856   /**
3857    * Add a new sort by annotation score menu item
3858    * 
3859    * @param sort
3860    *          the menu to add the option to
3861    * @param scoreLabel
3862    *          the label used to retrieve scores for each sequence on the
3863    *          alignment
3864    */
3865   public void addSortByAnnotScoreMenuItem(JMenu sort,
3866           final String scoreLabel)
3867   {
3868     final JMenuItem item = new JMenuItem(scoreLabel);
3869     sort.add(item);
3870     item.addActionListener(new java.awt.event.ActionListener()
3871     {
3872       @Override
3873       public void actionPerformed(ActionEvent e)
3874       {
3875         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3876         AlignmentSorter.sortByAnnotationScore(scoreLabel,
3877                 viewport.getAlignment());// ,viewport.getSelectionGroup());
3878         addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3879                 viewport.getAlignment()));
3880         alignPanel.paintAlignment(true, false);
3881       }
3882     });
3883   }
3884
3885   /**
3886    * last hash for alignment's annotation array - used to minimise cost of
3887    * rebuild.
3888    */
3889   protected int _annotationScoreVectorHash;
3890
3891   /**
3892    * search the alignment and rebuild the sort by annotation score submenu the
3893    * last alignment annotation vector hash is stored to minimize cost of
3894    * rebuilding in subsequence calls.
3895    * 
3896    */
3897   @Override
3898   public void buildSortByAnnotationScoresMenu()
3899   {
3900     if (viewport.getAlignment().getAlignmentAnnotation() == null)
3901     {
3902       return;
3903     }
3904
3905     if (viewport.getAlignment().getAlignmentAnnotation()
3906             .hashCode() != _annotationScoreVectorHash)
3907     {
3908       sortByAnnotScore.removeAll();
3909       // almost certainly a quicker way to do this - but we keep it simple
3910       Hashtable<String, String> scoreSorts = new Hashtable<>();
3911       AlignmentAnnotation aann[];
3912       for (SequenceI sqa : viewport.getAlignment().getSequences())
3913       {
3914         aann = sqa.getAnnotation();
3915         for (int i = 0; aann != null && i < aann.length; i++)
3916         {
3917           if (aann[i].hasScore() && aann[i].sequenceRef != null)
3918           {
3919             scoreSorts.put(aann[i].label, aann[i].label);
3920           }
3921         }
3922       }
3923       Enumeration<String> labels = scoreSorts.keys();
3924       while (labels.hasMoreElements())
3925       {
3926         addSortByAnnotScoreMenuItem(sortByAnnotScore, labels.nextElement());
3927       }
3928       sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3929       scoreSorts.clear();
3930
3931       _annotationScoreVectorHash = viewport.getAlignment()
3932               .getAlignmentAnnotation().hashCode();
3933     }
3934   }
3935
3936   /**
3937    * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3938    * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3939    * call. Listeners are added to remove the menu item when the treePanel is
3940    * closed, and adjust the tree leaf to sequence mapping when the alignment is
3941    * modified.
3942    */
3943   @Override
3944   public void buildTreeSortMenu()
3945   {
3946     sortByTreeMenu.removeAll();
3947
3948     List<Component> comps = PaintRefresher.components
3949             .get(viewport.getSequenceSetId());
3950     List<TreePanel> treePanels = new ArrayList<>();
3951     for (Component comp : comps)
3952     {
3953       if (comp instanceof TreePanel)
3954       {
3955         treePanels.add((TreePanel) comp);
3956       }
3957     }
3958
3959     if (treePanels.size() < 1)
3960     {
3961       sortByTreeMenu.setVisible(false);
3962       return;
3963     }
3964
3965     sortByTreeMenu.setVisible(true);
3966
3967     for (final TreePanel tp : treePanels)
3968     {
3969       final JMenuItem item = new JMenuItem(tp.getTitle());
3970       item.addActionListener(new java.awt.event.ActionListener()
3971       {
3972         @Override
3973         public void actionPerformed(ActionEvent e)
3974         {
3975           tp.sortByTree_actionPerformed();
3976           addHistoryItem(tp.sortAlignmentIn(alignPanel));
3977
3978         }
3979       });
3980
3981       sortByTreeMenu.add(item);
3982     }
3983   }
3984
3985   public boolean sortBy(AlignmentOrder alorder, String undoname)
3986   {
3987     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3988     AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3989     if (undoname != null)
3990     {
3991       addHistoryItem(new OrderCommand(undoname, oldOrder,
3992               viewport.getAlignment()));
3993     }
3994     alignPanel.paintAlignment(true, false);
3995     return true;
3996   }
3997
3998   /**
3999    * Work out whether the whole set of sequences or just the selected set will
4000    * be submitted for multiple alignment.
4001    * 
4002    */
4003   public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4004   {
4005     // Now, check we have enough sequences
4006     AlignmentView msa = null;
4007
4008     if ((viewport.getSelectionGroup() != null)
4009             && (viewport.getSelectionGroup().getSize() > 1))
4010     {
4011       // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4012       // some common interface!
4013       /*
4014        * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4015        * SequenceI[sz = seqs.getSize(false)];
4016        * 
4017        * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4018        * seqs.getSequenceAt(i); }
4019        */
4020       msa = viewport.getAlignmentView(true);
4021     }
4022     else if (viewport.getSelectionGroup() != null
4023             && viewport.getSelectionGroup().getSize() == 1)
4024     {
4025       int option = JvOptionPane.showConfirmDialog(this,
4026               MessageManager.getString("warn.oneseq_msainput_selection"),
4027               MessageManager.getString("label.invalid_selection"),
4028               JvOptionPane.OK_CANCEL_OPTION);
4029       if (option == JvOptionPane.OK_OPTION)
4030       {
4031         msa = viewport.getAlignmentView(false);
4032       }
4033     }
4034     else
4035     {
4036       msa = viewport.getAlignmentView(false);
4037     }
4038     return msa;
4039   }
4040
4041   /**
4042    * Decides what is submitted to a secondary structure prediction service: the
4043    * first sequence in the alignment, or in the current selection, or, if the
4044    * alignment is 'aligned' (ie padded with gaps), then the currently selected
4045    * region or the whole alignment. (where the first sequence in the set is the
4046    * one that the prediction will be for).
4047    */
4048   public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4049   {
4050     AlignmentView seqs = null;
4051
4052     if ((viewport.getSelectionGroup() != null)
4053             && (viewport.getSelectionGroup().getSize() > 0))
4054     {
4055       seqs = viewport.getAlignmentView(true);
4056     }
4057     else
4058     {
4059       seqs = viewport.getAlignmentView(false);
4060     }
4061     // limit sequences - JBPNote in future - could spawn multiple prediction
4062     // jobs
4063     // TODO: viewport.getAlignment().isAligned is a global state - the local
4064     // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4065     if (!viewport.getAlignment().isAligned(false))
4066     {
4067       seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4068       // TODO: if seqs.getSequences().length>1 then should really have warned
4069       // user!
4070
4071     }
4072     return seqs;
4073   }
4074
4075   /**
4076    * DOCUMENT ME!
4077    * 
4078    * @param e
4079    *          DOCUMENT ME!
4080    */
4081   @Override
4082   protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4083   {
4084     // Pick the tree file
4085     JalviewFileChooser chooser = new JalviewFileChooser(
4086             Cache.getProperty("LAST_DIRECTORY"));
4087     chooser.setFileView(new JalviewFileView());
4088     chooser.setDialogTitle(
4089             MessageManager.getString("label.select_newick_like_tree_file"));
4090     chooser.setToolTipText(
4091             MessageManager.getString("label.load_tree_file"));
4092
4093     chooser.setResponseHandler(0, () -> {
4094       String filePath = chooser.getSelectedFile().getPath();
4095       Cache.setProperty("LAST_DIRECTORY", filePath);
4096       NewickFile fin = null;
4097       try
4098       {
4099         fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4100                 DataSourceType.FILE));
4101         viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4102       } catch (Exception ex)
4103       {
4104         JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4105                 MessageManager.getString("label.problem_reading_tree_file"),
4106                 JvOptionPane.WARNING_MESSAGE);
4107         ex.printStackTrace();
4108       }
4109       if (fin != null && fin.hasWarningMessage())
4110       {
4111         JvOptionPane.showMessageDialog(Desktop.desktop,
4112                 fin.getWarningMessage(),
4113                 MessageManager
4114                         .getString("label.possible_problem_with_tree_file"),
4115                 JvOptionPane.WARNING_MESSAGE);
4116       }
4117       return null;
4118     });
4119     chooser.showOpenDialog(this);
4120   }
4121
4122   public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4123   {
4124     return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4125   }
4126
4127   public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4128           int h, int x, int y)
4129   {
4130     return showNewickTree(nf, treeTitle, null, w, h, x, y);
4131   }
4132
4133   /**
4134    * Add a treeviewer for the tree extracted from a Newick file object to the
4135    * current alignment view
4136    * 
4137    * @param nf
4138    *          the tree
4139    * @param title
4140    *          tree viewer title
4141    * @param input
4142    *          Associated alignment input data (or null)
4143    * @param w
4144    *          width
4145    * @param h
4146    *          height
4147    * @param x
4148    *          position
4149    * @param y
4150    *          position
4151    * @return TreePanel handle
4152    */
4153   public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4154           AlignmentView input, int w, int h, int x, int y)
4155   {
4156     TreePanel tp = null;
4157
4158     try
4159     {
4160       nf.parse();
4161
4162       if (nf.getTree() != null)
4163       {
4164         tp = new TreePanel(alignPanel, nf, treeTitle, input);
4165
4166         tp.setSize(w, h);
4167
4168         if (x > 0 && y > 0)
4169         {
4170           tp.setLocation(x, y);
4171         }
4172
4173         Desktop.addInternalFrame(tp, treeTitle, w, h);
4174       }
4175     } catch (Exception ex)
4176     {
4177       ex.printStackTrace();
4178     }
4179
4180     return tp;
4181   }
4182
4183   private boolean buildingMenu = false;
4184
4185   /**
4186    * Generates menu items and listener event actions for web service clients
4187    * 
4188    */
4189   public void BuildWebServiceMenu()
4190   {
4191     while (buildingMenu)
4192     {
4193       try
4194       {
4195         System.err.println("Waiting for building menu to finish.");
4196         Thread.sleep(10);
4197       } catch (Exception e)
4198       {
4199       }
4200     }
4201     final AlignFrame me = this;
4202     buildingMenu = true;
4203     new Thread(new Runnable()
4204     {
4205       @Override
4206       public void run()
4207       {
4208         final List<JMenuItem> legacyItems = new ArrayList<>();
4209         try
4210         {
4211           // System.err.println("Building ws menu again "
4212           // + Thread.currentThread());
4213           // TODO: add support for context dependent disabling of services based
4214           // on
4215           // alignment and current selection
4216           // TODO: add additional serviceHandle parameter to specify abstract
4217           // handler
4218           // class independently of AbstractName
4219           // TODO: add in rediscovery GUI function to restart discoverer
4220           // TODO: group services by location as well as function and/or
4221           // introduce
4222           // object broker mechanism.
4223           final Vector<JMenu> wsmenu = new Vector<>();
4224           final IProgressIndicator af = me;
4225
4226           /*
4227            * do not i18n these strings - they are hard-coded in class
4228            * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4229            * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4230            */
4231           final JMenu msawsmenu = new JMenu("Alignment");
4232           final JMenu secstrmenu = new JMenu(
4233                   "Secondary Structure Prediction");
4234           final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4235           final JMenu analymenu = new JMenu("Analysis");
4236           final JMenu dismenu = new JMenu("Protein Disorder");
4237           // JAL-940 - only show secondary structure prediction services from
4238           // the legacy server
4239           if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4240               // &&
4241           Discoverer.services != null && (Discoverer.services.size() > 0))
4242           {
4243             // TODO: refactor to allow list of AbstractName/Handler bindings to
4244             // be
4245             // stored or retrieved from elsewhere
4246             // No MSAWS used any more:
4247             // Vector msaws = null; // (Vector)
4248             // Discoverer.services.get("MsaWS");
4249             Vector<ServiceHandle> secstrpr = Discoverer.services
4250                     .get("SecStrPred");
4251             if (secstrpr != null)
4252             {
4253               // Add any secondary structure prediction services
4254               for (int i = 0, j = secstrpr.size(); i < j; i++)
4255               {
4256                 final ext.vamsas.ServiceHandle sh = secstrpr.get(i);
4257                 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4258                         .getServiceClient(sh);
4259                 int p = secstrmenu.getItemCount();
4260                 impl.attachWSMenuEntry(secstrmenu, me);
4261                 int q = secstrmenu.getItemCount();
4262                 for (int litm = p; litm < q; litm++)
4263                 {
4264                   legacyItems.add(secstrmenu.getItem(litm));
4265                 }
4266               }
4267             }
4268           }
4269
4270           // Add all submenus in the order they should appear on the web
4271           // services menu
4272           wsmenu.add(msawsmenu);
4273           wsmenu.add(secstrmenu);
4274           wsmenu.add(dismenu);
4275           wsmenu.add(analymenu);
4276           // No search services yet
4277           // wsmenu.add(seqsrchmenu);
4278
4279           javax.swing.SwingUtilities.invokeLater(new Runnable()
4280           {
4281             @Override
4282             public void run()
4283             {
4284               try
4285               {
4286                 webService.removeAll();
4287                 // first, add discovered services onto the webservices menu
4288                 if (wsmenu.size() > 0)
4289                 {
4290                   for (int i = 0, j = wsmenu.size(); i < j; i++)
4291                   {
4292                     webService.add(wsmenu.get(i));
4293                   }
4294                 }
4295                 else
4296                 {
4297                   webService.add(me.webServiceNoServices);
4298                 }
4299                 // TODO: move into separate menu builder class.
4300                 {
4301                   // logic for 2.11.1.4 is
4302                   // always look to see if there is a discover. if there isn't
4303                   // we can't show any Jws2 services
4304                   // if there are services available, show them - regardless of
4305                   // the 'show JWS2 preference'
4306                   // if the discoverer is running then say so
4307                   // otherwise offer to trigger discovery if 'show JWS2' is not
4308                   // enabled
4309                   Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4310                   if (jws2servs != null)
4311                   {
4312                     if (jws2servs.hasServices())
4313                     {
4314                       jws2servs.attachWSMenuEntry(webService, me);
4315                       for (Jws2Instance sv : jws2servs.getServices())
4316                       {
4317                         if (sv.description.toLowerCase(Locale.ROOT)
4318                                 .contains("jpred"))
4319                         {
4320                           for (JMenuItem jmi : legacyItems)
4321                           {
4322                             jmi.setVisible(false);
4323                           }
4324                         }
4325                       }
4326                     }
4327
4328                     if (jws2servs.isRunning())
4329                     {
4330                       JMenuItem tm = new JMenuItem(
4331                               "Still discovering JABA Services");
4332                       tm.setEnabled(false);
4333                       webService.add(tm);
4334                     }
4335                     else if (!Cache.getDefault("SHOW_JWS2_SERVICES", true))
4336                     {
4337                       JMenuItem enableJws2 = new JMenuItem(
4338                               "Discover Web Services");
4339                       enableJws2.setToolTipText(
4340                               "Select to start JABA Web Service discovery (or enable option in Web Service preferences)");
4341                       enableJws2.setEnabled(true);
4342                       enableJws2.addActionListener(new ActionListener()
4343                       {
4344
4345                         @Override
4346                         public void actionPerformed(ActionEvent e)
4347                         {
4348                           // start service discoverer, but ignore preference
4349                           Desktop.instance.startServiceDiscovery(false,
4350                                   true);
4351                         }
4352                       });
4353                       webService.add(enableJws2);
4354                     }
4355                   }
4356                 }
4357                 build_urlServiceMenu(me.webService);
4358                 build_fetchdbmenu(webService);
4359                 for (JMenu item : wsmenu)
4360                 {
4361                   if (item.getItemCount() == 0)
4362                   {
4363                     item.setEnabled(false);
4364                   }
4365                   else
4366                   {
4367                     item.setEnabled(true);
4368                   }
4369                 }
4370               } catch (Exception e)
4371               {
4372                 Console.debug(
4373                         "Exception during web service menu building process.",
4374                         e);
4375               }
4376             }
4377           });
4378         } catch (Exception e)
4379         {
4380         }
4381         buildingMenu = false;
4382       }
4383     }).start();
4384
4385   }
4386
4387   /**
4388    * construct any groupURL type service menu entries.
4389    * 
4390    * @param webService
4391    */
4392   protected void build_urlServiceMenu(JMenu webService)
4393   {
4394     // TODO: remove this code when 2.7 is released
4395     // DEBUG - alignmentView
4396     /*
4397      * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4398      * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4399      * 
4400      * @Override public void actionPerformed(ActionEvent e) {
4401      * jalview.datamodel.AlignmentView
4402      * .testSelectionViews(af.viewport.getAlignment(),
4403      * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4404      * 
4405      * }); webService.add(testAlView);
4406      */
4407     // TODO: refactor to RestClient discoverer and merge menu entries for
4408     // rest-style services with other types of analysis/calculation service
4409     // SHmmr test client - still being implemented.
4410     // DEBUG - alignmentView
4411
4412     for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4413             .getRestClients())
4414     {
4415       client.attachWSMenuEntry(
4416               JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4417               this);
4418     }
4419   }
4420
4421   /**
4422    * Searches the alignment sequences for xRefs and builds the Show
4423    * Cross-References menu (formerly called Show Products), with database
4424    * sources for which cross-references are found (protein sources for a
4425    * nucleotide alignment and vice versa)
4426    * 
4427    * @return true if Show Cross-references menu should be enabled
4428    */
4429   public boolean canShowProducts()
4430   {
4431     SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4432     AlignmentI dataset = viewport.getAlignment().getDataset();
4433
4434     showProducts.removeAll();
4435     final boolean dna = viewport.getAlignment().isNucleotide();
4436
4437     if (seqs == null || seqs.length == 0)
4438     {
4439       // nothing to see here.
4440       return false;
4441     }
4442
4443     boolean showp = false;
4444     try
4445     {
4446       List<String> ptypes = new CrossRef(seqs, dataset)
4447               .findXrefSourcesForSequences(dna);
4448
4449       for (final String source : ptypes)
4450       {
4451         showp = true;
4452         final AlignFrame af = this;
4453         JMenuItem xtype = new JMenuItem(source);
4454         xtype.addActionListener(new ActionListener()
4455         {
4456           @Override
4457           public void actionPerformed(ActionEvent e)
4458           {
4459             showProductsFor(af.viewport.getSequenceSelection(), dna,
4460                     source);
4461           }
4462         });
4463         showProducts.add(xtype);
4464       }
4465       showProducts.setVisible(showp);
4466       showProducts.setEnabled(showp);
4467     } catch (Exception e)
4468     {
4469       Console.warn(
4470               "canShowProducts threw an exception - please report to help@jalview.org",
4471               e);
4472       return false;
4473     }
4474     return showp;
4475   }
4476
4477   /**
4478    * Finds and displays cross-references for the selected sequences (protein
4479    * products for nucleotide sequences, dna coding sequences for peptides).
4480    * 
4481    * @param sel
4482    *          the sequences to show cross-references for
4483    * @param dna
4484    *          true if from a nucleotide alignment (so showing proteins)
4485    * @param source
4486    *          the database to show cross-references for
4487    */
4488   protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4489           final String source)
4490   {
4491     new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4492             .start();
4493   }
4494
4495   /**
4496    * Construct and display a new frame containing the translation of this
4497    * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4498    */
4499   @Override
4500   public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4501   {
4502     AlignmentI al = null;
4503     try
4504     {
4505       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4506
4507       al = dna.translateCdna(codeTable);
4508     } catch (Exception ex)
4509     {
4510       Console.error("Exception during translation. Please report this !",
4511               ex);
4512       final String msg = MessageManager.getString(
4513               "label.error_when_translating_sequences_submit_bug_report");
4514       final String errorTitle = MessageManager
4515               .getString("label.implementation_error")
4516               + MessageManager.getString("label.translation_failed");
4517       JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4518               JvOptionPane.ERROR_MESSAGE);
4519       return;
4520     }
4521     if (al == null || al.getHeight() == 0)
4522     {
4523       final String msg = MessageManager.getString(
4524               "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4525       final String errorTitle = MessageManager
4526               .getString("label.translation_failed");
4527       JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4528               JvOptionPane.WARNING_MESSAGE);
4529     }
4530     else
4531     {
4532       AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4533       af.setFileFormat(this.currentFileFormat);
4534       final String newTitle = MessageManager
4535               .formatMessage("label.translation_of_params", new Object[]
4536               { this.getTitle(), codeTable.getId() });
4537       af.setTitle(newTitle);
4538       if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4539       {
4540         final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4541         viewport.openSplitFrame(af, new Alignment(seqs));
4542       }
4543       else
4544       {
4545         Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4546                 DEFAULT_HEIGHT);
4547       }
4548     }
4549   }
4550
4551   /**
4552    * Set the file format
4553    * 
4554    * @param format
4555    */
4556   public void setFileFormat(FileFormatI format)
4557   {
4558     this.currentFileFormat = format;
4559   }
4560
4561   /**
4562    * Try to load a features file onto the alignment.
4563    * 
4564    * @param file
4565    *          contents or path to retrieve file or a File object
4566    * @param sourceType
4567    *          access mode of file (see jalview.io.AlignFile)
4568    * @return true if features file was parsed correctly.
4569    */
4570   public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4571   {
4572     // BH 2018
4573     return avc.parseFeaturesFile(file, sourceType,
4574             Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4575
4576   }
4577
4578   @Override
4579   public void refreshFeatureUI(boolean enableIfNecessary)
4580   {
4581     // note - currently this is only still here rather than in the controller
4582     // because of the featureSettings hard reference that is yet to be
4583     // abstracted
4584     if (enableIfNecessary)
4585     {
4586       viewport.setShowSequenceFeatures(true);
4587       showSeqFeatures.setSelected(true);
4588     }
4589
4590   }
4591
4592   @Override
4593   public void dragEnter(DropTargetDragEvent evt)
4594   {
4595   }
4596
4597   @Override
4598   public void dragExit(DropTargetEvent evt)
4599   {
4600   }
4601
4602   @Override
4603   public void dragOver(DropTargetDragEvent evt)
4604   {
4605   }
4606
4607   @Override
4608   public void dropActionChanged(DropTargetDragEvent evt)
4609   {
4610   }
4611
4612   @Override
4613   public void drop(DropTargetDropEvent evt)
4614   {
4615     // JAL-1552 - acceptDrop required before getTransferable call for
4616     // Java's Transferable for native dnd
4617     evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4618     Transferable t = evt.getTransferable();
4619
4620     final AlignFrame thisaf = this;
4621     final List<Object> files = new ArrayList<>();
4622     List<DataSourceType> protocols = new ArrayList<>();
4623
4624     try
4625     {
4626       Desktop.transferFromDropTarget(files, protocols, evt, t);
4627     } catch (Exception e)
4628     {
4629       e.printStackTrace();
4630     }
4631     if (files != null)
4632     {
4633       new Thread(new Runnable()
4634       {
4635         @Override
4636         public void run()
4637         {
4638           try
4639           {
4640             // check to see if any of these files have names matching sequences
4641             // in
4642             // the alignment
4643             SequenceIdMatcher idm = new SequenceIdMatcher(
4644                     viewport.getAlignment().getSequencesArray());
4645             /**
4646              * Object[] { String,SequenceI}
4647              */
4648             ArrayList<Object[]> filesmatched = new ArrayList<>();
4649             ArrayList<Object> filesnotmatched = new ArrayList<>();
4650             for (int i = 0; i < files.size(); i++)
4651             {
4652               // BH 2018
4653               Object file = files.get(i);
4654               String fileName = file.toString();
4655               String pdbfn = "";
4656               DataSourceType protocol = (file instanceof File
4657                       ? DataSourceType.FILE
4658                       : FormatAdapter.checkProtocol(fileName));
4659               if (protocol == DataSourceType.FILE)
4660               {
4661                 File fl;
4662                 if (file instanceof File)
4663                 {
4664                   fl = (File) file;
4665                   Platform.cacheFileData(fl);
4666                 }
4667                 else
4668                 {
4669                   fl = new File(fileName);
4670                 }
4671                 pdbfn = fl.getName();
4672               }
4673               else if (protocol == DataSourceType.URL)
4674               {
4675                 URL url = new URL(fileName);
4676                 pdbfn = url.getFile();
4677               }
4678               if (pdbfn.length() > 0)
4679               {
4680                 // attempt to find a match in the alignment
4681                 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4682                 int l = 0, c = pdbfn.indexOf(".");
4683                 while (mtch == null && c != -1)
4684                 {
4685                   do
4686                   {
4687                     l = c;
4688                   } while ((c = pdbfn.indexOf(".", l)) > l);
4689                   if (l > -1)
4690                   {
4691                     pdbfn = pdbfn.substring(0, l);
4692                   }
4693                   mtch = idm.findAllIdMatches(pdbfn);
4694                 }
4695                 if (mtch != null)
4696                 {
4697                   FileFormatI type;
4698                   try
4699                   {
4700                     type = new IdentifyFile().identify(file, protocol);
4701                   } catch (Exception ex)
4702                   {
4703                     type = null;
4704                   }
4705                   if (type != null && type.isStructureFile())
4706                   {
4707                     filesmatched.add(new Object[] { file, protocol, mtch });
4708                     continue;
4709                   }
4710                 }
4711                 // File wasn't named like one of the sequences or wasn't a PDB
4712                 // file.
4713                 filesnotmatched.add(file);
4714               }
4715             }
4716             int assocfiles = 0;
4717             if (filesmatched.size() > 0)
4718             {
4719               boolean autoAssociate = Cache
4720                       .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4721               if (!autoAssociate)
4722               {
4723                 String msg = MessageManager.formatMessage(
4724                         "label.automatically_associate_structure_files_with_sequences_same_name",
4725                         new Object[]
4726                         { Integer.valueOf(filesmatched.size())
4727                                 .toString() });
4728                 String ttl = MessageManager.getString(
4729                         "label.automatically_associate_structure_files_by_name");
4730                 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4731                         ttl, JvOptionPane.YES_NO_OPTION);
4732                 autoAssociate = choice == JvOptionPane.YES_OPTION;
4733               }
4734               if (autoAssociate)
4735               {
4736                 for (Object[] fm : filesmatched)
4737                 {
4738                   // try and associate
4739                   // TODO: may want to set a standard ID naming formalism for
4740                   // associating PDB files which have no IDs.
4741                   for (SequenceI toassoc : (SequenceI[]) fm[2])
4742                   {
4743                     PDBEntry pe = new AssociatePdbFileWithSeq()
4744                             .associatePdbWithSeq(fm[0].toString(),
4745                                     (DataSourceType) fm[1], toassoc, false,
4746                                     Desktop.instance);
4747                     if (pe != null)
4748                     {
4749                       System.err.println("Associated file : "
4750                               + (fm[0].toString()) + " with "
4751                               + toassoc.getDisplayId(true));
4752                       assocfiles++;
4753                     }
4754                   }
4755                   // TODO: do we need to update overview ? only if features are
4756                   // shown I guess
4757                   alignPanel.paintAlignment(true, false);
4758                 }
4759               }
4760               else
4761               {
4762                 /*
4763                  * add declined structures as sequences
4764                  */
4765                 for (Object[] o : filesmatched)
4766                 {
4767                   filesnotmatched.add(o[0]);
4768                 }
4769               }
4770             }
4771             if (filesnotmatched.size() > 0)
4772             {
4773               if (assocfiles > 0 && (Cache.getDefault(
4774                       "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4775                       || JvOptionPane.showConfirmDialog(thisaf,
4776                               "<html>" + MessageManager.formatMessage(
4777                                       "label.ignore_unmatched_dropped_files_info",
4778                                       new Object[]
4779                                       { Integer.valueOf(
4780                                               filesnotmatched.size())
4781                                               .toString() })
4782                                       + "</html>",
4783                               MessageManager.getString(
4784                                       "label.ignore_unmatched_dropped_files"),
4785                               JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4786               {
4787                 return;
4788               }
4789               for (Object fn : filesnotmatched)
4790               {
4791                 loadJalviewDataFile(fn, null, null, null);
4792               }
4793
4794             }
4795           } catch (Exception ex)
4796           {
4797             ex.printStackTrace();
4798           }
4799         }
4800       }).start();
4801     }
4802   }
4803
4804   /**
4805    * Attempt to load a "dropped" file or URL string, by testing in turn for
4806    * <ul>
4807    * <li>an Annotation file</li>
4808    * <li>a JNet file</li>
4809    * <li>a features file</li>
4810    * <li>else try to interpret as an alignment file</li>
4811    * </ul>
4812    * 
4813    * @param file
4814    *          either a filename or a URL string.
4815    */
4816   public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4817           FileFormatI format, SequenceI assocSeq)
4818   {
4819     // BH 2018 was String file
4820     try
4821     {
4822       if (sourceType == null)
4823       {
4824         sourceType = FormatAdapter.checkProtocol(file);
4825       }
4826       // if the file isn't identified, or not positively identified as some
4827       // other filetype (PFAM is default unidentified alignment file type) then
4828       // try to parse as annotation.
4829       boolean isAnnotation = (format == null
4830               || FileFormat.Pfam.equals(format))
4831                       ? new AnnotationFile().annotateAlignmentView(viewport,
4832                               file, sourceType)
4833                       : false;
4834
4835       if (!isAnnotation)
4836       {
4837         // first see if its a T-COFFEE score file
4838         TCoffeeScoreFile tcf = null;
4839         try
4840         {
4841           tcf = new TCoffeeScoreFile(file, sourceType);
4842           if (tcf.isValid())
4843           {
4844             if (tcf.annotateAlignment(viewport.getAlignment(), true))
4845             {
4846               buildColourMenu();
4847               changeColour(
4848                       new TCoffeeColourScheme(viewport.getAlignment()));
4849               isAnnotation = true;
4850               setStatus(MessageManager.getString(
4851                       "label.successfully_pasted_tcoffee_scores_to_alignment"));
4852             }
4853             else
4854             {
4855               // some problem - if no warning its probable that the ID matching
4856               // process didn't work
4857               JvOptionPane.showMessageDialog(Desktop.desktop,
4858                       tcf.getWarningMessage() == null
4859                               ? MessageManager.getString(
4860                                       "label.check_file_matches_sequence_ids_alignment")
4861                               : tcf.getWarningMessage(),
4862                       MessageManager.getString(
4863                               "label.problem_reading_tcoffee_score_file"),
4864                       JvOptionPane.WARNING_MESSAGE);
4865             }
4866           }
4867           else
4868           {
4869             tcf = null;
4870           }
4871         } catch (Exception x)
4872         {
4873           Console.debug(
4874                   "Exception when processing data source as T-COFFEE score file",
4875                   x);
4876           tcf = null;
4877         }
4878         if (tcf == null)
4879         {
4880           // try to see if its a JNet 'concise' style annotation file *before*
4881           // we
4882           // try to parse it as a features file
4883           if (format == null)
4884           {
4885             format = new IdentifyFile().identify(file, sourceType);
4886           }
4887           if (FileFormat.ScoreMatrix == format)
4888           {
4889             ScoreMatrixFile sm = new ScoreMatrixFile(
4890                     new FileParse(file, sourceType));
4891             sm.parse();
4892             // todo: i18n this message
4893             setStatus(MessageManager.formatMessage(
4894                     "label.successfully_loaded_matrix",
4895                     sm.getMatrixName()));
4896           }
4897           else if (FileFormat.Jnet.equals(format))
4898           {
4899             JPredFile predictions = new JPredFile(file, sourceType);
4900             new JnetAnnotationMaker();
4901             JnetAnnotationMaker.add_annotation(predictions,
4902                     viewport.getAlignment(), 0, false);
4903             viewport.getAlignment().setupJPredAlignment();
4904             isAnnotation = true;
4905           }
4906           // else if (IdentifyFile.FeaturesFile.equals(format))
4907           else if (FileFormat.Features.equals(format))
4908           {
4909             if (parseFeaturesFile(file, sourceType))
4910             {
4911               SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
4912               if (splitFrame != null)
4913               {
4914                 splitFrame.repaint();
4915               }
4916               else
4917               {
4918                 alignPanel.paintAlignment(true, true);
4919               }
4920             }
4921           }
4922           else
4923           {
4924             new FileLoader().LoadFile(viewport, file, sourceType, format);
4925           }
4926         }
4927       }
4928       if (isAnnotation)
4929       {
4930
4931         alignPanel.adjustAnnotationHeight();
4932         viewport.updateSequenceIdColours();
4933         buildSortByAnnotationScoresMenu();
4934         alignPanel.paintAlignment(true, true);
4935       }
4936     } catch (Exception ex)
4937     {
4938       ex.printStackTrace();
4939     } catch (OutOfMemoryError oom)
4940     {
4941       try
4942       {
4943         System.gc();
4944       } catch (Exception x)
4945       {
4946       }
4947       new OOMWarning(
4948               "loading data "
4949                       + (sourceType != null
4950                               ? (sourceType == DataSourceType.PASTE
4951                                       ? "from clipboard."
4952                                       : "using " + sourceType + " from "
4953                                               + file)
4954                               : ".")
4955                       + (format != null
4956                               ? "(parsing as '" + format + "' file)"
4957                               : ""),
4958               oom, Desktop.desktop);
4959     }
4960   }
4961
4962   /**
4963    * Method invoked by the ChangeListener on the tabbed pane, in other words
4964    * when a different tabbed pane is selected by the user or programmatically.
4965    */
4966   @Override
4967   public void tabSelectionChanged(int index)
4968   {
4969     if (index > -1)
4970     {
4971       /*
4972        * update current Overview window title (if there is one)
4973        * to add view name "Original" if necessary
4974        */
4975       alignPanel.setOverviewTitle(this);
4976       
4977       /*
4978        * switch panels and set Overview title (if there is one
4979        * because it was opened automatically)
4980        */
4981       alignPanel = alignPanels.get(index);
4982       alignPanel.setOverviewTitle(this);
4983
4984       viewport = alignPanel.av;
4985       avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4986       setMenusFromViewport(viewport);
4987       if (featureSettings != null && featureSettings.isOpen()
4988               && featureSettings.fr.getViewport() != viewport)
4989       {
4990         if (viewport.isShowSequenceFeatures())
4991         {
4992           // refresh the featureSettings to reflect UI change
4993           showFeatureSettingsUI();
4994         }
4995         else
4996         {
4997           // close feature settings for this view.
4998           featureSettings.close();
4999         }
5000       }
5001
5002     }
5003
5004     /*
5005      * 'focus' any colour slider that is open to the selected viewport
5006      */
5007     if (viewport.getConservationSelected())
5008     {
5009       SliderPanel.setConservationSlider(alignPanel,
5010               viewport.getResidueShading(), alignPanel.getViewName());
5011     }
5012     else
5013     {
5014       SliderPanel.hideConservationSlider();
5015     }
5016     if (viewport.getAbovePIDThreshold())
5017     {
5018       SliderPanel.setPIDSliderSource(alignPanel,
5019               viewport.getResidueShading(), alignPanel.getViewName());
5020     }
5021     else
5022     {
5023       SliderPanel.hidePIDSlider();
5024     }
5025
5026     /*
5027      * If there is a frame linked to this one in a SplitPane, switch it to the
5028      * same view tab index. No infinite recursion of calls should happen, since
5029      * tabSelectionChanged() should not get invoked on setting the selected
5030      * index to an unchanged value. Guard against setting an invalid index
5031      * before the new view peer tab has been created.
5032      */
5033     final AlignViewportI peer = viewport.getCodingComplement();
5034     if (peer != null)
5035     {
5036       AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5037               .getAlignPanel().alignFrame;
5038       if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5039       {
5040         linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5041       }
5042     }
5043   }
5044
5045   /**
5046    * On right mouse click on view tab, prompt for and set new view name.
5047    */
5048   @Override
5049   public void tabbedPane_mousePressed(MouseEvent e)
5050   {
5051     if (e.isPopupTrigger())
5052     {
5053       String msg = MessageManager.getString("label.enter_view_name");
5054       String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5055       String reply = JvOptionPane.showInputDialog(msg, ttl);
5056
5057       if (reply != null)
5058       {
5059         viewport.setViewName(reply);
5060         // TODO warn if reply is in getExistingViewNames()?
5061         tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5062       }
5063     }
5064   }
5065
5066   public AlignViewport getCurrentView()
5067   {
5068     return viewport;
5069   }
5070
5071   /**
5072    * Open the dialog for regex description parsing.
5073    */
5074   @Override
5075   protected void extractScores_actionPerformed(ActionEvent e)
5076   {
5077     ParseProperties pp = new jalview.analysis.ParseProperties(
5078             viewport.getAlignment());
5079     // TODO: verify regex and introduce GUI dialog for version 2.5
5080     // if (pp.getScoresFromDescription("col", "score column ",
5081     // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5082     // true)>0)
5083     if (pp.getScoresFromDescription("description column",
5084             "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5085     {
5086       buildSortByAnnotationScoresMenu();
5087     }
5088   }
5089
5090   /*
5091    * (non-Javadoc)
5092    * 
5093    * @see
5094    * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5095    * )
5096    */
5097   @Override
5098   protected void showDbRefs_actionPerformed(ActionEvent e)
5099   {
5100     viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5101   }
5102
5103   /*
5104    * (non-Javadoc)
5105    * 
5106    * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5107    * ActionEvent)
5108    */
5109   @Override
5110   protected void showNpFeats_actionPerformed(ActionEvent e)
5111   {
5112     viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5113   }
5114
5115   /**
5116    * find the viewport amongst the tabs in this alignment frame and close that
5117    * tab
5118    * 
5119    * @param av
5120    */
5121   public boolean closeView(AlignViewportI av)
5122   {
5123     if (viewport == av)
5124     {
5125       this.closeMenuItem_actionPerformed(false);
5126       return true;
5127     }
5128     Component[] comp = tabbedPane.getComponents();
5129     for (int i = 0; comp != null && i < comp.length; i++)
5130     {
5131       if (comp[i] instanceof AlignmentPanel)
5132       {
5133         if (((AlignmentPanel) comp[i]).av == av)
5134         {
5135           // close the view.
5136           closeView((AlignmentPanel) comp[i]);
5137           return true;
5138         }
5139       }
5140     }
5141     return false;
5142   }
5143
5144   protected void build_fetchdbmenu(JMenu webService)
5145   {
5146     // Temporary hack - DBRef Fetcher always top level ws entry.
5147     // TODO We probably want to store a sequence database checklist in
5148     // preferences and have checkboxes.. rather than individual sources selected
5149     // here
5150     final JMenu rfetch = new JMenu(
5151             MessageManager.getString("action.fetch_db_references"));
5152     rfetch.setToolTipText(MessageManager.getString(
5153             "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5154     webService.add(rfetch);
5155
5156     final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5157             MessageManager.getString("option.trim_retrieved_seqs"));
5158     trimrs.setToolTipText(
5159             MessageManager.getString("label.trim_retrieved_sequences"));
5160     trimrs.setSelected(
5161             Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5162     trimrs.addActionListener(new ActionListener()
5163     {
5164       @Override
5165       public void actionPerformed(ActionEvent e)
5166       {
5167         trimrs.setSelected(trimrs.isSelected());
5168         Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5169                 Boolean.valueOf(trimrs.isSelected()).toString());
5170       }
5171     });
5172     rfetch.add(trimrs);
5173     JMenuItem fetchr = new JMenuItem(
5174             MessageManager.getString("label.standard_databases"));
5175     fetchr.setToolTipText(
5176             MessageManager.getString("label.fetch_embl_uniprot"));
5177     fetchr.addActionListener(new ActionListener()
5178     {
5179
5180       @Override
5181       public void actionPerformed(ActionEvent e)
5182       {
5183         new Thread(new Runnable()
5184         {
5185           @Override
5186           public void run()
5187           {
5188             boolean isNucleotide = alignPanel.alignFrame.getViewport()
5189                     .getAlignment().isNucleotide();
5190             DBRefFetcher dbRefFetcher = new DBRefFetcher(
5191                     alignPanel.av.getSequenceSelection(),
5192                     alignPanel.alignFrame, null,
5193                     alignPanel.alignFrame.featureSettings, isNucleotide);
5194             dbRefFetcher.addListener(new FetchFinishedListenerI()
5195             {
5196               @Override
5197               public void finished()
5198               {
5199
5200                 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5201                         .getFeatureSettingsModels())
5202                 {
5203
5204                   alignPanel.av.mergeFeaturesStyle(srcSettings);
5205                 }
5206                 AlignFrame.this.setMenusForViewport();
5207               }
5208             });
5209             dbRefFetcher.fetchDBRefs(false);
5210           }
5211         }).start();
5212
5213       }
5214
5215     });
5216     rfetch.add(fetchr);
5217     new Thread(new Runnable()
5218     {
5219       @Override
5220       public void run()
5221       {
5222         final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5223                 .getSequenceFetcherSingleton();
5224         javax.swing.SwingUtilities.invokeLater(new Runnable()
5225         {
5226           @Override
5227           public void run()
5228           {
5229             String[] dbclasses = sf.getNonAlignmentSources();
5230             List<DbSourceProxy> otherdb;
5231             JMenu dfetch = new JMenu();
5232             JMenu ifetch = new JMenu();
5233             JMenuItem fetchr = null;
5234             int comp = 0, icomp = 0, mcomp = 15;
5235             String mname = null;
5236             int dbi = 0;
5237             for (String dbclass : dbclasses)
5238             {
5239               otherdb = sf.getSourceProxy(dbclass);
5240               // add a single entry for this class, or submenu allowing 'fetch
5241               // all' or pick one
5242               if (otherdb == null || otherdb.size() < 1)
5243               {
5244                 continue;
5245               }
5246               if (mname == null)
5247               {
5248                 mname = "From " + dbclass;
5249               }
5250               if (otherdb.size() == 1)
5251               {
5252                 final DbSourceProxy[] dassource = otherdb
5253                         .toArray(new DbSourceProxy[0]);
5254                 DbSourceProxy src = otherdb.get(0);
5255                 fetchr = new JMenuItem(src.getDbSource());
5256                 fetchr.addActionListener(new ActionListener()
5257                 {
5258
5259                   @Override
5260                   public void actionPerformed(ActionEvent e)
5261                   {
5262                     new Thread(new Runnable()
5263                     {
5264
5265                       @Override
5266                       public void run()
5267                       {
5268                         boolean isNucleotide = alignPanel.alignFrame
5269                                 .getViewport().getAlignment()
5270                                 .isNucleotide();
5271                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5272                                 alignPanel.av.getSequenceSelection(),
5273                                 alignPanel.alignFrame, dassource,
5274                                 alignPanel.alignFrame.featureSettings,
5275                                 isNucleotide);
5276                         dbRefFetcher
5277                                 .addListener(new FetchFinishedListenerI()
5278                                 {
5279                                   @Override
5280                                   public void finished()
5281                                   {
5282                                     FeatureSettingsModelI srcSettings = dassource[0]
5283                                             .getFeatureColourScheme();
5284                                     alignPanel.av.mergeFeaturesStyle(
5285                                             srcSettings);
5286                                     AlignFrame.this.setMenusForViewport();
5287                                   }
5288                                 });
5289                         dbRefFetcher.fetchDBRefs(false);
5290                       }
5291                     }).start();
5292                   }
5293
5294                 });
5295                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5296                         MessageManager.formatMessage(
5297                                 "label.fetch_retrieve_from", new Object[]
5298                                 { src.getDbName() })));
5299                 dfetch.add(fetchr);
5300                 comp++;
5301               }
5302               else
5303               {
5304                 final DbSourceProxy[] dassource = otherdb
5305                         .toArray(new DbSourceProxy[0]);
5306                 // fetch all entry
5307                 DbSourceProxy src = otherdb.get(0);
5308                 fetchr = new JMenuItem(MessageManager
5309                         .formatMessage("label.fetch_all_param", new Object[]
5310                         { src.getDbSource() }));
5311                 fetchr.addActionListener(new ActionListener()
5312                 {
5313                   @Override
5314                   public void actionPerformed(ActionEvent e)
5315                   {
5316                     new Thread(new Runnable()
5317                     {
5318
5319                       @Override
5320                       public void run()
5321                       {
5322                         boolean isNucleotide = alignPanel.alignFrame
5323                                 .getViewport().getAlignment()
5324                                 .isNucleotide();
5325                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5326                                 alignPanel.av.getSequenceSelection(),
5327                                 alignPanel.alignFrame, dassource,
5328                                 alignPanel.alignFrame.featureSettings,
5329                                 isNucleotide);
5330                         dbRefFetcher
5331                                 .addListener(new FetchFinishedListenerI()
5332                                 {
5333                                   @Override
5334                                   public void finished()
5335                                   {
5336                                     AlignFrame.this.setMenusForViewport();
5337                                   }
5338                                 });
5339                         dbRefFetcher.fetchDBRefs(false);
5340                       }
5341                     }).start();
5342                   }
5343                 });
5344
5345                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5346                         MessageManager.formatMessage(
5347                                 "label.fetch_retrieve_from_all_sources",
5348                                 new Object[]
5349                                 { Integer.valueOf(otherdb.size())
5350                                         .toString(),
5351                                     src.getDbSource(), src.getDbName() })));
5352                 dfetch.add(fetchr);
5353                 comp++;
5354                 // and then build the rest of the individual menus
5355                 ifetch = new JMenu(MessageManager.formatMessage(
5356                         "label.source_from_db_source", new Object[]
5357                         { src.getDbSource() }));
5358                 icomp = 0;
5359                 String imname = null;
5360                 int i = 0;
5361                 for (DbSourceProxy sproxy : otherdb)
5362                 {
5363                   String dbname = sproxy.getDbName();
5364                   String sname = dbname.length() > 5
5365                           ? dbname.substring(0, 5) + "..."
5366                           : dbname;
5367                   String msname = dbname.length() > 10
5368                           ? dbname.substring(0, 10) + "..."
5369                           : dbname;
5370                   if (imname == null)
5371                   {
5372                     imname = MessageManager
5373                             .formatMessage("label.from_msname", new Object[]
5374                             { sname });
5375                   }
5376                   fetchr = new JMenuItem(msname);
5377                   final DbSourceProxy[] dassrc = { sproxy };
5378                   fetchr.addActionListener(new ActionListener()
5379                   {
5380
5381                     @Override
5382                     public void actionPerformed(ActionEvent e)
5383                     {
5384                       new Thread(new Runnable()
5385                       {
5386
5387                         @Override
5388                         public void run()
5389                         {
5390                           boolean isNucleotide = alignPanel.alignFrame
5391                                   .getViewport().getAlignment()
5392                                   .isNucleotide();
5393                           DBRefFetcher dbRefFetcher = new DBRefFetcher(
5394                                   alignPanel.av.getSequenceSelection(),
5395                                   alignPanel.alignFrame, dassrc,
5396                                   alignPanel.alignFrame.featureSettings,
5397                                   isNucleotide);
5398                           dbRefFetcher
5399                                   .addListener(new FetchFinishedListenerI()
5400                                   {
5401                                     @Override
5402                                     public void finished()
5403                                     {
5404                                       AlignFrame.this.setMenusForViewport();
5405                                     }
5406                                   });
5407                           dbRefFetcher.fetchDBRefs(false);
5408                         }
5409                       }).start();
5410                     }
5411
5412                   });
5413                   fetchr.setToolTipText(
5414                           "<html>" + MessageManager.formatMessage(
5415                                   "label.fetch_retrieve_from", new Object[]
5416                                   { dbname }));
5417                   ifetch.add(fetchr);
5418                   ++i;
5419                   if (++icomp >= mcomp || i == (otherdb.size()))
5420                   {
5421                     ifetch.setText(MessageManager.formatMessage(
5422                             "label.source_to_target", imname, sname));
5423                     dfetch.add(ifetch);
5424                     ifetch = new JMenu();
5425                     imname = null;
5426                     icomp = 0;
5427                     comp++;
5428                   }
5429                 }
5430               }
5431               ++dbi;
5432               if (comp >= mcomp || dbi >= (dbclasses.length))
5433               {
5434                 dfetch.setText(MessageManager.formatMessage(
5435                         "label.source_to_target", mname, dbclass));
5436                 rfetch.add(dfetch);
5437                 dfetch = new JMenu();
5438                 mname = null;
5439                 comp = 0;
5440               }
5441             }
5442           }
5443         });
5444       }
5445     }).start();
5446
5447   }
5448
5449   /**
5450    * Left justify the whole alignment.
5451    */
5452   @Override
5453   protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5454   {
5455     AlignmentI al = viewport.getAlignment();
5456     al.justify(false);
5457     viewport.firePropertyChange("alignment", null, al);
5458   }
5459
5460   /**
5461    * Right justify the whole alignment.
5462    */
5463   @Override
5464   protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5465   {
5466     AlignmentI al = viewport.getAlignment();
5467     al.justify(true);
5468     viewport.firePropertyChange("alignment", null, al);
5469   }
5470
5471   @Override
5472   public void setShowSeqFeatures(boolean b)
5473   {
5474     showSeqFeatures.setSelected(b);
5475     viewport.setShowSequenceFeatures(b);
5476   }
5477
5478   /*
5479    * (non-Javadoc)
5480    * 
5481    * @see
5482    * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5483    * awt.event.ActionEvent)
5484    */
5485   @Override
5486   protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5487   {
5488     viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5489     alignPanel.paintAlignment(false, false);
5490   }
5491
5492   /*
5493    * (non-Javadoc)
5494    * 
5495    * @see
5496    * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5497    * .ActionEvent)
5498    */
5499   @Override
5500   protected void showGroupConsensus_actionPerformed(ActionEvent e)
5501   {
5502     viewport.setShowGroupConsensus(showGroupConsensus.getState());
5503     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5504
5505   }
5506
5507   /*
5508    * (non-Javadoc)
5509    * 
5510    * @see
5511    * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5512    * .event.ActionEvent)
5513    */
5514   @Override
5515   protected void showGroupConservation_actionPerformed(ActionEvent e)
5516   {
5517     viewport.setShowGroupConservation(showGroupConservation.getState());
5518     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5519   }
5520
5521   /*
5522    * (non-Javadoc)
5523    * 
5524    * @see
5525    * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5526    * .event.ActionEvent)
5527    */
5528   @Override
5529   protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5530   {
5531     viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5532     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5533   }
5534
5535   /*
5536    * (non-Javadoc)
5537    * 
5538    * @see
5539    * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5540    * .event.ActionEvent)
5541    */
5542   @Override
5543   protected void showSequenceLogo_actionPerformed(ActionEvent e)
5544   {
5545     viewport.setShowSequenceLogo(showSequenceLogo.getState());
5546     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5547   }
5548
5549   @Override
5550   protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5551   {
5552     showSequenceLogo.setState(true);
5553     viewport.setShowSequenceLogo(true);
5554     viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5555     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5556   }
5557
5558   @Override
5559   protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5560   {
5561     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5562   }
5563
5564   /*
5565    * (non-Javadoc)
5566    * 
5567    * @see
5568    * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5569    * .event.ActionEvent)
5570    */
5571   @Override
5572   protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5573   {
5574     if (avc.makeGroupsFromSelection())
5575     {
5576       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5577       alignPanel.updateAnnotation();
5578       alignPanel.paintAlignment(true,
5579               viewport.needToUpdateStructureViews());
5580     }
5581   }
5582
5583   public void clearAlignmentSeqRep()
5584   {
5585     // TODO refactor alignmentseqrep to controller
5586     if (viewport.getAlignment().hasSeqrep())
5587     {
5588       viewport.getAlignment().setSeqrep(null);
5589       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5590       alignPanel.updateAnnotation();
5591       alignPanel.paintAlignment(true, true);
5592     }
5593   }
5594
5595   @Override
5596   protected void createGroup_actionPerformed(ActionEvent e)
5597   {
5598     if (avc.createGroup())
5599     {
5600       if (applyAutoAnnotationSettings.isSelected())
5601       {
5602         alignPanel.updateAnnotation(true, false);
5603       }
5604       alignPanel.alignmentChanged();
5605     }
5606   }
5607
5608   @Override
5609   protected void unGroup_actionPerformed(ActionEvent e)
5610   {
5611     if (avc.unGroup())
5612     {
5613       alignPanel.alignmentChanged();
5614     }
5615   }
5616
5617   /**
5618    * make the given alignmentPanel the currently selected tab
5619    * 
5620    * @param alignmentPanel
5621    */
5622   public void setDisplayedView(AlignmentPanel alignmentPanel)
5623   {
5624     if (!viewport.getSequenceSetId()
5625             .equals(alignmentPanel.av.getSequenceSetId()))
5626     {
5627       throw new Error(MessageManager.getString(
5628               "error.implementation_error_cannot_show_view_alignment_frame"));
5629     }
5630     if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5631             .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5632     {
5633       tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5634     }
5635   }
5636
5637   /**
5638    * Action on selection of menu options to Show or Hide annotations.
5639    * 
5640    * @param visible
5641    * @param forSequences
5642    *          update sequence-related annotations
5643    * @param forAlignment
5644    *          update non-sequence-related annotations
5645    */
5646   @Override
5647   protected void setAnnotationsVisibility(boolean visible,
5648           boolean forSequences, boolean forAlignment)
5649   {
5650     AlignmentAnnotation[] anns = alignPanel.getAlignment()
5651             .getAlignmentAnnotation();
5652     if (anns == null)
5653     {
5654       return;
5655     }
5656     for (AlignmentAnnotation aa : anns)
5657     {
5658       /*
5659        * don't display non-positional annotations on an alignment
5660        */
5661       if (aa.annotations == null)
5662       {
5663         continue;
5664       }
5665       boolean apply = (aa.sequenceRef == null && forAlignment)
5666               || (aa.sequenceRef != null && forSequences);
5667       if (apply)
5668       {
5669         aa.visible = visible;
5670       }
5671     }
5672     alignPanel.validateAnnotationDimensions(true);
5673     alignPanel.alignmentChanged();
5674   }
5675
5676   /**
5677    * Store selected annotation sort order for the view and repaint.
5678    */
5679   @Override
5680   protected void sortAnnotations_actionPerformed()
5681   {
5682     this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5683     this.alignPanel.av
5684             .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5685     alignPanel.paintAlignment(false, false);
5686   }
5687
5688   /**
5689    * 
5690    * @return alignment panels in this alignment frame
5691    */
5692   public List<? extends AlignmentViewPanel> getAlignPanels()
5693   {
5694     // alignPanels is never null
5695     // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5696     return alignPanels;
5697   }
5698
5699   /**
5700    * Open a new alignment window, with the cDNA associated with this (protein)
5701    * alignment, aligned as is the protein.
5702    */
5703   protected void viewAsCdna_actionPerformed()
5704   {
5705     // TODO no longer a menu action - refactor as required
5706     final AlignmentI alignment = getViewport().getAlignment();
5707     List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5708     if (mappings == null)
5709     {
5710       return;
5711     }
5712     List<SequenceI> cdnaSeqs = new ArrayList<>();
5713     for (SequenceI aaSeq : alignment.getSequences())
5714     {
5715       for (AlignedCodonFrame acf : mappings)
5716       {
5717         SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5718         if (dnaSeq != null)
5719         {
5720           /*
5721            * There is a cDNA mapping for this protein sequence - add to new
5722            * alignment. It will share the same dataset sequence as other mapped
5723            * cDNA (no new mappings need to be created).
5724            */
5725           final Sequence newSeq = new Sequence(dnaSeq);
5726           newSeq.setDatasetSequence(dnaSeq);
5727           cdnaSeqs.add(newSeq);
5728         }
5729       }
5730     }
5731     if (cdnaSeqs.size() == 0)
5732     {
5733       // show a warning dialog no mapped cDNA
5734       return;
5735     }
5736     AlignmentI cdna = new Alignment(
5737             cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5738     GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5739             AlignFrame.DEFAULT_HEIGHT);
5740     cdna.alignAs(alignment);
5741     String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5742             + this.title;
5743     Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5744             AlignFrame.DEFAULT_HEIGHT);
5745   }
5746
5747   /**
5748    * Set visibility of dna/protein complement view (available when shown in a
5749    * split frame).
5750    * 
5751    * @param show
5752    */
5753   @Override
5754   protected void showComplement_actionPerformed(boolean show)
5755   {
5756     SplitContainerI sf = getSplitViewContainer();
5757     if (sf != null)
5758     {
5759       sf.setComplementVisible(this, show);
5760     }
5761   }
5762
5763   /**
5764    * Generate the reverse (optionally complemented) of the selected sequences,
5765    * and add them to the alignment
5766    */
5767   @Override
5768   protected void showReverse_actionPerformed(boolean complement)
5769   {
5770     AlignmentI al = null;
5771     try
5772     {
5773       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5774       al = dna.reverseCdna(complement);
5775       viewport.addAlignment(al, "");
5776       addHistoryItem(new EditCommand(
5777               MessageManager.getString("label.add_sequences"), Action.PASTE,
5778               al.getSequencesArray(), 0, al.getWidth(),
5779               viewport.getAlignment()));
5780     } catch (Exception ex)
5781     {
5782       System.err.println(ex.getMessage());
5783       return;
5784     }
5785   }
5786
5787   /**
5788    * Try to run a script in the Groovy console, having first ensured that this
5789    * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5790    * be targeted at this alignment.
5791    */
5792   @Override
5793   protected void runGroovy_actionPerformed()
5794   {
5795     Jalview.setCurrentAlignFrame(this);
5796     groovy.ui.Console console = Desktop.getGroovyConsole();
5797     if (console != null)
5798     {
5799       try
5800       {
5801         console.runScript();
5802       } catch (Exception ex)
5803       {
5804         System.err.println((ex.toString()));
5805         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5806                 MessageManager.getString("label.couldnt_run_groovy_script"),
5807                 MessageManager.getString("label.groovy_support_failed"),
5808                 JvOptionPane.ERROR_MESSAGE);
5809       }
5810     }
5811     else
5812     {
5813       System.err.println("Can't run Groovy script as console not found");
5814     }
5815   }
5816
5817   /**
5818    * Hides columns containing (or not containing) a specified feature, provided
5819    * that would not leave all columns hidden
5820    * 
5821    * @param featureType
5822    * @param columnsContaining
5823    * @return
5824    */
5825   public boolean hideFeatureColumns(String featureType,
5826           boolean columnsContaining)
5827   {
5828     boolean notForHiding = avc.markColumnsContainingFeatures(
5829             columnsContaining, false, false, featureType);
5830     if (notForHiding)
5831     {
5832       if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5833               false, featureType))
5834       {
5835         getViewport().hideSelectedColumns();
5836         return true;
5837       }
5838     }
5839     return false;
5840   }
5841
5842   @Override
5843   protected void selectHighlightedColumns_actionPerformed(
5844           ActionEvent actionEvent)
5845   {
5846     // include key modifier check in case user selects from menu
5847     avc.markHighlightedColumns(
5848             (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5849             (actionEvent.getModifiers() & (ActionEvent.META_MASK
5850                     | ActionEvent.CTRL_MASK)) != 0);
5851   }
5852
5853   /**
5854    * Rebuilds the Colour menu, including any user-defined colours which have
5855    * been loaded either on startup or during the session
5856    */
5857   public void buildColourMenu()
5858   {
5859     colourMenu.removeAll();
5860
5861     colourMenu.add(applyToAllGroups);
5862     colourMenu.add(textColour);
5863     colourMenu.addSeparator();
5864
5865     ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5866             viewport.getAlignment(), false);
5867
5868     colourMenu.add(annotationColour);
5869     bg.add(annotationColour);
5870     colourMenu.addSeparator();
5871     colourMenu.add(conservationMenuItem);
5872     colourMenu.add(modifyConservation);
5873     colourMenu.add(abovePIDThreshold);
5874     colourMenu.add(modifyPID);
5875
5876     ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5877     ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5878   }
5879
5880   /**
5881    * Open a dialog (if not already open) that allows the user to select and
5882    * calculate PCA or Tree analysis
5883    */
5884   protected void openTreePcaDialog()
5885   {
5886     if (alignPanel.getCalculationDialog() == null)
5887     {
5888       new CalculationChooser(AlignFrame.this);
5889     }
5890   }
5891
5892   @Override
5893   protected void loadVcf_actionPerformed()
5894   {
5895     JalviewFileChooser chooser = new JalviewFileChooser(
5896             Cache.getProperty("LAST_DIRECTORY"));
5897     chooser.setFileView(new JalviewFileView());
5898     chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5899     chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5900     final AlignFrame us = this;
5901     chooser.setResponseHandler(0, () -> {
5902       String choice = chooser.getSelectedFile().getPath();
5903       Cache.setProperty("LAST_DIRECTORY", choice);
5904       SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5905       new VCFLoader(choice).loadVCF(seqs, us);
5906       return null;
5907     });
5908     chooser.showOpenDialog(null);
5909
5910   }
5911
5912   private Rectangle lastFeatureSettingsBounds = null;
5913
5914   @Override
5915   public void setFeatureSettingsGeometry(Rectangle bounds)
5916   {
5917     lastFeatureSettingsBounds = bounds;
5918   }
5919
5920   @Override
5921   public Rectangle getFeatureSettingsGeometry()
5922   {
5923     return lastFeatureSettingsBounds;
5924   }
5925 }
5926
5927 class PrintThread extends Thread
5928 {
5929   AlignmentPanel ap;
5930
5931   public PrintThread(AlignmentPanel ap)
5932   {
5933     this.ap = ap;
5934   }
5935
5936   static PageFormat pf;
5937
5938   @Override
5939   public void run()
5940   {
5941     PrinterJob printJob = PrinterJob.getPrinterJob();
5942
5943     if (pf != null)
5944     {
5945       printJob.setPrintable(ap, pf);
5946     }
5947     else
5948     {
5949       printJob.setPrintable(ap);
5950     }
5951
5952     if (printJob.printDialog())
5953     {
5954       try
5955       {
5956         printJob.print();
5957       } catch (Exception PrintException)
5958       {
5959         PrintException.printStackTrace();
5960       }
5961     }
5962   }
5963 }