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