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