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