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