JAL-2629 can now filter by sequence e-value or 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().getAlignment().getSequences().size() < 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   /**
3790    * DOCUMENT ME!
3791    * 
3792    * @param e
3793    *          DOCUMENT ME!
3794    */
3795   @Override
3796   public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3797   {
3798     new RedundancyPanel(alignPanel, this);
3799   }
3800
3801   /**
3802    * DOCUMENT ME!
3803    * 
3804    * @param e
3805    *          DOCUMENT ME!
3806    */
3807   @Override
3808   public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3809   {
3810     if ((viewport.getSelectionGroup() == null)
3811             || (viewport.getSelectionGroup().getSize() < 2))
3812     {
3813       JvOptionPane.showInternalMessageDialog(this,
3814               MessageManager.getString(
3815                       "label.you_must_select_least_two_sequences"),
3816               MessageManager.getString("label.invalid_selection"),
3817               JvOptionPane.WARNING_MESSAGE);
3818     }
3819     else
3820     {
3821       JInternalFrame frame = new JInternalFrame();
3822       frame.setContentPane(new PairwiseAlignPanel(viewport));
3823       Desktop.addInternalFrame(frame,
3824               MessageManager.getString("action.pairwise_alignment"), 600,
3825               500);
3826     }
3827   }
3828
3829   @Override
3830   public void autoCalculate_actionPerformed(ActionEvent e)
3831   {
3832     viewport.autoCalculateConsensus = autoCalculate.isSelected();
3833     if (viewport.autoCalculateConsensus)
3834     {
3835       viewport.firePropertyChange("alignment", null,
3836               viewport.getAlignment().getSequences());
3837     }
3838   }
3839
3840   @Override
3841   public void sortByTreeOption_actionPerformed(ActionEvent e)
3842   {
3843     viewport.sortByTree = sortByTree.isSelected();
3844   }
3845
3846   @Override
3847   protected void listenToViewSelections_actionPerformed(ActionEvent e)
3848   {
3849     viewport.followSelection = listenToViewSelections.isSelected();
3850   }
3851
3852   /**
3853    * Constructs a tree panel and adds it to the desktop
3854    * 
3855    * @param type
3856    *          tree type (NJ or AV)
3857    * @param modelName
3858    *          name of score model used to compute the tree
3859    * @param options
3860    *          parameters for the distance or similarity calculation
3861    */
3862   void newTreePanel(String type, String modelName,
3863           SimilarityParamsI options)
3864   {
3865     String frameTitle = "";
3866     TreePanel tp;
3867
3868     boolean onSelection = false;
3869     if (viewport.getSelectionGroup() != null
3870             && viewport.getSelectionGroup().getSize() > 0)
3871     {
3872       SequenceGroup sg = viewport.getSelectionGroup();
3873
3874       /* Decide if the selection is a column region */
3875       for (SequenceI _s : sg.getSequences())
3876       {
3877         if (_s.getLength() < sg.getEndRes())
3878         {
3879           JvOptionPane.showMessageDialog(Desktop.desktop,
3880                   MessageManager.getString(
3881                           "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3882                   MessageManager.getString(
3883                           "label.sequences_selection_not_aligned"),
3884                   JvOptionPane.WARNING_MESSAGE);
3885
3886           return;
3887         }
3888       }
3889       onSelection = true;
3890     }
3891     else
3892     {
3893       if (viewport.getAlignment().getHeight() < 2)
3894       {
3895         return;
3896       }
3897     }
3898
3899     tp = new TreePanel(alignPanel, type, modelName, options);
3900     frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3901
3902     frameTitle += " from ";
3903
3904     if (viewport.getViewName() != null)
3905     {
3906       frameTitle += viewport.getViewName() + " of ";
3907     }
3908
3909     frameTitle += this.title;
3910
3911     Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3912   }
3913
3914   /**
3915    * DOCUMENT ME!
3916    * 
3917    * @param title
3918    *          DOCUMENT ME!
3919    * @param order
3920    *          DOCUMENT ME!
3921    */
3922   public void addSortByOrderMenuItem(String title,
3923           final AlignmentOrder order)
3924   {
3925     final JMenuItem item = new JMenuItem(MessageManager
3926             .formatMessage("action.by_title_param", new Object[]
3927             { title }));
3928     sort.add(item);
3929     item.addActionListener(new java.awt.event.ActionListener()
3930     {
3931       @Override
3932       public void actionPerformed(ActionEvent e)
3933       {
3934         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3935
3936         // TODO: JBPNote - have to map order entries to curent SequenceI
3937         // pointers
3938         AlignmentSorter.sortBy(viewport.getAlignment(), order);
3939
3940         addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3941                 viewport.getAlignment()));
3942
3943         alignPanel.paintAlignment(true, false);
3944       }
3945     });
3946   }
3947
3948   /**
3949    * Add a new sort by annotation score menu item
3950    * 
3951    * @param sort
3952    *          the menu to add the option to
3953    * @param scoreLabel
3954    *          the label used to retrieve scores for each sequence on the
3955    *          alignment
3956    */
3957   public void addSortByAnnotScoreMenuItem(JMenu sort,
3958           final String scoreLabel)
3959   {
3960     final JMenuItem item = new JMenuItem(scoreLabel);
3961     sort.add(item);
3962     item.addActionListener(new java.awt.event.ActionListener()
3963     {
3964       @Override
3965       public void actionPerformed(ActionEvent e)
3966       {
3967         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3968         AlignmentSorter.sortByAnnotationScore(scoreLabel,
3969                 viewport.getAlignment());// ,viewport.getSelectionGroup());
3970         addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3971                 viewport.getAlignment()));
3972         alignPanel.paintAlignment(true, false);
3973       }
3974     });
3975   }
3976
3977   /**
3978    * last hash for alignment's annotation array - used to minimise cost of
3979    * rebuild.
3980    */
3981   protected int _annotationScoreVectorHash;
3982
3983   /**
3984    * search the alignment and rebuild the sort by annotation score submenu the
3985    * last alignment annotation vector hash is stored to minimize cost of
3986    * rebuilding in subsequence calls.
3987    * 
3988    */
3989   @Override
3990   public void buildSortByAnnotationScoresMenu()
3991   {
3992     if (viewport.getAlignment().getAlignmentAnnotation() == null)
3993     {
3994       return;
3995     }
3996
3997     if (viewport.getAlignment().getAlignmentAnnotation()
3998             .hashCode() == _annotationScoreVectorHash)
3999     {
4000       return;
4001     }
4002
4003     sortByAnnotScore.removeAll();
4004     Set<String> scoreSorts = new HashSet<>();
4005     for (SequenceI sqa : viewport.getAlignment().getSequences())
4006     {
4007       AlignmentAnnotation[] anns = sqa.getAnnotation();
4008       for (int i = 0; anns != null && i < anns.length; i++)
4009       {
4010         AlignmentAnnotation aa = anns[i];
4011         if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4012         {
4013           scoreSorts.add(aa.label);
4014         }
4015       }
4016     }
4017     for (String label : scoreSorts)
4018     {
4019       addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4020     }
4021     sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4022
4023     _annotationScoreVectorHash = viewport.getAlignment()
4024             .getAlignmentAnnotation().hashCode();
4025   }
4026
4027   /**
4028    * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4029    * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4030    * call. Listeners are added to remove the menu item when the treePanel is
4031    * closed, and adjust the tree leaf to sequence mapping when the alignment is
4032    * modified.
4033    */
4034   @Override
4035   public void buildTreeSortMenu()
4036   {
4037     sortByTreeMenu.removeAll();
4038
4039     List<Component> comps = PaintRefresher.components
4040             .get(viewport.getSequenceSetId());
4041     List<TreePanel> treePanels = new ArrayList<>();
4042     for (Component comp : comps)
4043     {
4044       if (comp instanceof TreePanel)
4045       {
4046         treePanels.add((TreePanel) comp);
4047       }
4048     }
4049
4050     if (treePanels.size() < 1)
4051     {
4052       sortByTreeMenu.setVisible(false);
4053       return;
4054     }
4055
4056     sortByTreeMenu.setVisible(true);
4057
4058     for (final TreePanel tp : treePanels)
4059     {
4060       final JMenuItem item = new JMenuItem(tp.getTitle());
4061       item.addActionListener(new java.awt.event.ActionListener()
4062       {
4063         @Override
4064         public void actionPerformed(ActionEvent e)
4065         {
4066           tp.sortByTree_actionPerformed();
4067           addHistoryItem(tp.sortAlignmentIn(alignPanel));
4068
4069         }
4070       });
4071
4072       sortByTreeMenu.add(item);
4073     }
4074   }
4075
4076   public boolean sortBy(AlignmentOrder alorder, String undoname)
4077   {
4078     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4079     AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4080     if (undoname != null)
4081     {
4082       addHistoryItem(new OrderCommand(undoname, oldOrder,
4083               viewport.getAlignment()));
4084     }
4085     alignPanel.paintAlignment(true, false);
4086     return true;
4087   }
4088
4089   /**
4090    * Work out whether the whole set of sequences or just the selected set will
4091    * be submitted for multiple alignment.
4092    * 
4093    */
4094   public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4095   {
4096     // Now, check we have enough sequences
4097     AlignmentView msa = null;
4098
4099     if ((viewport.getSelectionGroup() != null)
4100             && (viewport.getSelectionGroup().getSize() > 1))
4101     {
4102       // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4103       // some common interface!
4104       /*
4105        * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4106        * SequenceI[sz = seqs.getSize(false)];
4107        * 
4108        * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4109        * seqs.getSequenceAt(i); }
4110        */
4111       msa = viewport.getAlignmentView(true);
4112     }
4113     else if (viewport.getSelectionGroup() != null
4114             && viewport.getSelectionGroup().getSize() == 1)
4115     {
4116       int option = JvOptionPane.showConfirmDialog(this,
4117               MessageManager.getString("warn.oneseq_msainput_selection"),
4118               MessageManager.getString("label.invalid_selection"),
4119               JvOptionPane.OK_CANCEL_OPTION);
4120       if (option == JvOptionPane.OK_OPTION)
4121       {
4122         msa = viewport.getAlignmentView(false);
4123       }
4124     }
4125     else
4126     {
4127       msa = viewport.getAlignmentView(false);
4128     }
4129     return msa;
4130   }
4131
4132   /**
4133    * Decides what is submitted to a secondary structure prediction service: the
4134    * first sequence in the alignment, or in the current selection, or, if the
4135    * alignment is 'aligned' (ie padded with gaps), then the currently selected
4136    * region or the whole alignment. (where the first sequence in the set is the
4137    * one that the prediction will be for).
4138    */
4139   public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4140   {
4141     AlignmentView seqs = null;
4142
4143     if ((viewport.getSelectionGroup() != null)
4144             && (viewport.getSelectionGroup().getSize() > 0))
4145     {
4146       seqs = viewport.getAlignmentView(true);
4147     }
4148     else
4149     {
4150       seqs = viewport.getAlignmentView(false);
4151     }
4152     // limit sequences - JBPNote in future - could spawn multiple prediction
4153     // jobs
4154     // TODO: viewport.getAlignment().isAligned is a global state - the local
4155     // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4156     if (!viewport.getAlignment().isAligned(false))
4157     {
4158       seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4159       // TODO: if seqs.getSequences().length>1 then should really have warned
4160       // user!
4161
4162     }
4163     return seqs;
4164   }
4165
4166   /**
4167    * DOCUMENT ME!
4168    * 
4169    * @param e
4170    *          DOCUMENT ME!
4171    */
4172   @Override
4173   protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4174   {
4175     // Pick the tree file
4176     JalviewFileChooser chooser = new JalviewFileChooser(
4177             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4178     chooser.setFileView(new JalviewFileView());
4179     chooser.setDialogTitle(
4180             MessageManager.getString("label.select_newick_like_tree_file"));
4181     chooser.setToolTipText(
4182             MessageManager.getString("label.load_tree_file"));
4183
4184     int value = chooser.showOpenDialog(null);
4185
4186     if (value == JalviewFileChooser.APPROVE_OPTION)
4187     {
4188       String filePath = chooser.getSelectedFile().getPath();
4189       Cache.setProperty("LAST_DIRECTORY", filePath);
4190       NewickFile fin = null;
4191       try
4192       {
4193         fin = new NewickFile(filePath, DataSourceType.FILE);
4194         viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4195       } catch (Exception ex)
4196       {
4197         JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4198                 MessageManager.getString("label.problem_reading_tree_file"),
4199                 JvOptionPane.WARNING_MESSAGE);
4200         ex.printStackTrace();
4201       }
4202       if (fin != null && fin.hasWarningMessage())
4203       {
4204         JvOptionPane.showMessageDialog(Desktop.desktop,
4205                 fin.getWarningMessage(),
4206                 MessageManager
4207                         .getString("label.possible_problem_with_tree_file"),
4208                 JvOptionPane.WARNING_MESSAGE);
4209       }
4210     }
4211   }
4212
4213   public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4214   {
4215     return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4216   }
4217
4218   public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4219           int h, int x, int y)
4220   {
4221     return showNewickTree(nf, treeTitle, null, w, h, x, y);
4222   }
4223
4224   /**
4225    * Add a treeviewer for the tree extracted from a Newick file object to the
4226    * current alignment view
4227    * 
4228    * @param nf
4229    *          the tree
4230    * @param title
4231    *          tree viewer title
4232    * @param input
4233    *          Associated alignment input data (or null)
4234    * @param w
4235    *          width
4236    * @param h
4237    *          height
4238    * @param x
4239    *          position
4240    * @param y
4241    *          position
4242    * @return TreePanel handle
4243    */
4244   public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4245           AlignmentView input, int w, int h, int x, int y)
4246   {
4247     TreePanel tp = null;
4248
4249     try
4250     {
4251       nf.parse();
4252
4253       if (nf.getTree() != null)
4254       {
4255         tp = new TreePanel(alignPanel, nf, treeTitle, input);
4256
4257         tp.setSize(w, h);
4258
4259         if (x > 0 && y > 0)
4260         {
4261           tp.setLocation(x, y);
4262         }
4263
4264         Desktop.addInternalFrame(tp, treeTitle, w, h);
4265       }
4266     } catch (Exception ex)
4267     {
4268       ex.printStackTrace();
4269     }
4270
4271     return tp;
4272   }
4273
4274   private boolean buildingMenu = false;
4275
4276   /**
4277    * Generates menu items and listener event actions for web service clients
4278    * 
4279    */
4280   public void BuildWebServiceMenu()
4281   {
4282     while (buildingMenu)
4283     {
4284       try
4285       {
4286         System.err.println("Waiting for building menu to finish.");
4287         Thread.sleep(10);
4288       } catch (Exception e)
4289       {
4290       }
4291     }
4292     final AlignFrame me = this;
4293     buildingMenu = true;
4294     new Thread(new Runnable()
4295     {
4296       @Override
4297       public void run()
4298       {
4299         final List<JMenuItem> legacyItems = new ArrayList<>();
4300         try
4301         {
4302           // System.err.println("Building ws menu again "
4303           // + Thread.currentThread());
4304           // TODO: add support for context dependent disabling of services based
4305           // on
4306           // alignment and current selection
4307           // TODO: add additional serviceHandle parameter to specify abstract
4308           // handler
4309           // class independently of AbstractName
4310           // TODO: add in rediscovery GUI function to restart discoverer
4311           // TODO: group services by location as well as function and/or
4312           // introduce
4313           // object broker mechanism.
4314           final Vector<JMenu> wsmenu = new Vector<>();
4315           final IProgressIndicator af = me;
4316
4317           /*
4318            * do not i18n these strings - they are hard-coded in class
4319            * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4320            * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4321            */
4322           final JMenu msawsmenu = new JMenu("Alignment");
4323           final JMenu secstrmenu = new JMenu(
4324                   "Secondary Structure Prediction");
4325           final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4326           final JMenu analymenu = new JMenu("Analysis");
4327           final JMenu dismenu = new JMenu("Protein Disorder");
4328           // JAL-940 - only show secondary structure prediction services from
4329           // the legacy server
4330           if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4331               // &&
4332           Discoverer.services != null && (Discoverer.services.size() > 0))
4333           {
4334             // TODO: refactor to allow list of AbstractName/Handler bindings to
4335             // be
4336             // stored or retrieved from elsewhere
4337             // No MSAWS used any more:
4338             // Vector msaws = null; // (Vector)
4339             // Discoverer.services.get("MsaWS");
4340             Vector secstrpr = (Vector) Discoverer.services
4341                     .get("SecStrPred");
4342             if (secstrpr != null)
4343             {
4344               // Add any secondary structure prediction services
4345               for (int i = 0, j = secstrpr.size(); i < j; i++)
4346               {
4347                 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4348                         .get(i);
4349                 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4350                         .getServiceClient(sh);
4351                 int p = secstrmenu.getItemCount();
4352                 impl.attachWSMenuEntry(secstrmenu, me);
4353                 int q = secstrmenu.getItemCount();
4354                 for (int litm = p; litm < q; litm++)
4355                 {
4356                   legacyItems.add(secstrmenu.getItem(litm));
4357                 }
4358               }
4359             }
4360           }
4361
4362           // Add all submenus in the order they should appear on the web
4363           // services menu
4364           wsmenu.add(msawsmenu);
4365           wsmenu.add(secstrmenu);
4366           wsmenu.add(dismenu);
4367           wsmenu.add(analymenu);
4368           // No search services yet
4369           // wsmenu.add(seqsrchmenu);
4370
4371           javax.swing.SwingUtilities.invokeLater(new Runnable()
4372           {
4373             @Override
4374             public void run()
4375             {
4376               try
4377               {
4378                 webService.removeAll();
4379                 // first, add discovered services onto the webservices menu
4380                 if (wsmenu.size() > 0)
4381                 {
4382                   for (int i = 0, j = wsmenu.size(); i < j; i++)
4383                   {
4384                     webService.add(wsmenu.get(i));
4385                   }
4386                 }
4387                 else
4388                 {
4389                   webService.add(me.webServiceNoServices);
4390                 }
4391                 // TODO: move into separate menu builder class.
4392                 boolean new_sspred = false;
4393                 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4394                 {
4395                   Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4396                   if (jws2servs != null)
4397                   {
4398                     if (jws2servs.hasServices())
4399                     {
4400                       jws2servs.attachWSMenuEntry(webService, me);
4401                       for (Jws2Instance sv : jws2servs.getServices())
4402                       {
4403                         if (sv.description.toLowerCase().contains("jpred"))
4404                         {
4405                           for (JMenuItem jmi : legacyItems)
4406                           {
4407                             jmi.setVisible(false);
4408                           }
4409                         }
4410                       }
4411
4412                     }
4413                     if (jws2servs.isRunning())
4414                     {
4415                       JMenuItem tm = new JMenuItem(
4416                               "Still discovering JABA Services");
4417                       tm.setEnabled(false);
4418                       webService.add(tm);
4419                     }
4420                   }
4421                 }
4422                 build_urlServiceMenu(me.webService);
4423                 build_fetchdbmenu(webService);
4424                 for (JMenu item : wsmenu)
4425                 {
4426                   if (item.getItemCount() == 0)
4427                   {
4428                     item.setEnabled(false);
4429                   }
4430                   else
4431                   {
4432                     item.setEnabled(true);
4433                   }
4434                 }
4435               } catch (Exception e)
4436               {
4437                 Cache.log.debug(
4438                         "Exception during web service menu building process.",
4439                         e);
4440               }
4441             }
4442           });
4443         } catch (Exception e)
4444         {
4445         }
4446         buildingMenu = false;
4447       }
4448     }).start();
4449
4450   }
4451
4452   /**
4453    * construct any groupURL type service menu entries.
4454    * 
4455    * @param webService
4456    */
4457   private void build_urlServiceMenu(JMenu webService)
4458   {
4459     // TODO: remove this code when 2.7 is released
4460     // DEBUG - alignmentView
4461     /*
4462      * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4463      * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4464      * 
4465      * @Override public void actionPerformed(ActionEvent e) {
4466      * jalview.datamodel.AlignmentView
4467      * .testSelectionViews(af.viewport.getAlignment(),
4468      * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4469      * 
4470      * }); webService.add(testAlView);
4471      */
4472     // TODO: refactor to RestClient discoverer and merge menu entries for
4473     // rest-style services with other types of analysis/calculation service
4474     // SHmmr test client - still being implemented.
4475     // DEBUG - alignmentView
4476
4477     for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4478             .getRestClients())
4479     {
4480       client.attachWSMenuEntry(
4481               JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4482               this);
4483     }
4484   }
4485
4486   /**
4487    * Searches the alignment sequences for xRefs and builds the Show
4488    * Cross-References menu (formerly called Show Products), with database
4489    * sources for which cross-references are found (protein sources for a
4490    * nucleotide alignment and vice versa)
4491    * 
4492    * @return true if Show Cross-references menu should be enabled
4493    */
4494   public boolean canShowProducts()
4495   {
4496     SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4497     AlignmentI dataset = viewport.getAlignment().getDataset();
4498
4499     showProducts.removeAll();
4500     final boolean dna = viewport.getAlignment().isNucleotide();
4501
4502     if (seqs == null || seqs.length == 0)
4503     {
4504       // nothing to see here.
4505       return false;
4506     }
4507
4508     boolean showp = false;
4509     try
4510     {
4511       List<String> ptypes = new CrossRef(seqs, dataset)
4512               .findXrefSourcesForSequences(dna);
4513
4514       for (final String source : ptypes)
4515       {
4516         showp = true;
4517         final AlignFrame af = this;
4518         JMenuItem xtype = new JMenuItem(source);
4519         xtype.addActionListener(new ActionListener()
4520         {
4521           @Override
4522           public void actionPerformed(ActionEvent e)
4523           {
4524             showProductsFor(af.viewport.getSequenceSelection(), dna,
4525                     source);
4526           }
4527         });
4528         showProducts.add(xtype);
4529       }
4530       showProducts.setVisible(showp);
4531       showProducts.setEnabled(showp);
4532     } catch (Exception e)
4533     {
4534       Cache.log.warn(
4535               "canShowProducts threw an exception - please report to help@jalview.org",
4536               e);
4537       return false;
4538     }
4539     return showp;
4540   }
4541
4542   /**
4543    * Finds and displays cross-references for the selected sequences (protein
4544    * products for nucleotide sequences, dna coding sequences for peptides).
4545    * 
4546    * @param sel
4547    *          the sequences to show cross-references for
4548    * @param dna
4549    *          true if from a nucleotide alignment (so showing proteins)
4550    * @param source
4551    *          the database to show cross-references for
4552    */
4553   protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4554           final String source)
4555   {
4556     new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4557             .start();
4558   }
4559
4560   /**
4561    * Construct and display a new frame containing the translation of this
4562    * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4563    */
4564   @Override
4565   public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4566   {
4567     AlignmentI al = null;
4568     try
4569     {
4570       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4571
4572       al = dna.translateCdna(codeTable);
4573     } catch (Exception ex)
4574     {
4575       jalview.bin.Cache.log.error(
4576               "Exception during translation. Please report this !", ex);
4577       final String msg = MessageManager.getString(
4578               "label.error_when_translating_sequences_submit_bug_report");
4579       final String errorTitle = MessageManager
4580               .getString("label.implementation_error")
4581               + MessageManager.getString("label.translation_failed");
4582       JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4583               JvOptionPane.ERROR_MESSAGE);
4584       return;
4585     }
4586     if (al == null || al.getHeight() == 0)
4587     {
4588       final String msg = MessageManager.getString(
4589               "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4590       final String errorTitle = MessageManager
4591               .getString("label.translation_failed");
4592       JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4593               JvOptionPane.WARNING_MESSAGE);
4594     }
4595     else
4596     {
4597       AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4598       af.setFileFormat(this.currentFileFormat);
4599       final String newTitle = MessageManager
4600               .formatMessage("label.translation_of_params", new Object[]
4601               { this.getTitle(), codeTable.getId() });
4602       af.setTitle(newTitle);
4603       if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4604       {
4605         final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4606         viewport.openSplitFrame(af, new Alignment(seqs));
4607       }
4608       else
4609       {
4610         Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4611                 DEFAULT_HEIGHT);
4612       }
4613     }
4614   }
4615
4616   /**
4617    * Set the file format
4618    * 
4619    * @param format
4620    */
4621   public void setFileFormat(FileFormatI format)
4622   {
4623     this.currentFileFormat = format;
4624   }
4625
4626   /**
4627    * Try to load a features file onto the alignment.
4628    * 
4629    * @param file
4630    *          contents or path to retrieve file
4631    * @param sourceType
4632    *          access mode of file (see jalview.io.AlignFile)
4633    * @return true if features file was parsed correctly.
4634    */
4635   public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4636   {
4637     return avc.parseFeaturesFile(file, sourceType,
4638             Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4639
4640   }
4641
4642   @Override
4643   public void refreshFeatureUI(boolean enableIfNecessary)
4644   {
4645     // note - currently this is only still here rather than in the controller
4646     // because of the featureSettings hard reference that is yet to be
4647     // abstracted
4648     if (enableIfNecessary)
4649     {
4650       viewport.setShowSequenceFeatures(true);
4651       showSeqFeatures.setSelected(true);
4652     }
4653
4654   }
4655
4656   @Override
4657   public void dragEnter(DropTargetDragEvent evt)
4658   {
4659   }
4660
4661   @Override
4662   public void dragExit(DropTargetEvent evt)
4663   {
4664   }
4665
4666   @Override
4667   public void dragOver(DropTargetDragEvent evt)
4668   {
4669   }
4670
4671   @Override
4672   public void dropActionChanged(DropTargetDragEvent evt)
4673   {
4674   }
4675
4676   @Override
4677   public void drop(DropTargetDropEvent evt)
4678   {
4679     // JAL-1552 - acceptDrop required before getTransferable call for
4680     // Java's Transferable for native dnd
4681     evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4682     Transferable t = evt.getTransferable();
4683     final AlignFrame thisaf = this;
4684     final List<String> files = new ArrayList<>();
4685     List<DataSourceType> protocols = new ArrayList<>();
4686
4687     try
4688     {
4689       Desktop.transferFromDropTarget(files, protocols, evt, t);
4690     } catch (Exception e)
4691     {
4692       e.printStackTrace();
4693     }
4694     if (files != null)
4695     {
4696       new Thread(new Runnable()
4697       {
4698         @Override
4699         public void run()
4700         {
4701           try
4702           {
4703             // check to see if any of these files have names matching sequences
4704             // in
4705             // the alignment
4706             SequenceIdMatcher idm = new SequenceIdMatcher(
4707                     viewport.getAlignment().getSequencesArray());
4708             /**
4709              * Object[] { String,SequenceI}
4710              */
4711             ArrayList<Object[]> filesmatched = new ArrayList<>();
4712             ArrayList<String> filesnotmatched = new ArrayList<>();
4713             for (int i = 0; i < files.size(); i++)
4714             {
4715               String file = files.get(i).toString();
4716               String pdbfn = "";
4717               DataSourceType protocol = FormatAdapter.checkProtocol(file);
4718               if (protocol == DataSourceType.FILE)
4719               {
4720                 File fl = new File(file);
4721                 pdbfn = fl.getName();
4722               }
4723               else if (protocol == DataSourceType.URL)
4724               {
4725                 URL url = new URL(file);
4726                 pdbfn = url.getFile();
4727               }
4728               if (pdbfn.length() > 0)
4729               {
4730                 // attempt to find a match in the alignment
4731                 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4732                 int l = 0, c = pdbfn.indexOf(".");
4733                 while (mtch == null && c != -1)
4734                 {
4735                   do
4736                   {
4737                     l = c;
4738                   } while ((c = pdbfn.indexOf(".", l)) > l);
4739                   if (l > -1)
4740                   {
4741                     pdbfn = pdbfn.substring(0, l);
4742                   }
4743                   mtch = idm.findAllIdMatches(pdbfn);
4744                 }
4745                 if (mtch != null)
4746                 {
4747                   FileFormatI type = null;
4748                   try
4749                   {
4750                     type = new IdentifyFile().identify(file, protocol);
4751                   } catch (Exception ex)
4752                   {
4753                     type = null;
4754                   }
4755                   if (type != null && type.isStructureFile())
4756                   {
4757                     filesmatched.add(new Object[] { file, protocol, mtch });
4758                     continue;
4759                   }
4760                 }
4761                 // File wasn't named like one of the sequences or wasn't a PDB
4762                 // file.
4763                 filesnotmatched.add(file);
4764               }
4765             }
4766             int assocfiles = 0;
4767             if (filesmatched.size() > 0)
4768             {
4769               boolean autoAssociate = Cache
4770                       .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4771               if (!autoAssociate)
4772               {
4773                 String msg = MessageManager.formatMessage(
4774                         "label.automatically_associate_structure_files_with_sequences_same_name",
4775                         new Object[]
4776                         { Integer.valueOf(filesmatched.size())
4777                                 .toString() });
4778                 String ttl = MessageManager.getString(
4779                         "label.automatically_associate_structure_files_by_name");
4780                 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4781                         ttl, JvOptionPane.YES_NO_OPTION);
4782                 autoAssociate = choice == JvOptionPane.YES_OPTION;
4783               }
4784               if (autoAssociate)
4785               {
4786                 for (Object[] fm : filesmatched)
4787                 {
4788                   // try and associate
4789                   // TODO: may want to set a standard ID naming formalism for
4790                   // associating PDB files which have no IDs.
4791                   for (SequenceI toassoc : (SequenceI[]) fm[2])
4792                   {
4793                     PDBEntry pe = new AssociatePdbFileWithSeq()
4794                             .associatePdbWithSeq((String) fm[0],
4795                                     (DataSourceType) fm[1], toassoc, false,
4796                                     Desktop.instance);
4797                     if (pe != null)
4798                     {
4799                       System.err.println("Associated file : "
4800                               + ((String) fm[0]) + " with "
4801                               + toassoc.getDisplayId(true));
4802                       assocfiles++;
4803                     }
4804                   }
4805                   // TODO: do we need to update overview ? only if features are
4806                   // shown I guess
4807                   alignPanel.paintAlignment(true, false);
4808                 }
4809               }
4810               else
4811               {
4812                 /*
4813                  * add declined structures as sequences
4814                  */
4815                 for (Object[] o : filesmatched)
4816                 {
4817                   filesnotmatched.add((String) o[0]);
4818                 }
4819               }
4820             }
4821             if (filesnotmatched.size() > 0)
4822             {
4823               if (assocfiles > 0 && (Cache.getDefault(
4824                       "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4825                       || JvOptionPane.showConfirmDialog(thisaf,
4826                               "<html>" + MessageManager.formatMessage(
4827                                       "label.ignore_unmatched_dropped_files_info",
4828                                       new Object[]
4829                                       { Integer.valueOf(
4830                                               filesnotmatched.size())
4831                                               .toString() })
4832                                       + "</html>",
4833                               MessageManager.getString(
4834                                       "label.ignore_unmatched_dropped_files"),
4835                               JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4836               {
4837                 return;
4838               }
4839               for (String fn : filesnotmatched)
4840               {
4841                 loadJalviewDataFile(fn, null, null, null);
4842               }
4843
4844             }
4845           } catch (Exception ex)
4846           {
4847             ex.printStackTrace();
4848           }
4849         }
4850       }).start();
4851     }
4852   }
4853
4854   /**
4855    * Attempt to load a "dropped" file or URL string, by testing in turn for
4856    * <ul>
4857    * <li>an Annotation file</li>
4858    * <li>a JNet file</li>
4859    * <li>a features file</li>
4860    * <li>else try to interpret as an alignment file</li>
4861    * </ul>
4862    * 
4863    * @param file
4864    *          either a filename or a URL string.
4865    * @throws InterruptedException
4866    * @throws IOException
4867    */
4868   public void loadJalviewDataFile(String file, DataSourceType sourceType,
4869           FileFormatI format, SequenceI assocSeq)
4870   {
4871     try
4872     {
4873       if (sourceType == null)
4874       {
4875         sourceType = FormatAdapter.checkProtocol(file);
4876       }
4877       // if the file isn't identified, or not positively identified as some
4878       // other filetype (PFAM is default unidentified alignment file type) then
4879       // try to parse as annotation.
4880       boolean isAnnotation = (format == null
4881               || FileFormat.Pfam.equals(format))
4882                       ? new AnnotationFile().annotateAlignmentView(viewport,
4883                               file, sourceType)
4884                       : false;
4885
4886       if (!isAnnotation)
4887       {
4888         // first see if its a T-COFFEE score file
4889         TCoffeeScoreFile tcf = null;
4890         try
4891         {
4892           tcf = new TCoffeeScoreFile(file, sourceType);
4893           if (tcf.isValid())
4894           {
4895             if (tcf.annotateAlignment(viewport.getAlignment(), true))
4896             {
4897               buildColourMenu();
4898               changeColour(
4899                       new TCoffeeColourScheme(viewport.getAlignment()));
4900               isAnnotation = true;
4901               statusBar.setText(MessageManager.getString(
4902                       "label.successfully_pasted_tcoffee_scores_to_alignment"));
4903             }
4904             else
4905             {
4906               // some problem - if no warning its probable that the ID matching
4907               // process didn't work
4908               JvOptionPane.showMessageDialog(Desktop.desktop,
4909                       tcf.getWarningMessage() == null
4910                               ? MessageManager.getString(
4911                                       "label.check_file_matches_sequence_ids_alignment")
4912                               : tcf.getWarningMessage(),
4913                       MessageManager.getString(
4914                               "label.problem_reading_tcoffee_score_file"),
4915                       JvOptionPane.WARNING_MESSAGE);
4916             }
4917           }
4918           else
4919           {
4920             tcf = null;
4921           }
4922         } catch (Exception x)
4923         {
4924           Cache.log.debug(
4925                   "Exception when processing data source as T-COFFEE score file",
4926                   x);
4927           tcf = null;
4928         }
4929         if (tcf == null)
4930         {
4931           // try to see if its a JNet 'concise' style annotation file *before*
4932           // we
4933           // try to parse it as a features file
4934           if (format == null)
4935           {
4936             format = new IdentifyFile().identify(file, sourceType);
4937           }
4938           if (FileFormat.ScoreMatrix == format)
4939           {
4940             ScoreMatrixFile sm = new ScoreMatrixFile(
4941                     new FileParse(file, sourceType));
4942             sm.parse();
4943             // todo: i18n this message
4944             statusBar.setText(MessageManager.formatMessage(
4945                     "label.successfully_loaded_matrix",
4946                     sm.getMatrixName()));
4947           }
4948           else if (FileFormat.Jnet.equals(format))
4949           {
4950             JPredFile predictions = new JPredFile(file, sourceType);
4951             new JnetAnnotationMaker();
4952             JnetAnnotationMaker.add_annotation(predictions,
4953                     viewport.getAlignment(), 0, false);
4954             viewport.getAlignment().setupJPredAlignment();
4955             isAnnotation = true;
4956           }
4957           // else if (IdentifyFile.FeaturesFile.equals(format))
4958           else if (FileFormat.Features.equals(format))
4959           {
4960             if (parseFeaturesFile(file, sourceType))
4961             {
4962               alignPanel.paintAlignment(true, true);
4963             }
4964           }
4965           else
4966           {
4967             new FileLoader().LoadFile(viewport, file, sourceType, format);
4968           }
4969         }
4970       }
4971       if (isAnnotation)
4972       {
4973         alignPanel.adjustAnnotationHeight();
4974         viewport.updateSequenceIdColours();
4975         buildSortByAnnotationScoresMenu();
4976         alignPanel.paintAlignment(true, true);
4977       }
4978     } catch (Exception ex)
4979     {
4980       ex.printStackTrace();
4981     } catch (OutOfMemoryError oom)
4982     {
4983       try
4984       {
4985         System.gc();
4986       } catch (Exception x)
4987       {
4988       }
4989       new OOMWarning(
4990               "loading data "
4991                       + (sourceType != null
4992                               ? (sourceType == DataSourceType.PASTE
4993                                       ? "from clipboard."
4994                                       : "using " + sourceType + " from "
4995                                               + file)
4996                               : ".")
4997                       + (format != null
4998                               ? "(parsing as '" + format + "' file)"
4999                               : ""),
5000               oom, Desktop.desktop);
5001     }
5002   }
5003
5004   /**
5005    * Method invoked by the ChangeListener on the tabbed pane, in other words
5006    * when a different tabbed pane is selected by the user or programmatically.
5007    */
5008   @Override
5009   public void tabSelectionChanged(int index)
5010   {
5011     if (index > -1)
5012     {
5013       alignPanel = alignPanels.get(index);
5014       viewport = alignPanel.av;
5015       avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5016       setMenusFromViewport(viewport);
5017     }
5018
5019     /*
5020      * 'focus' any colour slider that is open to the selected viewport
5021      */
5022     if (viewport.getConservationSelected())
5023     {
5024       SliderPanel.setConservationSlider(alignPanel,
5025               viewport.getResidueShading(), alignPanel.getViewName());
5026     }
5027     else
5028     {
5029       SliderPanel.hideConservationSlider();
5030     }
5031     if (viewport.getAbovePIDThreshold())
5032     {
5033       SliderPanel.setPIDSliderSource(alignPanel,
5034               viewport.getResidueShading(), alignPanel.getViewName());
5035     }
5036     else
5037     {
5038       SliderPanel.hidePIDSlider();
5039     }
5040
5041     /*
5042      * If there is a frame linked to this one in a SplitPane, switch it to the
5043      * same view tab index. No infinite recursion of calls should happen, since
5044      * tabSelectionChanged() should not get invoked on setting the selected
5045      * index to an unchanged value. Guard against setting an invalid index
5046      * before the new view peer tab has been created.
5047      */
5048     final AlignViewportI peer = viewport.getCodingComplement();
5049     if (peer != null)
5050     {
5051       AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5052               .getAlignPanel().alignFrame;
5053       if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5054       {
5055         linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5056       }
5057     }
5058   }
5059
5060   /**
5061    * On right mouse click on view tab, prompt for and set new view name.
5062    */
5063   @Override
5064   public void tabbedPane_mousePressed(MouseEvent e)
5065   {
5066     if (e.isPopupTrigger())
5067     {
5068       String msg = MessageManager.getString("label.enter_view_name");
5069       String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
5070               JvOptionPane.QUESTION_MESSAGE);
5071
5072       if (reply != null)
5073       {
5074         viewport.setViewName(reply);
5075         // TODO warn if reply is in getExistingViewNames()?
5076         tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5077       }
5078     }
5079   }
5080
5081   public AlignViewport getCurrentView()
5082   {
5083     return viewport;
5084   }
5085
5086   /**
5087    * Open the dialog for regex description parsing.
5088    */
5089   @Override
5090   protected void extractScores_actionPerformed(ActionEvent e)
5091   {
5092     ParseProperties pp = new jalview.analysis.ParseProperties(
5093             viewport.getAlignment());
5094     // TODO: verify regex and introduce GUI dialog for version 2.5
5095     // if (pp.getScoresFromDescription("col", "score column ",
5096     // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5097     // true)>0)
5098     if (pp.getScoresFromDescription("description column",
5099             "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5100     {
5101       buildSortByAnnotationScoresMenu();
5102     }
5103   }
5104
5105   /*
5106    * (non-Javadoc)
5107    * 
5108    * @see
5109    * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5110    * )
5111    */
5112   @Override
5113   protected void showDbRefs_actionPerformed(ActionEvent e)
5114   {
5115     viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5116   }
5117
5118   /*
5119    * (non-Javadoc)
5120    * 
5121    * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5122    * ActionEvent)
5123    */
5124   @Override
5125   protected void showNpFeats_actionPerformed(ActionEvent e)
5126   {
5127     viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5128   }
5129
5130   /**
5131    * find the viewport amongst the tabs in this alignment frame and close that
5132    * tab
5133    * 
5134    * @param av
5135    */
5136   public boolean closeView(AlignViewportI av)
5137   {
5138     if (viewport == av)
5139     {
5140       this.closeMenuItem_actionPerformed(false);
5141       return true;
5142     }
5143     Component[] comp = tabbedPane.getComponents();
5144     for (int i = 0; comp != null && i < comp.length; i++)
5145     {
5146       if (comp[i] instanceof AlignmentPanel)
5147       {
5148         if (((AlignmentPanel) comp[i]).av == av)
5149         {
5150           // close the view.
5151           closeView((AlignmentPanel) comp[i]);
5152           return true;
5153         }
5154       }
5155     }
5156     return false;
5157   }
5158
5159   protected void build_fetchdbmenu(JMenu webService)
5160   {
5161     // Temporary hack - DBRef Fetcher always top level ws entry.
5162     // TODO We probably want to store a sequence database checklist in
5163     // preferences and have checkboxes.. rather than individual sources selected
5164     // here
5165     final JMenu rfetch = new JMenu(
5166             MessageManager.getString("action.fetch_db_references"));
5167     rfetch.setToolTipText(MessageManager.getString(
5168             "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5169     webService.add(rfetch);
5170
5171     final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5172             MessageManager.getString("option.trim_retrieved_seqs"));
5173     trimrs.setToolTipText(
5174             MessageManager.getString("label.trim_retrieved_sequences"));
5175     trimrs.setSelected(
5176             Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5177     trimrs.addActionListener(new ActionListener()
5178     {
5179       @Override
5180       public void actionPerformed(ActionEvent e)
5181       {
5182         trimrs.setSelected(trimrs.isSelected());
5183         Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5184                 Boolean.valueOf(trimrs.isSelected()).toString());
5185       };
5186     });
5187     rfetch.add(trimrs);
5188     JMenuItem fetchr = new JMenuItem(
5189             MessageManager.getString("label.standard_databases"));
5190     fetchr.setToolTipText(
5191             MessageManager.getString("label.fetch_embl_uniprot"));
5192     fetchr.addActionListener(new ActionListener()
5193     {
5194
5195       @Override
5196       public void actionPerformed(ActionEvent e)
5197       {
5198         new Thread(new Runnable()
5199         {
5200           @Override
5201           public void run()
5202           {
5203             boolean isNucleotide = alignPanel.alignFrame.getViewport()
5204                     .getAlignment().isNucleotide();
5205             DBRefFetcher dbRefFetcher = new DBRefFetcher(
5206                     alignPanel.av.getSequenceSelection(),
5207                     alignPanel.alignFrame, null,
5208                     alignPanel.alignFrame.featureSettings, isNucleotide);
5209             dbRefFetcher.addListener(new FetchFinishedListenerI()
5210             {
5211               @Override
5212               public void finished()
5213               {
5214                 AlignFrame.this.setMenusForViewport();
5215               }
5216             });
5217             dbRefFetcher.fetchDBRefs(false);
5218           }
5219         }).start();
5220
5221       }
5222
5223     });
5224     rfetch.add(fetchr);
5225     final AlignFrame me = this;
5226     new Thread(new Runnable()
5227     {
5228       @Override
5229       public void run()
5230       {
5231         final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5232                 .getSequenceFetcherSingleton(me);
5233         javax.swing.SwingUtilities.invokeLater(new Runnable()
5234         {
5235           @Override
5236           public void run()
5237           {
5238             String[] dbclasses = sf.getOrderedSupportedSources();
5239             // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5240             // jalview.util.QuickSort.sort(otherdb, otherdb);
5241             List<DbSourceProxy> otherdb;
5242             JMenu dfetch = new JMenu();
5243             JMenu ifetch = new JMenu();
5244             JMenuItem fetchr = null;
5245             int comp = 0, icomp = 0, mcomp = 15;
5246             String mname = null;
5247             int dbi = 0;
5248             for (String dbclass : dbclasses)
5249             {
5250               otherdb = sf.getSourceProxy(dbclass);
5251               // add a single entry for this class, or submenu allowing 'fetch
5252               // all' or pick one
5253               if (otherdb == null || otherdb.size() < 1)
5254               {
5255                 continue;
5256               }
5257               // List<DbSourceProxy> dbs=otherdb;
5258               // otherdb=new ArrayList<DbSourceProxy>();
5259               // for (DbSourceProxy db:dbs)
5260               // {
5261               // if (!db.isA(DBRefSource.ALIGNMENTDB)
5262               // }
5263               if (mname == null)
5264               {
5265                 mname = "From " + dbclass;
5266               }
5267               if (otherdb.size() == 1)
5268               {
5269                 final DbSourceProxy[] dassource = otherdb
5270                         .toArray(new DbSourceProxy[0]);
5271                 DbSourceProxy src = otherdb.get(0);
5272                 fetchr = new JMenuItem(src.getDbSource());
5273                 fetchr.addActionListener(new ActionListener()
5274                 {
5275
5276                   @Override
5277                   public void actionPerformed(ActionEvent e)
5278                   {
5279                     new Thread(new Runnable()
5280                     {
5281
5282                       @Override
5283                       public void run()
5284                       {
5285                         boolean isNucleotide = alignPanel.alignFrame
5286                                 .getViewport().getAlignment()
5287                                 .isNucleotide();
5288                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5289                                 alignPanel.av.getSequenceSelection(),
5290                                 alignPanel.alignFrame, dassource,
5291                                 alignPanel.alignFrame.featureSettings,
5292                                 isNucleotide);
5293                         dbRefFetcher
5294                                 .addListener(new FetchFinishedListenerI()
5295                                 {
5296                                   @Override
5297                                   public void finished()
5298                                   {
5299                                     AlignFrame.this.setMenusForViewport();
5300                                   }
5301                                 });
5302                         dbRefFetcher.fetchDBRefs(false);
5303                       }
5304                     }).start();
5305                   }
5306
5307                 });
5308                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5309                         MessageManager.formatMessage(
5310                                 "label.fetch_retrieve_from", new Object[]
5311                                 { src.getDbName() })));
5312                 dfetch.add(fetchr);
5313                 comp++;
5314               }
5315               else
5316               {
5317                 final DbSourceProxy[] dassource = otherdb
5318                         .toArray(new DbSourceProxy[0]);
5319                 // fetch all entry
5320                 DbSourceProxy src = otherdb.get(0);
5321                 fetchr = new JMenuItem(MessageManager
5322                         .formatMessage("label.fetch_all_param", new Object[]
5323                         { src.getDbSource() }));
5324                 fetchr.addActionListener(new ActionListener()
5325                 {
5326                   @Override
5327                   public void actionPerformed(ActionEvent e)
5328                   {
5329                     new Thread(new Runnable()
5330                     {
5331
5332                       @Override
5333                       public void run()
5334                       {
5335                         boolean isNucleotide = alignPanel.alignFrame
5336                                 .getViewport().getAlignment()
5337                                 .isNucleotide();
5338                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5339                                 alignPanel.av.getSequenceSelection(),
5340                                 alignPanel.alignFrame, dassource,
5341                                 alignPanel.alignFrame.featureSettings,
5342                                 isNucleotide);
5343                         dbRefFetcher
5344                                 .addListener(new FetchFinishedListenerI()
5345                                 {
5346                                   @Override
5347                                   public void finished()
5348                                   {
5349                                     AlignFrame.this.setMenusForViewport();
5350                                   }
5351                                 });
5352                         dbRefFetcher.fetchDBRefs(false);
5353                       }
5354                     }).start();
5355                   }
5356                 });
5357
5358                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5359                         MessageManager.formatMessage(
5360                                 "label.fetch_retrieve_from_all_sources",
5361                                 new Object[]
5362                                 { Integer.valueOf(otherdb.size())
5363                                         .toString(),
5364                                     src.getDbSource(), src.getDbName() })));
5365                 dfetch.add(fetchr);
5366                 comp++;
5367                 // and then build the rest of the individual menus
5368                 ifetch = new JMenu(MessageManager.formatMessage(
5369                         "label.source_from_db_source", new Object[]
5370                         { src.getDbSource() }));
5371                 icomp = 0;
5372                 String imname = null;
5373                 int i = 0;
5374                 for (DbSourceProxy sproxy : otherdb)
5375                 {
5376                   String dbname = sproxy.getDbName();
5377                   String sname = dbname.length() > 5
5378                           ? dbname.substring(0, 5) + "..."
5379                           : dbname;
5380                   String msname = dbname.length() > 10
5381                           ? dbname.substring(0, 10) + "..."
5382                           : dbname;
5383                   if (imname == null)
5384                   {
5385                     imname = MessageManager
5386                             .formatMessage("label.from_msname", new Object[]
5387                             { sname });
5388                   }
5389                   fetchr = new JMenuItem(msname);
5390                   final DbSourceProxy[] dassrc = { sproxy };
5391                   fetchr.addActionListener(new ActionListener()
5392                   {
5393
5394                     @Override
5395                     public void actionPerformed(ActionEvent e)
5396                     {
5397                       new Thread(new Runnable()
5398                       {
5399
5400                         @Override
5401                         public void run()
5402                         {
5403                           boolean isNucleotide = alignPanel.alignFrame
5404                                   .getViewport().getAlignment()
5405                                   .isNucleotide();
5406                           DBRefFetcher dbRefFetcher = new DBRefFetcher(
5407                                   alignPanel.av.getSequenceSelection(),
5408                                   alignPanel.alignFrame, dassrc,
5409                                   alignPanel.alignFrame.featureSettings,
5410                                   isNucleotide);
5411                           dbRefFetcher
5412                                   .addListener(new FetchFinishedListenerI()
5413                                   {
5414                                     @Override
5415                                     public void finished()
5416                                     {
5417                                       AlignFrame.this.setMenusForViewport();
5418                                     }
5419                                   });
5420                           dbRefFetcher.fetchDBRefs(false);
5421                         }
5422                       }).start();
5423                     }
5424
5425                   });
5426                   fetchr.setToolTipText(
5427                           "<html>" + MessageManager.formatMessage(
5428                                   "label.fetch_retrieve_from", new Object[]
5429                                   { dbname }));
5430                   ifetch.add(fetchr);
5431                   ++i;
5432                   if (++icomp >= mcomp || i == (otherdb.size()))
5433                   {
5434                     ifetch.setText(MessageManager.formatMessage(
5435                             "label.source_to_target", imname, sname));
5436                     dfetch.add(ifetch);
5437                     ifetch = new JMenu();
5438                     imname = null;
5439                     icomp = 0;
5440                     comp++;
5441                   }
5442                 }
5443               }
5444               ++dbi;
5445               if (comp >= mcomp || dbi >= (dbclasses.length))
5446               {
5447                 dfetch.setText(MessageManager.formatMessage(
5448                         "label.source_to_target", mname, dbclass));
5449                 rfetch.add(dfetch);
5450                 dfetch = new JMenu();
5451                 mname = null;
5452                 comp = 0;
5453               }
5454             }
5455           }
5456         });
5457       }
5458     }).start();
5459
5460   }
5461
5462   /**
5463    * Left justify the whole alignment.
5464    */
5465   @Override
5466   protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5467   {
5468     AlignmentI al = viewport.getAlignment();
5469     al.justify(false);
5470     viewport.firePropertyChange("alignment", null, al);
5471   }
5472
5473   /**
5474    * Right justify the whole alignment.
5475    */
5476   @Override
5477   protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5478   {
5479     AlignmentI al = viewport.getAlignment();
5480     al.justify(true);
5481     viewport.firePropertyChange("alignment", null, al);
5482   }
5483
5484   @Override
5485   public void setShowSeqFeatures(boolean b)
5486   {
5487     showSeqFeatures.setSelected(b);
5488     viewport.setShowSequenceFeatures(b);
5489   }
5490
5491   /*
5492    * (non-Javadoc)
5493    * 
5494    * @see
5495    * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5496    * awt.event.ActionEvent)
5497    */
5498   @Override
5499   protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5500   {
5501     viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5502     alignPanel.paintAlignment(false, false);
5503   }
5504
5505   /*
5506    * (non-Javadoc)
5507    * 
5508    * @see
5509    * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5510    * .ActionEvent)
5511    */
5512   @Override
5513   protected void showGroupConsensus_actionPerformed(ActionEvent e)
5514   {
5515     viewport.setShowGroupConsensus(showGroupConsensus.getState());
5516     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5517
5518   }
5519
5520   /*
5521    * (non-Javadoc)
5522    * 
5523    * @see
5524    * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5525    * .event.ActionEvent)
5526    */
5527   @Override
5528   protected void showGroupConservation_actionPerformed(ActionEvent e)
5529   {
5530     viewport.setShowGroupConservation(showGroupConservation.getState());
5531     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5532   }
5533
5534   /*
5535    * (non-Javadoc)
5536    * 
5537    * @see
5538    * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5539    * .event.ActionEvent)
5540    */
5541   @Override
5542   protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5543   {
5544     viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5545     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5546   }
5547
5548   /*
5549    * (non-Javadoc)
5550    * 
5551    * @see
5552    * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5553    * .event.ActionEvent)
5554    */
5555   @Override
5556   protected void showSequenceLogo_actionPerformed(ActionEvent e)
5557   {
5558     viewport.setShowSequenceLogo(showSequenceLogo.getState());
5559     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5560   }
5561
5562   @Override
5563   protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5564   {
5565     showSequenceLogo.setState(true);
5566     viewport.setShowSequenceLogo(true);
5567     viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5568     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5569   }
5570
5571   @Override
5572   protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5573   {
5574     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5575   }
5576
5577   /*
5578    * (non-Javadoc)
5579    * 
5580    * @see
5581    * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5582    * .event.ActionEvent)
5583    */
5584   @Override
5585   protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5586   {
5587     if (avc.makeGroupsFromSelection())
5588     {
5589       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5590       alignPanel.updateAnnotation();
5591       alignPanel.paintAlignment(true,
5592               viewport.needToUpdateStructureViews());
5593     }
5594   }
5595
5596   public void clearAlignmentSeqRep()
5597   {
5598     // TODO refactor alignmentseqrep to controller
5599     if (viewport.getAlignment().hasSeqrep())
5600     {
5601       viewport.getAlignment().setSeqrep(null);
5602       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5603       alignPanel.updateAnnotation();
5604       alignPanel.paintAlignment(true, true);
5605     }
5606   }
5607
5608   @Override
5609   protected void createGroup_actionPerformed(ActionEvent e)
5610   {
5611     if (avc.createGroup())
5612     {
5613       if (applyAutoAnnotationSettings.isSelected())
5614       {
5615         alignPanel.updateAnnotation(true, false);
5616       }
5617       alignPanel.alignmentChanged();
5618     }
5619   }
5620
5621   @Override
5622   protected void unGroup_actionPerformed(ActionEvent e)
5623   {
5624     if (avc.unGroup())
5625     {
5626       alignPanel.alignmentChanged();
5627     }
5628   }
5629
5630   /**
5631    * make the given alignmentPanel the currently selected tab
5632    * 
5633    * @param alignmentPanel
5634    */
5635   public void setDisplayedView(AlignmentPanel alignmentPanel)
5636   {
5637     if (!viewport.getSequenceSetId()
5638             .equals(alignmentPanel.av.getSequenceSetId()))
5639     {
5640       throw new Error(MessageManager.getString(
5641               "error.implementation_error_cannot_show_view_alignment_frame"));
5642     }
5643     if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5644             .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5645     {
5646       tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5647     }
5648   }
5649
5650   /**
5651    * Action on selection of menu options to Show or Hide annotations.
5652    * 
5653    * @param visible
5654    * @param forSequences
5655    *          update sequence-related annotations
5656    * @param forAlignment
5657    *          update non-sequence-related annotations
5658    */
5659   @Override
5660   protected void setAnnotationsVisibility(boolean visible,
5661           boolean forSequences, boolean forAlignment)
5662   {
5663     AlignmentAnnotation[] anns = alignPanel.getAlignment()
5664             .getAlignmentAnnotation();
5665     if (anns == null)
5666     {
5667       return;
5668     }
5669     for (AlignmentAnnotation aa : anns)
5670     {
5671       /*
5672        * don't display non-positional annotations on an alignment
5673        */
5674       if (aa.annotations == null)
5675       {
5676         continue;
5677       }
5678       boolean apply = (aa.sequenceRef == null && forAlignment)
5679               || (aa.sequenceRef != null && forSequences);
5680       if (apply)
5681       {
5682         aa.visible = visible;
5683       }
5684     }
5685     alignPanel.validateAnnotationDimensions(true);
5686     alignPanel.alignmentChanged();
5687   }
5688
5689   /**
5690    * Store selected annotation sort order for the view and repaint.
5691    */
5692   @Override
5693   protected void sortAnnotations_actionPerformed()
5694   {
5695     this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5696     this.alignPanel.av
5697             .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5698     alignPanel.paintAlignment(false, false);
5699   }
5700
5701   /**
5702    * 
5703    * @return alignment panels in this alignment frame
5704    */
5705   public List<? extends AlignmentViewPanel> getAlignPanels()
5706   {
5707     // alignPanels is never null
5708     // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5709     return alignPanels;
5710   }
5711
5712   /**
5713    * Open a new alignment window, with the cDNA associated with this (protein)
5714    * alignment, aligned as is the protein.
5715    */
5716   protected void viewAsCdna_actionPerformed()
5717   {
5718     // TODO no longer a menu action - refactor as required
5719     final AlignmentI alignment = getViewport().getAlignment();
5720     List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5721     if (mappings == null)
5722     {
5723       return;
5724     }
5725     List<SequenceI> cdnaSeqs = new ArrayList<>();
5726     for (SequenceI aaSeq : alignment.getSequences())
5727     {
5728       for (AlignedCodonFrame acf : mappings)
5729       {
5730         SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5731         if (dnaSeq != null)
5732         {
5733           /*
5734            * There is a cDNA mapping for this protein sequence - add to new
5735            * alignment. It will share the same dataset sequence as other mapped
5736            * cDNA (no new mappings need to be created).
5737            */
5738           final Sequence newSeq = new Sequence(dnaSeq);
5739           newSeq.setDatasetSequence(dnaSeq);
5740           cdnaSeqs.add(newSeq);
5741         }
5742       }
5743     }
5744     if (cdnaSeqs.size() == 0)
5745     {
5746       // show a warning dialog no mapped cDNA
5747       return;
5748     }
5749     AlignmentI cdna = new Alignment(
5750             cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5751     GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5752             AlignFrame.DEFAULT_HEIGHT);
5753     cdna.alignAs(alignment);
5754     String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5755             + this.title;
5756     Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5757             AlignFrame.DEFAULT_HEIGHT);
5758   }
5759
5760   /**
5761    * Set visibility of dna/protein complement view (available when shown in a
5762    * split frame).
5763    * 
5764    * @param show
5765    */
5766   @Override
5767   protected void showComplement_actionPerformed(boolean show)
5768   {
5769     SplitContainerI sf = getSplitViewContainer();
5770     if (sf != null)
5771     {
5772       sf.setComplementVisible(this, show);
5773     }
5774   }
5775
5776   /**
5777    * Generate the reverse (optionally complemented) of the selected sequences,
5778    * and add them to the alignment
5779    */
5780   @Override
5781   protected void showReverse_actionPerformed(boolean complement)
5782   {
5783     AlignmentI al = null;
5784     try
5785     {
5786       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5787       al = dna.reverseCdna(complement);
5788       viewport.addAlignment(al, "");
5789       addHistoryItem(new EditCommand(
5790               MessageManager.getString("label.add_sequences"), Action.PASTE,
5791               al.getSequencesArray(), 0, al.getWidth(),
5792               viewport.getAlignment()));
5793     } catch (Exception ex)
5794     {
5795       System.err.println(ex.getMessage());
5796       return;
5797     }
5798   }
5799
5800   /**
5801    * Try to run a script in the Groovy console, having first ensured that this
5802    * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5803    * be targeted at this alignment.
5804    */
5805   @Override
5806   protected void runGroovy_actionPerformed()
5807   {
5808     Jalview.setCurrentAlignFrame(this);
5809     groovy.ui.Console console = Desktop.getGroovyConsole();
5810     if (console != null)
5811     {
5812       try
5813       {
5814         console.runScript();
5815       } catch (Exception ex)
5816       {
5817         System.err.println((ex.toString()));
5818         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5819                 MessageManager.getString("label.couldnt_run_groovy_script"),
5820                 MessageManager.getString("label.groovy_support_failed"),
5821                 JvOptionPane.ERROR_MESSAGE);
5822       }
5823     }
5824     else
5825     {
5826       System.err.println("Can't run Groovy script as console not found");
5827     }
5828   }
5829
5830   /**
5831    * Hides columns containing (or not containing) a specified feature, provided
5832    * that would not leave all columns hidden
5833    * 
5834    * @param featureType
5835    * @param columnsContaining
5836    * @return
5837    */
5838   public boolean hideFeatureColumns(String featureType,
5839           boolean columnsContaining)
5840   {
5841     boolean notForHiding = avc.markColumnsContainingFeatures(
5842             columnsContaining, false, false, featureType);
5843     if (notForHiding)
5844     {
5845       if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5846               false, featureType))
5847       {
5848         getViewport().hideSelectedColumns();
5849         return true;
5850       }
5851     }
5852     return false;
5853   }
5854
5855   @Override
5856   protected void selectHighlightedColumns_actionPerformed(
5857           ActionEvent actionEvent)
5858   {
5859     // include key modifier check in case user selects from menu
5860     avc.markHighlightedColumns(
5861             (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5862             (actionEvent.getModifiers() & (ActionEvent.META_MASK
5863                     | ActionEvent.CTRL_MASK)) != 0);
5864   }
5865
5866   /**
5867    * Rebuilds the Colour menu, including any user-defined colours which have
5868    * been loaded either on startup or during the session
5869    */
5870   public void buildColourMenu()
5871   {
5872     colourMenu.removeAll();
5873
5874     colourMenu.add(applyToAllGroups);
5875     colourMenu.add(textColour);
5876     colourMenu.addSeparator();
5877
5878     ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5879             viewport.getAlignment(), false);
5880
5881     colourMenu.add(annotationColour);
5882     bg.add(annotationColour);
5883     colourMenu.addSeparator();
5884     colourMenu.add(conservationMenuItem);
5885     colourMenu.add(modifyConservation);
5886     colourMenu.add(abovePIDThreshold);
5887     colourMenu.add(modifyPID);
5888
5889     ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5890     ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5891   }
5892
5893   /**
5894    * Open a dialog (if not already open) that allows the user to select and
5895    * calculate PCA or Tree analysis
5896    */
5897   protected void openTreePcaDialog()
5898   {
5899     if (alignPanel.getCalculationDialog() == null)
5900     {
5901       new CalculationChooser(AlignFrame.this);
5902     }
5903   }
5904
5905   /**
5906    * Sets the status of the HMMER menu
5907    */
5908   public void updateHMMERStatus()
5909   {
5910     hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
5911   }
5912
5913   @Override
5914   protected void loadVcf_actionPerformed()
5915   {
5916     JalviewFileChooser chooser = new JalviewFileChooser(
5917             Cache.getProperty("LAST_DIRECTORY"));
5918     chooser.setFileView(new JalviewFileView());
5919     chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5920     chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5921
5922     int value = chooser.showOpenDialog(null);
5923
5924     if (value == JalviewFileChooser.APPROVE_OPTION)
5925     {
5926       String choice = chooser.getSelectedFile().getPath();
5927       Cache.setProperty("LAST_DIRECTORY", choice);
5928       SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5929       new VCFLoader(choice).loadVCF(seqs, this);
5930     }
5931
5932   }
5933 }
5934
5935 class PrintThread extends Thread
5936 {
5937   AlignmentPanel ap;
5938
5939   public PrintThread(AlignmentPanel ap)
5940   {
5941     this.ap = ap;
5942   }
5943
5944   static PageFormat pf;
5945
5946   @Override
5947   public void run()
5948   {
5949     PrinterJob printJob = PrinterJob.getPrinterJob();
5950
5951     if (pf != null)
5952     {
5953       printJob.setPrintable(ap, pf);
5954     }
5955     else
5956     {
5957       printJob.setPrintable(ap);
5958     }
5959
5960     if (printJob.printDialog())
5961     {
5962       try
5963       {
5964         printJob.print();
5965       } catch (Exception PrintException)
5966       {
5967         PrintException.printStackTrace();
5968       }
5969     }
5970   }
5971 }