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