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