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