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