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