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