JAL-3070 slivka service discovery as a background thread - still need to unify Jabaws...
[jalview.git] / src / jalview / gui / AlignFrame.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.GeneticCodeI;
28 import jalview.analysis.ParseProperties;
29 import jalview.analysis.SequenceIdMatcher;
30 import jalview.api.AlignExportSettingI;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignViewportI;
34 import jalview.api.AlignmentViewPanel;
35 import jalview.api.FeatureSettingsControllerI;
36 import jalview.api.FeatureSettingsModelI;
37 import jalview.api.SplitContainerI;
38 import jalview.api.ViewStyleI;
39 import jalview.api.analysis.SimilarityParamsI;
40 import jalview.bin.Cache;
41 import jalview.bin.Jalview;
42 import jalview.commands.CommandI;
43 import jalview.commands.EditCommand;
44 import jalview.commands.EditCommand.Action;
45 import jalview.commands.OrderCommand;
46 import jalview.commands.RemoveGapColCommand;
47 import jalview.commands.RemoveGapsCommand;
48 import jalview.commands.SlideSequencesCommand;
49 import jalview.commands.TrimRegionCommand;
50 import jalview.datamodel.AlignedCodonFrame;
51 import jalview.datamodel.Alignment;
52 import jalview.datamodel.AlignmentAnnotation;
53 import jalview.datamodel.AlignmentExportData;
54 import jalview.datamodel.AlignmentI;
55 import jalview.datamodel.AlignmentOrder;
56 import jalview.datamodel.AlignmentView;
57 import jalview.datamodel.ColumnSelection;
58 import jalview.datamodel.HiddenColumns;
59 import jalview.datamodel.HiddenSequences;
60 import jalview.datamodel.PDBEntry;
61 import jalview.datamodel.SeqCigar;
62 import jalview.datamodel.Sequence;
63 import jalview.datamodel.SequenceGroup;
64 import jalview.datamodel.SequenceI;
65 import jalview.gui.ColourMenuHelper.ColourChangeListener;
66 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
67 import jalview.hmmer.HMMAlign;
68 import jalview.hmmer.HMMBuild;
69 import jalview.hmmer.HMMERParamStore;
70 import jalview.hmmer.HMMERPreset;
71 import jalview.hmmer.HMMSearch;
72 import jalview.hmmer.HmmerCommand;
73 import jalview.hmmer.JackHMMER;
74 import jalview.io.AlignmentProperties;
75 import jalview.io.AnnotationFile;
76 import jalview.io.BackupFiles;
77 import jalview.io.BioJsHTMLOutput;
78 import jalview.io.DataSourceType;
79 import jalview.io.FileFormat;
80 import jalview.io.FileFormatI;
81 import jalview.io.FileFormats;
82 import jalview.io.FileLoader;
83 import jalview.io.FileParse;
84 import jalview.io.FormatAdapter;
85 import jalview.io.HtmlSvgOutput;
86 import jalview.io.IdentifyFile;
87 import jalview.io.JPredFile;
88 import jalview.io.JalviewFileChooser;
89 import jalview.io.JalviewFileView;
90 import jalview.io.JnetAnnotationMaker;
91 import jalview.io.NewickFile;
92 import jalview.io.ScoreMatrixFile;
93 import jalview.io.TCoffeeScoreFile;
94 import jalview.io.vcf.VCFLoader;
95 import jalview.jbgui.GAlignFrame;
96 import jalview.schemes.ColourSchemeI;
97 import jalview.schemes.ColourSchemes;
98 import jalview.schemes.ResidueColourScheme;
99 import jalview.schemes.TCoffeeColourScheme;
100 import jalview.util.MessageManager;
101 import jalview.viewmodel.AlignmentViewport;
102 import jalview.viewmodel.ViewportRanges;
103 import jalview.ws.DBRefFetcher;
104 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
105 import jalview.ws.api.ServiceWithParameters;
106 import jalview.ws.jws1.Discoverer;
107 import jalview.ws.jws2.Jws2Discoverer;
108 import jalview.ws.params.ArgumentI;
109 import jalview.ws.params.ParamDatastoreI;
110 import jalview.ws.params.WsParamSetI;
111 import jalview.ws.seqfetcher.DbSourceProxy;
112 import jalview.ws.slivkaws.SlivkaWSDiscoverer;
113
114 import java.awt.BorderLayout;
115 import java.awt.Component;
116 import java.awt.Rectangle;
117 import java.awt.Toolkit;
118 import java.awt.datatransfer.Clipboard;
119 import java.awt.datatransfer.DataFlavor;
120 import java.awt.datatransfer.StringSelection;
121 import java.awt.datatransfer.Transferable;
122 import java.awt.dnd.DnDConstants;
123 import java.awt.dnd.DropTargetDragEvent;
124 import java.awt.dnd.DropTargetDropEvent;
125 import java.awt.dnd.DropTargetEvent;
126 import java.awt.dnd.DropTargetListener;
127 import java.awt.event.ActionEvent;
128 import java.awt.event.ActionListener;
129 import java.awt.event.FocusAdapter;
130 import java.awt.event.FocusEvent;
131 import java.awt.event.ItemEvent;
132 import java.awt.event.ItemListener;
133 import java.awt.event.KeyAdapter;
134 import java.awt.event.KeyEvent;
135 import java.awt.event.MouseEvent;
136 import java.awt.print.PageFormat;
137 import java.awt.print.PrinterJob;
138 import java.beans.PropertyChangeEvent;
139 import java.io.File;
140 import java.io.FileWriter;
141 import java.io.IOException;
142 import java.io.PrintWriter;
143 import java.net.URL;
144 import java.util.ArrayList;
145 import java.util.Arrays;
146 import java.util.Deque;
147 import java.util.HashSet;
148 import java.util.List;
149 import java.util.Set;
150 import java.util.Vector;
151
152 import javax.swing.ButtonGroup;
153 import javax.swing.JCheckBoxMenuItem;
154 import javax.swing.JEditorPane;
155 import javax.swing.JFileChooser;
156 import javax.swing.JInternalFrame;
157 import javax.swing.JLayeredPane;
158 import javax.swing.JMenu;
159 import javax.swing.JMenuItem;
160 import javax.swing.JOptionPane;
161 import javax.swing.JScrollPane;
162 import javax.swing.SwingUtilities;
163
164 /**
165  * DOCUMENT ME!
166  * 
167  * @author $author$
168  * @version $Revision$
169  */
170 public class AlignFrame extends GAlignFrame implements DropTargetListener,
171         IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
172 {
173   public static final int DEFAULT_WIDTH = 700;
174
175   public static final int DEFAULT_HEIGHT = 500;
176
177   /*
178    * The currently displayed panel (selected tabbed view if more than one)
179    */
180   public AlignmentPanel alignPanel;
181
182   AlignViewport viewport;
183
184   public AlignViewControllerI avc;
185
186   List<AlignmentPanel> alignPanels = new ArrayList<>();
187
188   /**
189    * Last format used to load or save alignments in this window
190    */
191   FileFormatI currentFileFormat = null;
192
193   /**
194    * Current filename for this alignment
195    */
196   String fileName = null;
197
198
199   /**
200    * Creates a new AlignFrame object with specific width and height.
201    * 
202    * @param al
203    * @param width
204    * @param height
205    */
206   public AlignFrame(AlignmentI al, int width, int height)
207   {
208     this(al, null, width, height);
209   }
210
211   /**
212    * Creates a new AlignFrame object with specific width, height and
213    * sequenceSetId
214    * 
215    * @param al
216    * @param width
217    * @param height
218    * @param sequenceSetId
219    */
220   public AlignFrame(AlignmentI al, int width, int height,
221           String sequenceSetId)
222   {
223     this(al, null, width, height, sequenceSetId);
224   }
225
226   /**
227    * Creates a new AlignFrame object with specific width, height and
228    * sequenceSetId
229    * 
230    * @param al
231    * @param width
232    * @param height
233    * @param sequenceSetId
234    * @param viewId
235    */
236   public AlignFrame(AlignmentI al, int width, int height,
237           String sequenceSetId, String viewId)
238   {
239     this(al, null, width, height, sequenceSetId, viewId);
240   }
241
242   /**
243    * new alignment window with hidden columns
244    * 
245    * @param al
246    *          AlignmentI
247    * @param hiddenColumns
248    *          ColumnSelection or null
249    * @param width
250    *          Width of alignment frame
251    * @param height
252    *          height of frame.
253    */
254   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
255           int height)
256   {
257     this(al, hiddenColumns, width, height, null);
258   }
259
260   /**
261    * Create alignment frame for al with hiddenColumns, a specific width and
262    * height, and specific sequenceId
263    * 
264    * @param al
265    * @param hiddenColumns
266    * @param width
267    * @param height
268    * @param sequenceSetId
269    *          (may be null)
270    */
271   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
272           int height, String sequenceSetId)
273   {
274     this(al, hiddenColumns, width, height, sequenceSetId, null);
275   }
276
277   /**
278    * Create alignment frame for al with hiddenColumns, a specific width and
279    * height, and specific sequenceId
280    * 
281    * @param al
282    * @param hiddenColumns
283    * @param width
284    * @param height
285    * @param sequenceSetId
286    *          (may be null)
287    * @param viewId
288    *          (may be null)
289    */
290   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
291           int height, String sequenceSetId, String viewId)
292   {
293     setSize(width, height);
294
295     if (al.getDataset() == null)
296     {
297       al.setDataset(null);
298     }
299
300     viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
301
302     alignPanel = new AlignmentPanel(this, viewport);
303
304     addAlignmentPanel(alignPanel, true);
305     init();
306   }
307
308   public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
309           HiddenColumns hiddenColumns, int width, int height)
310   {
311     setSize(width, height);
312
313     if (al.getDataset() == null)
314     {
315       al.setDataset(null);
316     }
317
318     viewport = new AlignViewport(al, hiddenColumns);
319
320     if (hiddenSeqs != null && hiddenSeqs.length > 0)
321     {
322       viewport.hideSequence(hiddenSeqs);
323     }
324     alignPanel = new AlignmentPanel(this, viewport);
325     addAlignmentPanel(alignPanel, true);
326     init();
327   }
328
329   /**
330    * Make a new AlignFrame from existing alignmentPanels
331    * 
332    * @param ap
333    *          AlignmentPanel
334    * @param av
335    *          AlignViewport
336    */
337   public AlignFrame(AlignmentPanel ap)
338   {
339     viewport = ap.av;
340     alignPanel = ap;
341     addAlignmentPanel(ap, false);
342     init();
343   }
344
345   /**
346    * initalise the alignframe from the underlying viewport data and the
347    * configurations
348    */
349   void init()
350   {
351     if (!Jalview.isHeadlessMode())
352     {
353       progressBar = new ProgressBar(this.statusPanel, this.statusBar);
354     }
355
356     avc = new jalview.controller.AlignViewController(this, viewport,
357             alignPanel);
358     if (viewport.getAlignmentConservationAnnotation() == null)
359     {
360       // BLOSUM62Colour.setEnabled(false);
361       conservationMenuItem.setEnabled(false);
362       modifyConservation.setEnabled(false);
363       // PIDColour.setEnabled(false);
364       // abovePIDThreshold.setEnabled(false);
365       // modifyPID.setEnabled(false);
366     }
367
368     String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
369             "No sort");
370
371     if (sortby.equals("Id"))
372     {
373       sortIDMenuItem_actionPerformed(null);
374     }
375     else if (sortby.equals("Pairwise Identity"))
376     {
377       sortPairwiseMenuItem_actionPerformed(null);
378     }
379
380     this.alignPanel.av
381             .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
382
383     setMenusFromViewport(viewport);
384     buildSortByAnnotationScoresMenu();
385     calculateTree.addActionListener(new ActionListener()
386     {
387
388       @Override
389       public void actionPerformed(ActionEvent e)
390       {
391         openTreePcaDialog();
392       }
393     });
394     buildColourMenu();
395
396     if (Desktop.desktop != null)
397     {
398       this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
399       addServiceListeners();
400       setGUINucleotide();
401     }
402
403     if (viewport.getWrapAlignment())
404     {
405       wrapMenuItem_actionPerformed(null);
406     }
407
408     if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
409     {
410       this.overviewMenuItem_actionPerformed(null);
411     }
412
413     addKeyListener();
414
415     final List<AlignmentPanel> selviews = new ArrayList<>();
416     final List<AlignmentPanel> origview = new ArrayList<>();
417     final String menuLabel = MessageManager
418             .getString("label.copy_format_from");
419     ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
420             new ViewSetProvider()
421             {
422
423               @Override
424               public AlignmentPanel[] getAllAlignmentPanels()
425               {
426                 origview.clear();
427                 origview.add(alignPanel);
428                 // make an array of all alignment panels except for this one
429                 List<AlignmentPanel> aps = new ArrayList<>(
430                         Arrays.asList(Desktop.getAlignmentPanels(null)));
431                 aps.remove(AlignFrame.this.alignPanel);
432                 return aps.toArray(new AlignmentPanel[aps.size()]);
433               }
434             }, selviews, new ItemListener()
435             {
436
437               @Override
438               public void itemStateChanged(ItemEvent e)
439               {
440                 if (origview.size() > 0)
441                 {
442                   final AlignmentPanel ap = origview.get(0);
443
444                   /*
445                    * Copy the ViewStyle of the selected panel to 'this one'.
446                    * Don't change value of 'scaleProteinAsCdna' unless copying
447                    * from a SplitFrame.
448                    */
449                   ViewStyleI vs = selviews.get(0).getAlignViewport()
450                           .getViewStyle();
451                   boolean fromSplitFrame = selviews.get(0)
452                           .getAlignViewport().getCodingComplement() != null;
453                   if (!fromSplitFrame)
454                   {
455                     vs.setScaleProteinAsCdna(ap.getAlignViewport()
456                             .getViewStyle().isScaleProteinAsCdna());
457                   }
458                   ap.getAlignViewport().setViewStyle(vs);
459
460                   /*
461                    * Also rescale ViewStyle of SplitFrame complement if there is
462                    * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
463                    * the whole ViewStyle (allow cDNA protein to have different
464                    * fonts)
465                    */
466                   AlignViewportI complement = ap.getAlignViewport()
467                           .getCodingComplement();
468                   if (complement != null && vs.isScaleProteinAsCdna())
469                   {
470                     AlignFrame af = Desktop.getAlignFrameFor(complement);
471                     ((SplitFrame) af.getSplitViewContainer())
472                             .adjustLayout();
473                     af.setMenusForViewport();
474                   }
475
476                   ap.updateLayout();
477                   ap.setSelected(true);
478                   ap.alignFrame.setMenusForViewport();
479
480                 }
481               }
482             });
483     if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
484             .indexOf("devel") > -1
485             || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
486                     .indexOf("test") > -1)
487     {
488       formatMenu.add(vsel);
489     }
490     addFocusListener(new FocusAdapter()
491     {
492       @Override
493       public void focusGained(FocusEvent e)
494       {
495         Jalview.setCurrentAlignFrame(AlignFrame.this);
496       }
497     });
498
499   }
500
501   /**
502    * Change the filename and format for the alignment, and enable the 'reload'
503    * button functionality.
504    * 
505    * @param file
506    *          valid filename
507    * @param format
508    *          format of file
509    */
510   public void setFileName(String file, FileFormatI format)
511   {
512     fileName = file;
513     setFileFormat(format);
514     reload.setEnabled(true);
515   }
516
517   /**
518    * Add a KeyListener with handlers for various KeyPressed and KeyReleased
519    * events
520    */
521   void addKeyListener()
522   {
523     addKeyListener(new KeyAdapter()
524     {
525       @Override
526       public void keyPressed(KeyEvent evt)
527       {
528         if (viewport.cursorMode
529                 && ((evt.getKeyCode() >= KeyEvent.VK_0
530                         && evt.getKeyCode() <= KeyEvent.VK_9)
531                         || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
532                                 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
533                 && Character.isDigit(evt.getKeyChar()))
534         {
535           alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
536         }
537
538         switch (evt.getKeyCode())
539         {
540
541         case 27: // escape key
542           deselectAllSequenceMenuItem_actionPerformed(null);
543
544           break;
545
546         case KeyEvent.VK_DOWN:
547           if (evt.isAltDown() || !viewport.cursorMode)
548           {
549             moveSelectedSequences(false);
550           }
551           if (viewport.cursorMode)
552           {
553             alignPanel.getSeqPanel().moveCursor(0, 1);
554           }
555           break;
556
557         case KeyEvent.VK_UP:
558           if (evt.isAltDown() || !viewport.cursorMode)
559           {
560             moveSelectedSequences(true);
561           }
562           if (viewport.cursorMode)
563           {
564             alignPanel.getSeqPanel().moveCursor(0, -1);
565           }
566
567           break;
568
569         case KeyEvent.VK_LEFT:
570           if (evt.isAltDown() || !viewport.cursorMode)
571           {
572             slideSequences(false,
573                     alignPanel.getSeqPanel().getKeyboardNo1());
574           }
575           else
576           {
577             alignPanel.getSeqPanel().moveCursor(-1, 0);
578           }
579
580           break;
581
582         case KeyEvent.VK_RIGHT:
583           if (evt.isAltDown() || !viewport.cursorMode)
584           {
585             slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
586           }
587           else
588           {
589             alignPanel.getSeqPanel().moveCursor(1, 0);
590           }
591           break;
592
593         case KeyEvent.VK_SPACE:
594           if (viewport.cursorMode)
595           {
596             alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
597                     || evt.isShiftDown() || evt.isAltDown());
598           }
599           break;
600
601         // case KeyEvent.VK_A:
602         // if (viewport.cursorMode)
603         // {
604         // alignPanel.seqPanel.insertNucAtCursor(false,"A");
605         // //System.out.println("A");
606         // }
607         // break;
608         /*
609          * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
610          * System.out.println("closing bracket"); } break;
611          */
612         case KeyEvent.VK_DELETE:
613         case KeyEvent.VK_BACK_SPACE:
614           if (!viewport.cursorMode)
615           {
616             cut_actionPerformed(null);
617           }
618           else
619           {
620             alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
621                     || evt.isShiftDown() || evt.isAltDown());
622           }
623
624           break;
625
626         case KeyEvent.VK_S:
627           if (viewport.cursorMode)
628           {
629             alignPanel.getSeqPanel().setCursorRow();
630           }
631           break;
632         case KeyEvent.VK_C:
633           if (viewport.cursorMode && !evt.isControlDown())
634           {
635             alignPanel.getSeqPanel().setCursorColumn();
636           }
637           break;
638         case KeyEvent.VK_P:
639           if (viewport.cursorMode)
640           {
641             alignPanel.getSeqPanel().setCursorPosition();
642           }
643           break;
644
645         case KeyEvent.VK_ENTER:
646         case KeyEvent.VK_COMMA:
647           if (viewport.cursorMode)
648           {
649             alignPanel.getSeqPanel().setCursorRowAndColumn();
650           }
651           break;
652
653         case KeyEvent.VK_Q:
654           if (viewport.cursorMode)
655           {
656             alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
657           }
658           break;
659         case KeyEvent.VK_M:
660           if (viewport.cursorMode)
661           {
662             alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
663           }
664           break;
665
666         case KeyEvent.VK_F2:
667           viewport.cursorMode = !viewport.cursorMode;
668           statusBar.setText(MessageManager
669                   .formatMessage("label.keyboard_editing_mode", new String[]
670                   { (viewport.cursorMode ? "on" : "off") }));
671           if (viewport.cursorMode)
672           {
673             ViewportRanges ranges = viewport.getRanges();
674             alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
675                     .getStartRes();
676             alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
677                     .getStartSeq();
678           }
679           alignPanel.getSeqPanel().seqCanvas.repaint();
680           break;
681
682         case KeyEvent.VK_F1:
683           try
684           {
685             Help.showHelpWindow();
686           } catch (Exception ex)
687           {
688             ex.printStackTrace();
689           }
690           break;
691         case KeyEvent.VK_H:
692         {
693           boolean toggleSeqs = !evt.isControlDown();
694           boolean toggleCols = !evt.isShiftDown();
695           toggleHiddenRegions(toggleSeqs, toggleCols);
696           break;
697         }
698         case KeyEvent.VK_B:
699         {
700           boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
701           boolean modifyExisting = true; // always modify, don't clear
702                                          // evt.isShiftDown();
703           boolean invertHighlighted = evt.isAltDown();
704           avc.markHighlightedColumns(invertHighlighted, modifyExisting,
705                   toggleSel);
706           break;
707         }
708         case KeyEvent.VK_PAGE_UP:
709           viewport.getRanges().pageUp();
710           break;
711         case KeyEvent.VK_PAGE_DOWN:
712           viewport.getRanges().pageDown();
713           break;
714         }
715       }
716
717       @Override
718       public void keyReleased(KeyEvent evt)
719       {
720         switch (evt.getKeyCode())
721         {
722         case KeyEvent.VK_LEFT:
723           if (evt.isAltDown() || !viewport.cursorMode)
724           {
725             viewport.firePropertyChange("alignment", null,
726                     viewport.getAlignment().getSequences());
727           }
728           break;
729
730         case KeyEvent.VK_RIGHT:
731           if (evt.isAltDown() || !viewport.cursorMode)
732           {
733             viewport.firePropertyChange("alignment", null,
734                     viewport.getAlignment().getSequences());
735           }
736           break;
737         }
738       }
739     });
740   }
741
742   public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
743   {
744     ap.alignFrame = this;
745     avc = new jalview.controller.AlignViewController(this, viewport,
746             alignPanel);
747
748     alignPanels.add(ap);
749
750     PaintRefresher.Register(ap, ap.av.getSequenceSetId());
751
752     int aSize = alignPanels.size();
753
754     tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
755
756     if (aSize == 1 && ap.av.getViewName() == null)
757     {
758       this.getContentPane().add(ap, BorderLayout.CENTER);
759     }
760     else
761     {
762       if (aSize == 2)
763       {
764         setInitialTabVisible();
765       }
766
767       expandViews.setEnabled(true);
768       gatherViews.setEnabled(true);
769       tabbedPane.addTab(ap.av.getViewName(), ap);
770
771       ap.setVisible(false);
772     }
773
774     if (newPanel)
775     {
776       if (ap.av.isPadGaps())
777       {
778         ap.av.getAlignment().padGaps();
779       }
780       ap.av.updateConservation(ap);
781       ap.av.updateConsensus(ap);
782       ap.av.updateStrucConsensus(ap);
783       ap.av.initInformationWorker(ap);
784     }
785   }
786
787   public void setInitialTabVisible()
788   {
789     expandViews.setEnabled(true);
790     gatherViews.setEnabled(true);
791     tabbedPane.setVisible(true);
792     AlignmentPanel first = alignPanels.get(0);
793     tabbedPane.addTab(first.av.getViewName(), first);
794     this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
795   }
796
797   public AlignViewport getViewport()
798   {
799     return viewport;
800   }
801
802   /* Set up intrinsic listeners for dynamically generated GUI bits. */
803   private void addServiceListeners()
804   {
805     final java.beans.PropertyChangeListener thisListener;
806     Desktop.instance.addJalviewPropertyChangeListener("services",
807             thisListener = new java.beans.PropertyChangeListener()
808             {
809               @Override
810               public void propertyChange(PropertyChangeEvent evt)
811               {
812                 // // System.out.println("Discoverer property change.");
813                 // if (evt.getPropertyName().equals("services"))
814                 {
815                   SwingUtilities.invokeLater(new Runnable()
816                   {
817
818                     @Override
819                     public void run()
820                     {
821                       System.err.println(
822                               "Rebuild WS Menu for service change");
823                       BuildWebServiceMenu();
824                     }
825
826                   });
827                 }
828               }
829             });
830     addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
831     {
832       @Override
833       public void internalFrameClosed(
834               javax.swing.event.InternalFrameEvent evt)
835       {
836         // System.out.println("deregistering discoverer listener");
837         Desktop.instance.removeJalviewPropertyChangeListener("services",
838                 thisListener);
839         closeMenuItem_actionPerformed(true);
840       };
841     });
842     // Finally, build the menu once to get current service state
843     new Thread(new Runnable()
844     {
845       @Override
846       public void run()
847       {
848         BuildWebServiceMenu();
849       }
850     }).start();
851   }
852
853   /**
854    * Configure menu items that vary according to whether the alignment is
855    * nucleotide or protein
856    */
857   public void setGUINucleotide()
858   {
859     AlignmentI al = getViewport().getAlignment();
860     boolean nucleotide = al.isNucleotide();
861
862     loadVcf.setVisible(nucleotide);
863     showTranslation.setVisible(nucleotide);
864     showReverse.setVisible(nucleotide);
865     showReverseComplement.setVisible(nucleotide);
866     conservationMenuItem.setEnabled(!nucleotide);
867     modifyConservation
868             .setEnabled(!nucleotide && conservationMenuItem.isSelected());
869     showGroupConservation.setEnabled(!nucleotide);
870
871     showComplementMenuItem
872             .setText(nucleotide ? MessageManager.getString("label.protein")
873                     : MessageManager.getString("label.nucleotide"));
874   }
875
876   /**
877    * set up menus for the current viewport. This may be called after any
878    * operation that affects the data in the current view (selection changed,
879    * etc) to update the menus to reflect the new state.
880    */
881   @Override
882   public void setMenusForViewport()
883   {
884     setMenusFromViewport(viewport);
885   }
886
887   /**
888    * Need to call this method when tabs are selected for multiple views, or when
889    * loading from Jalview2XML.java
890    * 
891    * @param av
892    *          AlignViewport
893    */
894   public void setMenusFromViewport(AlignViewport av)
895   {
896     padGapsMenuitem.setSelected(av.isPadGaps());
897     colourTextMenuItem.setSelected(av.isShowColourText());
898     abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
899     modifyPID.setEnabled(abovePIDThreshold.isSelected());
900     conservationMenuItem.setSelected(av.getConservationSelected());
901     modifyConservation.setEnabled(conservationMenuItem.isSelected());
902     seqLimits.setSelected(av.getShowJVSuffix());
903     idRightAlign.setSelected(av.isRightAlignIds());
904     centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
905     renderGapsMenuItem.setSelected(av.isRenderGaps());
906     wrapMenuItem.setSelected(av.getWrapAlignment());
907     scaleAbove.setVisible(av.getWrapAlignment());
908     scaleLeft.setVisible(av.getWrapAlignment());
909     scaleRight.setVisible(av.getWrapAlignment());
910     annotationPanelMenuItem.setState(av.isShowAnnotation());
911     /*
912      * Show/hide annotations only enabled if annotation panel is shown
913      */
914     showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
915     hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
916     showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
917     hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
918     viewBoxesMenuItem.setSelected(av.getShowBoxes());
919     viewTextMenuItem.setSelected(av.getShowText());
920     showNonconservedMenuItem.setSelected(av.getShowUnconserved());
921     showGroupConsensus.setSelected(av.isShowGroupConsensus());
922     showGroupConservation.setSelected(av.isShowGroupConservation());
923     showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
924     showSequenceLogo.setSelected(av.isShowSequenceLogo());
925     normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
926     showInformationHistogram.setSelected(av.isShowInformationHistogram());
927     showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
928     normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
929
930     ColourMenuHelper.setColourSelected(colourMenu,
931             av.getGlobalColourScheme());
932
933     showSeqFeatures.setSelected(av.isShowSequenceFeatures());
934     hiddenMarkers.setState(av.getShowHiddenMarkers());
935     applyToAllGroups.setState(av.getColourAppliesToAllGroups());
936     showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
937     showDbRefsMenuitem.setSelected(av.isShowDBRefs());
938     autoCalculate.setSelected(av.autoCalculateConsensus);
939     sortByTree.setSelected(av.sortByTree);
940     listenToViewSelections.setSelected(av.followSelection);
941
942     showProducts.setEnabled(canShowProducts());
943     setGroovyEnabled(Desktop.getGroovyConsole() != null);
944
945     updateEditMenuBar();
946   }
947
948   /**
949    * Set the enabled state of the 'Run Groovy' option in the Calculate menu
950    * 
951    * @param b
952    */
953   public void setGroovyEnabled(boolean b)
954   {
955     runGroovy.setEnabled(b);
956   }
957
958   private IProgressIndicator progressBar;
959
960   /*
961    * (non-Javadoc)
962    * 
963    * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
964    */
965   @Override
966   public void setProgressBar(String message, long id)
967   {
968     progressBar.setProgressBar(message, id);
969   }
970
971   @Override
972   public void registerHandler(final long id,
973           final IProgressIndicatorHandler handler)
974   {
975     progressBar.registerHandler(id, handler);
976   }
977
978   /**
979    * 
980    * @return true if any progress bars are still active
981    */
982   @Override
983   public boolean operationInProgress()
984   {
985     return progressBar.operationInProgress();
986   }
987
988   /**
989    * Sets the text of the status bar. Note that setting a null or empty value
990    * will cause the status bar to be hidden, with possibly undesirable flicker
991    * of the screen layout.
992    */
993   @Override
994   public void setStatus(String text)
995   {
996     statusBar.setText(text == null || text.isEmpty() ? " " : text);
997   }
998
999   /*
1000    * Added so Castor Mapping file can obtain Jalview Version
1001    */
1002   public String getVersion()
1003   {
1004     return jalview.bin.Cache.getProperty("VERSION");
1005   }
1006
1007   public FeatureRenderer getFeatureRenderer()
1008   {
1009     return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1010   }
1011
1012   @Override
1013   public void fetchSequence_actionPerformed(ActionEvent e)
1014   {
1015     new jalview.gui.SequenceFetcher(this);
1016   }
1017
1018   @Override
1019   public void addFromFile_actionPerformed(ActionEvent e)
1020   {
1021     Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1022   }
1023
1024   @Override
1025   public void hmmBuild_actionPerformed(boolean withDefaults)
1026   {
1027     if (!alignmentIsSufficient(1))
1028     {
1029       return;
1030     }
1031
1032     /*
1033      * get default parameters, and optionally show a dialog
1034      * to allow them to be modified
1035      */
1036     ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1037     List<ArgumentI> args = store.getServiceParameters();
1038
1039     if (!withDefaults)
1040     {
1041       WsParamSetI set = new HMMERPreset();
1042       WsJobParameters params = new WsJobParameters(store, set, args);
1043       if (params.showRunDialog())
1044       {
1045         args = params.getJobParams();
1046       }
1047       else
1048       {
1049         return; // user cancelled
1050       }
1051     }
1052     new Thread(new HMMBuild(this, args)).start();
1053   }
1054
1055   @Override
1056   public void hmmAlign_actionPerformed(boolean withDefaults)
1057   {
1058     if (!(checkForHMM() && alignmentIsSufficient(2)))
1059     {
1060       return;
1061     }
1062
1063     /*
1064      * get default parameters, and optionally show a dialog
1065      * to allow them to be modified
1066      */
1067     ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1068     List<ArgumentI> args = store.getServiceParameters();
1069
1070     if (!withDefaults)
1071     {
1072       WsParamSetI set = new HMMERPreset();
1073       WsJobParameters params = new WsJobParameters(store, set, args);
1074       if (params.showRunDialog())
1075       {
1076         args = params.getJobParams();
1077       }
1078       else
1079       {
1080         return; // user cancelled
1081       }
1082     }
1083     new Thread(new HMMAlign(this, args)).start();
1084   }
1085
1086   @Override
1087   public void hmmSearch_actionPerformed(boolean withDefaults)
1088   {
1089     if (!checkForHMM())
1090     {
1091       return;
1092     }
1093
1094     /*
1095      * get default parameters, and (if requested) show 
1096      * dialog to allow modification
1097      */
1098     ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1099     List<ArgumentI> args = store.getServiceParameters();
1100
1101     if (!withDefaults)
1102     {
1103       WsParamSetI set = new HMMERPreset();
1104       WsJobParameters params = new WsJobParameters(store, set, args);
1105       if (params.showRunDialog())
1106       {
1107         args = params.getJobParams();
1108       }
1109       else
1110       {
1111         return; // user cancelled
1112       }
1113     }
1114     new Thread(new HMMSearch(this, args)).start();
1115     alignPanel.repaint();
1116   }
1117   
1118   @Override
1119   public void jackhmmer_actionPerformed(boolean withDefaults)
1120   {
1121     
1122     /*
1123      * get default parameters, and (if requested) show 
1124      * dialog to allow modification
1125      */
1126     
1127     ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
1128     List<ArgumentI> args = store.getServiceParameters();
1129
1130     if (!withDefaults)
1131     {
1132       WsParamSetI set = new HMMERPreset();
1133       WsJobParameters params = new WsJobParameters(store, set, args);
1134       if (params.showRunDialog())
1135       {
1136         args = params.getJobParams();
1137       }
1138       else
1139       {
1140         return; // user cancelled
1141       }
1142     }
1143     new Thread(new JackHMMER(this, args)).start();
1144     alignPanel.repaint();
1145     
1146   }
1147
1148   /**
1149    * Checks if the alignment has at least one hidden Markov model, if not shows
1150    * a dialog advising to run hmmbuild or load an HMM profile
1151    * 
1152    * @return
1153    */
1154   private boolean checkForHMM()
1155   {
1156     if (viewport.getAlignment().getHmmSequences().isEmpty())
1157     {
1158       JOptionPane.showMessageDialog(this,
1159               MessageManager.getString("warn.no_hmm"));
1160       return false;
1161     }
1162     return true;
1163   }
1164   
1165   @Override
1166   protected void filterByEValue_actionPerformed()
1167   {
1168     viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
1169   }
1170   
1171   @Override
1172   protected void filterByScore_actionPerformed()
1173   {
1174     viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
1175   }
1176   
1177   private double inputDouble(String message)
1178   {
1179     String str = null;
1180     Double d = null;
1181     while(d == null || d <= 0)
1182     {
1183       str = JOptionPane.showInputDialog(this.alignPanel, message);
1184       try
1185       {
1186         d = Double.valueOf(str);
1187       }
1188       catch (NumberFormatException e)
1189       {
1190       }
1191     }
1192     return d;
1193   }
1194
1195   /**
1196    * Checks if the alignment contains the required number of sequences.
1197    * 
1198    * @param required
1199    * @return
1200    */
1201   public boolean alignmentIsSufficient(int required)
1202   {
1203       if (getViewport().getSequenceSelection().length < required)
1204       {
1205         JOptionPane.showMessageDialog(this,
1206                 MessageManager.getString("label.not_enough_sequences"));
1207         return false;
1208       }
1209       return true;
1210   }
1211
1212   /**
1213    * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1214    * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1215    * comma-separated list)
1216    */
1217   @Override
1218   public void addDatabase_actionPerformed() throws IOException
1219   {
1220     if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1221     {
1222       Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1223     }
1224
1225     String path = openFileChooser(false);
1226     if (path != null && new File(path).exists())
1227     {
1228       IdentifyFile identifier = new IdentifyFile();
1229       FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1230       if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1231               || format == FileFormat.Pfam)
1232       {
1233         String currentDbPaths = Cache
1234                 .getProperty(Preferences.HMMSEARCH_DBS);
1235         currentDbPaths += Preferences.COMMA + path;
1236         Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1237       }
1238       else
1239       {
1240         JOptionPane.showMessageDialog(this,
1241                 MessageManager.getString("warn.invalid_format"));
1242       }
1243     }
1244   }
1245
1246   /**
1247    * Opens a file chooser, optionally restricted to selecting folders
1248    * (directories) only. Answers the path to the selected file or folder, or
1249    * null if none is chosen.
1250    * 
1251    * @param
1252    * @return
1253    */
1254   protected String openFileChooser(boolean forFolder)
1255   {
1256     // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1257     String choice = null;
1258     JFileChooser chooser = new JFileChooser();
1259     if (forFolder)
1260     {
1261       chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1262     }
1263     chooser.setDialogTitle(
1264             MessageManager.getString("label.open_local_file"));
1265     chooser.setToolTipText(MessageManager.getString("action.open"));
1266
1267     int value = chooser.showOpenDialog(this);
1268
1269     if (value == JFileChooser.APPROVE_OPTION)
1270     {
1271       choice = chooser.getSelectedFile().getPath();
1272     }
1273     return choice;
1274   }
1275
1276   @Override
1277   public void reload_actionPerformed(ActionEvent e)
1278   {
1279     if (fileName != null)
1280     {
1281       // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1282       // originating file's format
1283       // TODO: work out how to recover feature settings for correct view(s) when
1284       // file is reloaded.
1285       if (FileFormat.Jalview.equals(currentFileFormat))
1286       {
1287         JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1288         for (int i = 0; i < frames.length; i++)
1289         {
1290           if (frames[i] instanceof AlignFrame && frames[i] != this
1291                   && ((AlignFrame) frames[i]).fileName != null
1292                   && ((AlignFrame) frames[i]).fileName.equals(fileName))
1293           {
1294             try
1295             {
1296               frames[i].setSelected(true);
1297               Desktop.instance.closeAssociatedWindows();
1298             } catch (java.beans.PropertyVetoException ex)
1299             {
1300             }
1301           }
1302
1303         }
1304         Desktop.instance.closeAssociatedWindows();
1305
1306         FileLoader loader = new FileLoader();
1307         DataSourceType protocol = fileName.startsWith("http:")
1308                 ? DataSourceType.URL
1309                 : DataSourceType.FILE;
1310         loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1311       }
1312       else
1313       {
1314         Rectangle bounds = this.getBounds();
1315
1316         FileLoader loader = new FileLoader();
1317         DataSourceType protocol = fileName.startsWith("http:")
1318                 ? DataSourceType.URL
1319                 : DataSourceType.FILE;
1320         AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1321                 protocol, currentFileFormat);
1322
1323         newframe.setBounds(bounds);
1324         if (featureSettings != null && featureSettings.isShowing())
1325         {
1326           final Rectangle fspos = featureSettings.frame.getBounds();
1327           // TODO: need a 'show feature settings' function that takes bounds -
1328           // need to refactor Desktop.addFrame
1329           newframe.featureSettings_actionPerformed(null);
1330           final FeatureSettings nfs = newframe.featureSettings;
1331           SwingUtilities.invokeLater(new Runnable()
1332           {
1333             @Override
1334             public void run()
1335             {
1336               nfs.frame.setBounds(fspos);
1337             }
1338           });
1339           this.featureSettings.close();
1340           this.featureSettings = null;
1341         }
1342         this.closeMenuItem_actionPerformed(true);
1343       }
1344     }
1345   }
1346
1347   @Override
1348   public void addFromText_actionPerformed(ActionEvent e)
1349   {
1350     Desktop.instance
1351             .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1352   }
1353
1354   @Override
1355   public void addFromURL_actionPerformed(ActionEvent e)
1356   {
1357     Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1358   }
1359
1360   @Override
1361   public void save_actionPerformed(ActionEvent e)
1362   {
1363     if (fileName == null || (currentFileFormat == null)
1364             || fileName.startsWith("http"))
1365     {
1366       saveAs_actionPerformed(null);
1367     }
1368     else
1369     {
1370       saveAlignment(fileName, currentFileFormat);
1371     }
1372   }
1373
1374   /**
1375    * DOCUMENT ME!
1376    * 
1377    * @param e
1378    *          DOCUMENT ME!
1379    */
1380   @Override
1381   public void saveAs_actionPerformed(ActionEvent e)
1382   {
1383     String format = currentFileFormat == null ? null
1384             : currentFileFormat.getName();
1385     JalviewFileChooser chooser = JalviewFileChooser
1386             .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1387
1388     chooser.setFileView(new JalviewFileView());
1389     chooser.setDialogTitle(
1390             MessageManager.getString("label.save_alignment_to_file"));
1391     chooser.setToolTipText(MessageManager.getString("action.save"));
1392
1393     int value = chooser.showSaveDialog(this);
1394
1395     if (value == JalviewFileChooser.APPROVE_OPTION)
1396     {
1397       currentFileFormat = chooser.getSelectedFormat();
1398       while (currentFileFormat == null)
1399       {
1400         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1401                 MessageManager.getString(
1402                         "label.select_file_format_before_saving"),
1403                 MessageManager.getString("label.file_format_not_specified"),
1404                 JvOptionPane.WARNING_MESSAGE);
1405         currentFileFormat = chooser.getSelectedFormat();
1406         value = chooser.showSaveDialog(this);
1407         if (value != JalviewFileChooser.APPROVE_OPTION)
1408         {
1409           return;
1410         }
1411       }
1412
1413       fileName = chooser.getSelectedFile().getPath();
1414
1415       Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1416
1417       Cache.setProperty("LAST_DIRECTORY", fileName);
1418       saveAlignment(fileName, currentFileFormat);
1419     }
1420   }
1421
1422   public boolean saveAlignment(String file, FileFormatI format)
1423   {
1424     boolean success = true;
1425
1426     if (FileFormat.Jalview.equals(format))
1427     {
1428       String shortName = title;
1429
1430       if (shortName.indexOf(java.io.File.separatorChar) > -1)
1431       {
1432         shortName = shortName.substring(
1433                 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1434       }
1435
1436       success = new jalview.project.Jalview2XML().saveAlignment(this, file,
1437               shortName);
1438
1439       statusBar.setText(MessageManager.formatMessage(
1440               "label.successfully_saved_to_file_in_format", new Object[]
1441               { fileName, format }));
1442
1443     }
1444     else
1445     {
1446       AlignmentExportData exportData = getAlignmentForExport(format,
1447               viewport, null);
1448       if (exportData.getSettings().isCancelled())
1449       {
1450         return false;
1451       }
1452       FormatAdapter f = new FormatAdapter(alignPanel,
1453               exportData.getSettings());
1454       String output = f.formatSequences(format, exportData.getAlignment(), // class
1455                                                                            // cast
1456                                                                            // exceptions
1457                                                                            // will
1458               // occur in the distant future
1459               exportData.getOmitHidden(), exportData.getStartEndPostions(),
1460               f.getCacheSuffixDefault(format),
1461               viewport.getAlignment().getHiddenColumns());
1462
1463       if (output == null)
1464       {
1465         success = false;
1466       }
1467       else
1468       {
1469         // create backupfiles object and get new temp filename destination
1470         BackupFiles backupfiles = new BackupFiles(file);
1471
1472         try
1473         {
1474           PrintWriter out = new PrintWriter(
1475                   new FileWriter(backupfiles.getTempFilePath()));
1476
1477           out.print(output);
1478           out.close();
1479           this.setTitle(file);
1480           statusBar.setText(MessageManager.formatMessage(
1481                   "label.successfully_saved_to_file_in_format", new Object[]
1482                   { fileName, format.getName() }));
1483         } catch (Exception ex)
1484         {
1485           success = false;
1486           ex.printStackTrace();
1487         }
1488
1489         backupfiles.setWriteSuccess(success);
1490         // do the backup file roll and rename the temp file to actual file
1491         success = backupfiles.rollBackupsAndRenameTempFile();
1492
1493       }
1494     }
1495
1496     if (!success)
1497     {
1498       JvOptionPane.showInternalMessageDialog(this, MessageManager
1499               .formatMessage("label.couldnt_save_file", new Object[]
1500               { fileName }),
1501               MessageManager.getString("label.error_saving_file"),
1502               JvOptionPane.WARNING_MESSAGE);
1503     }
1504
1505     return success;
1506   }
1507
1508   private void warningMessage(String warning, String title)
1509   {
1510     if (new jalview.util.Platform().isHeadless())
1511     {
1512       System.err.println("Warning: " + title + "\nWarning: " + warning);
1513
1514     }
1515     else
1516     {
1517       JvOptionPane.showInternalMessageDialog(this, warning, title,
1518               JvOptionPane.WARNING_MESSAGE);
1519     }
1520     return;
1521   }
1522
1523   /**
1524    * DOCUMENT ME!
1525    * 
1526    * @param e
1527    *          DOCUMENT ME!
1528    */
1529   @Override
1530   protected void outputText_actionPerformed(ActionEvent e)
1531   {
1532     FileFormatI fileFormat = FileFormats.getInstance()
1533             .forName(e.getActionCommand());
1534     AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1535             viewport, null);
1536     if (exportData.getSettings().isCancelled())
1537     {
1538       return;
1539     }
1540     CutAndPasteTransfer cap = new CutAndPasteTransfer();
1541     cap.setForInput(null);
1542     try
1543     {
1544       FileFormatI format = fileFormat;
1545       cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1546               .formatSequences(format, exportData.getAlignment(),
1547                       exportData.getOmitHidden(),
1548                       exportData.getStartEndPostions(),
1549                       viewport.getAlignment().getHiddenColumns()));
1550       Desktop.addInternalFrame(cap, MessageManager
1551               .formatMessage("label.alignment_output_command", new Object[]
1552               { e.getActionCommand() }), 600, 500);
1553     } catch (OutOfMemoryError oom)
1554     {
1555       new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1556               oom);
1557       cap.dispose();
1558     }
1559
1560   }
1561
1562   public static AlignmentExportData getAlignmentForExport(
1563           FileFormatI format, AlignViewportI viewport,
1564           AlignExportSettingI exportSettings)
1565   {
1566     AlignmentI alignmentToExport = null;
1567     AlignExportSettingI settings = exportSettings;
1568     String[] omitHidden = null;
1569
1570     HiddenSequences hiddenSeqs = viewport.getAlignment()
1571             .getHiddenSequences();
1572
1573     alignmentToExport = viewport.getAlignment();
1574
1575     boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1576     if (settings == null)
1577     {
1578       settings = new AlignExportSettings(hasHiddenSeqs,
1579               viewport.hasHiddenColumns(), format);
1580     }
1581     // settings.isExportAnnotations();
1582
1583     if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1584     {
1585       omitHidden = viewport.getViewAsString(false,
1586               settings.isExportHiddenSequences());
1587     }
1588
1589     int[] alignmentStartEnd = new int[2];
1590     if (hasHiddenSeqs && settings.isExportHiddenSequences())
1591     {
1592       alignmentToExport = hiddenSeqs.getFullAlignment();
1593     }
1594     else
1595     {
1596       alignmentToExport = viewport.getAlignment();
1597     }
1598     alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1599             .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1600     AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1601             omitHidden, alignmentStartEnd, settings);
1602     return ed;
1603   }
1604
1605   /**
1606    * DOCUMENT ME!
1607    * 
1608    * @param e
1609    *          DOCUMENT ME!
1610    */
1611   @Override
1612   protected void htmlMenuItem_actionPerformed(ActionEvent e)
1613   {
1614     HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1615     htmlSVG.exportHTML(null);
1616   }
1617
1618   @Override
1619   public void bioJSMenuItem_actionPerformed(ActionEvent e)
1620   {
1621     BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1622     bjs.exportHTML(null);
1623   }
1624
1625   public void createImageMap(File file, String image)
1626   {
1627     alignPanel.makePNGImageMap(file, image);
1628   }
1629
1630   /**
1631    * DOCUMENT ME!
1632    * 
1633    * @param e
1634    *          DOCUMENT ME!
1635    */
1636   @Override
1637   public void createPNG(File f)
1638   {
1639     alignPanel.makePNG(f);
1640   }
1641
1642   /**
1643    * DOCUMENT ME!
1644    * 
1645    * @param e
1646    *          DOCUMENT ME!
1647    */
1648   @Override
1649   public void createEPS(File f)
1650   {
1651     alignPanel.makeEPS(f);
1652   }
1653
1654   @Override
1655   public void createSVG(File f)
1656   {
1657     alignPanel.makeSVG(f);
1658   }
1659
1660   @Override
1661   public void pageSetup_actionPerformed(ActionEvent e)
1662   {
1663     PrinterJob printJob = PrinterJob.getPrinterJob();
1664     PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1665   }
1666
1667   /**
1668    * DOCUMENT ME!
1669    * 
1670    * @param e
1671    *          DOCUMENT ME!
1672    */
1673   @Override
1674   public void printMenuItem_actionPerformed(ActionEvent e)
1675   {
1676     // Putting in a thread avoids Swing painting problems
1677     PrintThread thread = new PrintThread(alignPanel);
1678     thread.start();
1679   }
1680
1681   @Override
1682   public void exportFeatures_actionPerformed(ActionEvent e)
1683   {
1684     new AnnotationExporter(alignPanel).exportFeatures();
1685   }
1686
1687   @Override
1688   public void exportAnnotations_actionPerformed(ActionEvent e)
1689   {
1690     new AnnotationExporter(alignPanel).exportAnnotations();
1691   }
1692
1693   @Override
1694   public void associatedData_actionPerformed(ActionEvent e)
1695           throws IOException, InterruptedException
1696   {
1697     // Pick the tree file
1698     JalviewFileChooser chooser = new JalviewFileChooser(
1699             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1700     chooser.setFileView(new JalviewFileView());
1701     chooser.setDialogTitle(
1702             MessageManager.getString("label.load_jalview_annotations"));
1703     chooser.setToolTipText(
1704             MessageManager.getString("label.load_jalview_annotations"));
1705
1706     int value = chooser.showOpenDialog(null);
1707
1708     if (value == JalviewFileChooser.APPROVE_OPTION)
1709     {
1710       String choice = chooser.getSelectedFile().getPath();
1711       jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1712       loadJalviewDataFile(choice, null, null, null);
1713     }
1714
1715   }
1716
1717   /**
1718    * Close the current view or all views in the alignment frame. If the frame
1719    * only contains one view then the alignment will be removed from memory.
1720    * 
1721    * @param closeAllTabs
1722    */
1723   @Override
1724   public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1725   {
1726     if (alignPanels != null && alignPanels.size() < 2)
1727     {
1728       closeAllTabs = true;
1729     }
1730
1731     try
1732     {
1733       if (alignPanels != null)
1734       {
1735         if (closeAllTabs)
1736         {
1737           if (this.isClosed())
1738           {
1739             // really close all the windows - otherwise wait till
1740             // setClosed(true) is called
1741             for (int i = 0; i < alignPanels.size(); i++)
1742             {
1743               AlignmentPanel ap = alignPanels.get(i);
1744               ap.closePanel();
1745             }
1746           }
1747         }
1748         else
1749         {
1750           closeView(alignPanel);
1751         }
1752       }
1753
1754       if (closeAllTabs)
1755       {
1756         /*
1757          * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1758          * be called recursively, with the frame now in 'closed' state
1759          */
1760         this.setClosed(true);
1761       }
1762     } catch (Exception ex)
1763     {
1764       ex.printStackTrace();
1765     }
1766   }
1767
1768   /**
1769    * Close the specified panel and close up tabs appropriately.
1770    * 
1771    * @param panelToClose
1772    */
1773   public void closeView(AlignmentPanel panelToClose)
1774   {
1775     int index = tabbedPane.getSelectedIndex();
1776     int closedindex = tabbedPane.indexOfComponent(panelToClose);
1777     alignPanels.remove(panelToClose);
1778     panelToClose.closePanel();
1779     panelToClose = null;
1780
1781     tabbedPane.removeTabAt(closedindex);
1782     tabbedPane.validate();
1783
1784     if (index > closedindex || index == tabbedPane.getTabCount())
1785     {
1786       // modify currently selected tab index if necessary.
1787       index--;
1788     }
1789
1790     this.tabSelectionChanged(index);
1791   }
1792
1793   /**
1794    * DOCUMENT ME!
1795    */
1796   void updateEditMenuBar()
1797   {
1798
1799     if (viewport.getHistoryList().size() > 0)
1800     {
1801       undoMenuItem.setEnabled(true);
1802       CommandI command = viewport.getHistoryList().peek();
1803       undoMenuItem.setText(MessageManager
1804               .formatMessage("label.undo_command", new Object[]
1805               { command.getDescription() }));
1806     }
1807     else
1808     {
1809       undoMenuItem.setEnabled(false);
1810       undoMenuItem.setText(MessageManager.getString("action.undo"));
1811     }
1812
1813     if (viewport.getRedoList().size() > 0)
1814     {
1815       redoMenuItem.setEnabled(true);
1816
1817       CommandI command = viewport.getRedoList().peek();
1818       redoMenuItem.setText(MessageManager
1819               .formatMessage("label.redo_command", new Object[]
1820               { command.getDescription() }));
1821     }
1822     else
1823     {
1824       redoMenuItem.setEnabled(false);
1825       redoMenuItem.setText(MessageManager.getString("action.redo"));
1826     }
1827   }
1828
1829   @Override
1830   public void addHistoryItem(CommandI command)
1831   {
1832     if (command.getSize() > 0)
1833     {
1834       viewport.addToHistoryList(command);
1835       viewport.clearRedoList();
1836       updateEditMenuBar();
1837       viewport.updateHiddenColumns();
1838       // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1839       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1840       // viewport.getColumnSelection()
1841       // .getHiddenColumns().size() > 0);
1842     }
1843   }
1844
1845   /**
1846    * 
1847    * @return alignment objects for all views
1848    */
1849   AlignmentI[] getViewAlignments()
1850   {
1851     if (alignPanels != null)
1852     {
1853       AlignmentI[] als = new AlignmentI[alignPanels.size()];
1854       int i = 0;
1855       for (AlignmentPanel ap : alignPanels)
1856       {
1857         als[i++] = ap.av.getAlignment();
1858       }
1859       return als;
1860     }
1861     if (viewport != null)
1862     {
1863       return new AlignmentI[] { viewport.getAlignment() };
1864     }
1865     return null;
1866   }
1867
1868   /**
1869    * DOCUMENT ME!
1870    * 
1871    * @param e
1872    *          DOCUMENT ME!
1873    */
1874   @Override
1875   protected void undoMenuItem_actionPerformed(ActionEvent e)
1876   {
1877     if (viewport.getHistoryList().isEmpty())
1878     {
1879       return;
1880     }
1881     CommandI command = viewport.getHistoryList().pop();
1882     viewport.addToRedoList(command);
1883     command.undoCommand(getViewAlignments());
1884
1885     AlignmentViewport originalSource = getOriginatingSource(command);
1886     updateEditMenuBar();
1887
1888     if (originalSource != null)
1889     {
1890       if (originalSource != viewport)
1891       {
1892         Cache.log.warn(
1893                 "Implementation worry: mismatch of viewport origin for undo");
1894       }
1895       originalSource.updateHiddenColumns();
1896       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1897       // null
1898       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1899       // viewport.getColumnSelection()
1900       // .getHiddenColumns().size() > 0);
1901       originalSource.firePropertyChange("alignment", null,
1902               originalSource.getAlignment().getSequences());
1903     }
1904   }
1905
1906   /**
1907    * DOCUMENT ME!
1908    * 
1909    * @param e
1910    *          DOCUMENT ME!
1911    */
1912   @Override
1913   protected void redoMenuItem_actionPerformed(ActionEvent e)
1914   {
1915     if (viewport.getRedoList().size() < 1)
1916     {
1917       return;
1918     }
1919
1920     CommandI command = viewport.getRedoList().pop();
1921     viewport.addToHistoryList(command);
1922     command.doCommand(getViewAlignments());
1923
1924     AlignmentViewport originalSource = getOriginatingSource(command);
1925     updateEditMenuBar();
1926
1927     if (originalSource != null)
1928     {
1929
1930       if (originalSource != viewport)
1931       {
1932         Cache.log.warn(
1933                 "Implementation worry: mismatch of viewport origin for redo");
1934       }
1935       originalSource.updateHiddenColumns();
1936       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1937       // null
1938       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1939       // viewport.getColumnSelection()
1940       // .getHiddenColumns().size() > 0);
1941       originalSource.firePropertyChange("alignment", null,
1942               originalSource.getAlignment().getSequences());
1943     }
1944   }
1945
1946   AlignmentViewport getOriginatingSource(CommandI command)
1947   {
1948     AlignmentViewport originalSource = null;
1949     // For sequence removal and addition, we need to fire
1950     // the property change event FROM the viewport where the
1951     // original alignment was altered
1952     AlignmentI al = null;
1953     if (command instanceof EditCommand)
1954     {
1955       EditCommand editCommand = (EditCommand) command;
1956       al = editCommand.getAlignment();
1957       List<Component> comps = PaintRefresher.components
1958               .get(viewport.getSequenceSetId());
1959
1960       for (Component comp : comps)
1961       {
1962         if (comp instanceof AlignmentPanel)
1963         {
1964           if (al == ((AlignmentPanel) comp).av.getAlignment())
1965           {
1966             originalSource = ((AlignmentPanel) comp).av;
1967             break;
1968           }
1969         }
1970       }
1971     }
1972
1973     if (originalSource == null)
1974     {
1975       // The original view is closed, we must validate
1976       // the current view against the closed view first
1977       if (al != null)
1978       {
1979         PaintRefresher.validateSequences(al, viewport.getAlignment());
1980       }
1981
1982       originalSource = viewport;
1983     }
1984
1985     return originalSource;
1986   }
1987
1988   /**
1989    * DOCUMENT ME!
1990    * 
1991    * @param up
1992    *          DOCUMENT ME!
1993    */
1994   public void moveSelectedSequences(boolean up)
1995   {
1996     SequenceGroup sg = viewport.getSelectionGroup();
1997
1998     if (sg == null)
1999     {
2000       return;
2001     }
2002     viewport.getAlignment().moveSelectedSequencesByOne(sg,
2003             viewport.getHiddenRepSequences(), up);
2004     alignPanel.paintAlignment(true, false);
2005   }
2006
2007   synchronized void slideSequences(boolean right, int size)
2008   {
2009     List<SequenceI> sg = new ArrayList<>();
2010     if (viewport.cursorMode)
2011     {
2012       sg.add(viewport.getAlignment()
2013               .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2014     }
2015     else if (viewport.getSelectionGroup() != null
2016             && viewport.getSelectionGroup().getSize() != viewport
2017                     .getAlignment().getHeight())
2018     {
2019       sg = viewport.getSelectionGroup()
2020               .getSequences(viewport.getHiddenRepSequences());
2021     }
2022
2023     if (sg.size() < 1)
2024     {
2025       return;
2026     }
2027
2028     List<SequenceI> invertGroup = new ArrayList<>();
2029
2030     for (SequenceI seq : viewport.getAlignment().getSequences())
2031     {
2032       if (!sg.contains(seq))
2033       {
2034         invertGroup.add(seq);
2035       }
2036     }
2037
2038     SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2039
2040     SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2041     for (int i = 0; i < invertGroup.size(); i++)
2042     {
2043       seqs2[i] = invertGroup.get(i);
2044     }
2045
2046     SlideSequencesCommand ssc;
2047     if (right)
2048     {
2049       ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2050               viewport.getGapCharacter());
2051     }
2052     else
2053     {
2054       ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2055               viewport.getGapCharacter());
2056     }
2057
2058     int groupAdjustment = 0;
2059     if (ssc.getGapsInsertedBegin() && right)
2060     {
2061       if (viewport.cursorMode)
2062       {
2063         alignPanel.getSeqPanel().moveCursor(size, 0);
2064       }
2065       else
2066       {
2067         groupAdjustment = size;
2068       }
2069     }
2070     else if (!ssc.getGapsInsertedBegin() && !right)
2071     {
2072       if (viewport.cursorMode)
2073       {
2074         alignPanel.getSeqPanel().moveCursor(-size, 0);
2075       }
2076       else
2077       {
2078         groupAdjustment = -size;
2079       }
2080     }
2081
2082     if (groupAdjustment != 0)
2083     {
2084       viewport.getSelectionGroup().setStartRes(
2085               viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2086       viewport.getSelectionGroup().setEndRes(
2087               viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2088     }
2089
2090     /*
2091      * just extend the last slide command if compatible; but not if in
2092      * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2093      */
2094     boolean appendHistoryItem = false;
2095     Deque<CommandI> historyList = viewport.getHistoryList();
2096     boolean inSplitFrame = getSplitViewContainer() != null;
2097     if (!inSplitFrame && historyList != null && historyList.size() > 0
2098             && historyList.peek() instanceof SlideSequencesCommand)
2099     {
2100       appendHistoryItem = ssc.appendSlideCommand(
2101               (SlideSequencesCommand) historyList.peek());
2102     }
2103
2104     if (!appendHistoryItem)
2105     {
2106       addHistoryItem(ssc);
2107     }
2108
2109     repaint();
2110   }
2111
2112   /**
2113    * DOCUMENT ME!
2114    * 
2115    * @param e
2116    *          DOCUMENT ME!
2117    */
2118   @Override
2119   protected void copy_actionPerformed(ActionEvent e)
2120   {
2121     if (viewport.getSelectionGroup() == null)
2122     {
2123       return;
2124     }
2125     // TODO: preserve the ordering of displayed alignment annotation in any
2126     // internal paste (particularly sequence associated annotation)
2127     SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2128     String[] omitHidden = null;
2129
2130     if (viewport.hasHiddenColumns())
2131     {
2132       omitHidden = viewport.getViewAsString(true);
2133     }
2134
2135     String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2136             seqs, omitHidden, null);
2137
2138     StringSelection ss = new StringSelection(output);
2139
2140     try
2141     {
2142       jalview.gui.Desktop.internalCopy = true;
2143       // Its really worth setting the clipboard contents
2144       // to empty before setting the large StringSelection!!
2145       Toolkit.getDefaultToolkit().getSystemClipboard()
2146               .setContents(new StringSelection(""), null);
2147
2148       Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2149               Desktop.instance);
2150     } catch (OutOfMemoryError er)
2151     {
2152       new OOMWarning("copying region", er);
2153       return;
2154     }
2155
2156     HiddenColumns hiddenColumns = null;
2157     if (viewport.hasHiddenColumns())
2158     {
2159       int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2160       int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2161
2162       // create new HiddenColumns object with copy of hidden regions
2163       // between startRes and endRes, offset by startRes
2164       hiddenColumns = new HiddenColumns(
2165               viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2166               hiddenCutoff, hiddenOffset);
2167     }
2168
2169     Desktop.jalviewClipboard = new Object[] { seqs,
2170         viewport.getAlignment().getDataset(), hiddenColumns };
2171     statusBar.setText(MessageManager.formatMessage(
2172             "label.copied_sequences_to_clipboard", new Object[]
2173             { Integer.valueOf(seqs.length).toString() }));
2174   }
2175
2176   /**
2177    * DOCUMENT ME!
2178    * 
2179    * @param e
2180    *          DOCUMENT ME!
2181    * @throws InterruptedException
2182    * @throws IOException
2183    */
2184   @Override
2185   protected void pasteNew_actionPerformed(ActionEvent e)
2186           throws IOException, InterruptedException
2187   {
2188     paste(true);
2189   }
2190
2191   /**
2192    * DOCUMENT ME!
2193    * 
2194    * @param e
2195    *          DOCUMENT ME!
2196    * @throws InterruptedException
2197    * @throws IOException
2198    */
2199   @Override
2200   protected void pasteThis_actionPerformed(ActionEvent e)
2201           throws IOException, InterruptedException
2202   {
2203     paste(false);
2204   }
2205
2206   /**
2207    * Paste contents of Jalview clipboard
2208    * 
2209    * @param newAlignment
2210    *          true to paste to a new alignment, otherwise add to this.
2211    * @throws InterruptedException
2212    * @throws IOException
2213    */
2214   void paste(boolean newAlignment) throws IOException, InterruptedException
2215   {
2216     boolean externalPaste = true;
2217     try
2218     {
2219       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2220       Transferable contents = c.getContents(this);
2221
2222       if (contents == null)
2223       {
2224         return;
2225       }
2226
2227       String str;
2228       FileFormatI format;
2229       try
2230       {
2231         str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2232         if (str.length() < 1)
2233         {
2234           return;
2235         }
2236
2237         format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2238
2239       } catch (OutOfMemoryError er)
2240       {
2241         new OOMWarning("Out of memory pasting sequences!!", er);
2242         return;
2243       }
2244
2245       SequenceI[] sequences;
2246       boolean annotationAdded = false;
2247       AlignmentI alignment = null;
2248
2249       if (Desktop.jalviewClipboard != null)
2250       {
2251         // The clipboard was filled from within Jalview, we must use the
2252         // sequences
2253         // And dataset from the copied alignment
2254         SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2255         // be doubly sure that we create *new* sequence objects.
2256         sequences = new SequenceI[newseq.length];
2257         for (int i = 0; i < newseq.length; i++)
2258         {
2259           sequences[i] = new Sequence(newseq[i]);
2260         }
2261         alignment = new Alignment(sequences);
2262         externalPaste = false;
2263       }
2264       else
2265       {
2266         // parse the clipboard as an alignment.
2267         alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2268                 format);
2269         sequences = alignment.getSequencesArray();
2270       }
2271
2272       int alwidth = 0;
2273       ArrayList<Integer> newGraphGroups = new ArrayList<>();
2274       int fgroup = -1;
2275
2276       if (newAlignment)
2277       {
2278
2279         if (Desktop.jalviewClipboard != null)
2280         {
2281           // dataset is inherited
2282           alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2283         }
2284         else
2285         {
2286           // new dataset is constructed
2287           alignment.setDataset(null);
2288         }
2289         alwidth = alignment.getWidth() + 1;
2290       }
2291       else
2292       {
2293         AlignmentI pastedal = alignment; // preserve pasted alignment object
2294         // Add pasted sequences and dataset into existing alignment.
2295         alignment = viewport.getAlignment();
2296         alwidth = alignment.getWidth() + 1;
2297         // decide if we need to import sequences from an existing dataset
2298         boolean importDs = Desktop.jalviewClipboard != null
2299                 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2300         // importDs==true instructs us to copy over new dataset sequences from
2301         // an existing alignment
2302         Vector newDs = (importDs) ? new Vector() : null; // used to create
2303         // minimum dataset set
2304
2305         for (int i = 0; i < sequences.length; i++)
2306         {
2307           if (importDs)
2308           {
2309             newDs.addElement(null);
2310           }
2311           SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2312           // paste
2313           if (importDs && ds != null)
2314           {
2315             if (!newDs.contains(ds))
2316             {
2317               newDs.setElementAt(ds, i);
2318               ds = new Sequence(ds);
2319               // update with new dataset sequence
2320               sequences[i].setDatasetSequence(ds);
2321             }
2322             else
2323             {
2324               ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2325             }
2326           }
2327           else
2328           {
2329             // copy and derive new dataset sequence
2330             sequences[i] = sequences[i].deriveSequence();
2331             alignment.getDataset()
2332                     .addSequence(sequences[i].getDatasetSequence());
2333             // TODO: avoid creation of duplicate dataset sequences with a
2334             // 'contains' method using SequenceI.equals()/SequenceI.contains()
2335           }
2336           alignment.addSequence(sequences[i]); // merges dataset
2337         }
2338         if (newDs != null)
2339         {
2340           newDs.clear(); // tidy up
2341         }
2342         if (alignment.getAlignmentAnnotation() != null)
2343         {
2344           for (AlignmentAnnotation alan : alignment
2345                   .getAlignmentAnnotation())
2346           {
2347             if (alan.graphGroup > fgroup)
2348             {
2349               fgroup = alan.graphGroup;
2350             }
2351           }
2352         }
2353         if (pastedal.getAlignmentAnnotation() != null)
2354         {
2355           // Add any annotation attached to alignment.
2356           AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2357           for (int i = 0; i < alann.length; i++)
2358           {
2359             annotationAdded = true;
2360             if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2361             {
2362               AlignmentAnnotation newann = new AlignmentAnnotation(
2363                       alann[i]);
2364               if (newann.graphGroup > -1)
2365               {
2366                 if (newGraphGroups.size() <= newann.graphGroup
2367                         || newGraphGroups.get(newann.graphGroup) == null)
2368                 {
2369                   for (int q = newGraphGroups
2370                           .size(); q <= newann.graphGroup; q++)
2371                   {
2372                     newGraphGroups.add(q, null);
2373                   }
2374                   newGraphGroups.set(newann.graphGroup,
2375                           Integer.valueOf(++fgroup));
2376                 }
2377                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2378                         .intValue();
2379               }
2380
2381               newann.padAnnotation(alwidth);
2382               alignment.addAnnotation(newann);
2383             }
2384           }
2385         }
2386       }
2387       if (!newAlignment)
2388       {
2389         // /////
2390         // ADD HISTORY ITEM
2391         //
2392         addHistoryItem(new EditCommand(
2393                 MessageManager.getString("label.add_sequences"),
2394                 Action.PASTE, sequences, 0, alignment.getWidth(),
2395                 alignment));
2396       }
2397       // Add any annotations attached to sequences
2398       for (int i = 0; i < sequences.length; i++)
2399       {
2400         if (sequences[i].getAnnotation() != null)
2401         {
2402           AlignmentAnnotation newann;
2403           for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2404           {
2405             annotationAdded = true;
2406             newann = sequences[i].getAnnotation()[a];
2407             newann.adjustForAlignment();
2408             newann.padAnnotation(alwidth);
2409             if (newann.graphGroup > -1)
2410             {
2411               if (newann.graphGroup > -1)
2412               {
2413                 if (newGraphGroups.size() <= newann.graphGroup
2414                         || newGraphGroups.get(newann.graphGroup) == null)
2415                 {
2416                   for (int q = newGraphGroups
2417                           .size(); q <= newann.graphGroup; q++)
2418                   {
2419                     newGraphGroups.add(q, null);
2420                   }
2421                   newGraphGroups.set(newann.graphGroup,
2422                           Integer.valueOf(++fgroup));
2423                 }
2424                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2425                         .intValue();
2426               }
2427             }
2428             alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2429             // was
2430             // duplicated
2431             // earlier
2432             alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2433                     a);
2434           }
2435         }
2436       }
2437       if (!newAlignment)
2438       {
2439
2440         // propagate alignment changed.
2441         viewport.getRanges().setEndSeq(alignment.getHeight());
2442         if (annotationAdded)
2443         {
2444           // Duplicate sequence annotation in all views.
2445           AlignmentI[] alview = this.getViewAlignments();
2446           for (int i = 0; i < sequences.length; i++)
2447           {
2448             AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2449             if (sann == null)
2450             {
2451               continue;
2452             }
2453             for (int avnum = 0; avnum < alview.length; avnum++)
2454             {
2455               if (alview[avnum] != alignment)
2456               {
2457                 // duplicate in a view other than the one with input focus
2458                 int avwidth = alview[avnum].getWidth() + 1;
2459                 // this relies on sann being preserved after we
2460                 // modify the sequence's annotation array for each duplication
2461                 for (int a = 0; a < sann.length; a++)
2462                 {
2463                   AlignmentAnnotation newann = new AlignmentAnnotation(
2464                           sann[a]);
2465                   sequences[i].addAlignmentAnnotation(newann);
2466                   newann.padAnnotation(avwidth);
2467                   alview[avnum].addAnnotation(newann); // annotation was
2468                   // duplicated earlier
2469                   // TODO JAL-1145 graphGroups are not updated for sequence
2470                   // annotation added to several views. This may cause
2471                   // strangeness
2472                   alview[avnum].setAnnotationIndex(newann, a);
2473                 }
2474               }
2475             }
2476           }
2477           buildSortByAnnotationScoresMenu();
2478         }
2479         viewport.firePropertyChange("alignment", null,
2480                 alignment.getSequences());
2481         if (alignPanels != null)
2482         {
2483           for (AlignmentPanel ap : alignPanels)
2484           {
2485             ap.validateAnnotationDimensions(false);
2486           }
2487         }
2488         else
2489         {
2490           alignPanel.validateAnnotationDimensions(false);
2491         }
2492
2493       }
2494       else
2495       {
2496         AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2497                 DEFAULT_HEIGHT);
2498         String newtitle = new String("Copied sequences");
2499
2500         if (Desktop.jalviewClipboard != null
2501                 && Desktop.jalviewClipboard[2] != null)
2502         {
2503           HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2504           af.viewport.setHiddenColumns(hc);
2505         }
2506
2507         // >>>This is a fix for the moment, until a better solution is
2508         // found!!<<<
2509         af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2510                 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2511                         .getFeatureRenderer());
2512
2513         // TODO: maintain provenance of an alignment, rather than just make the
2514         // title a concatenation of operations.
2515         if (!externalPaste)
2516         {
2517           if (title.startsWith("Copied sequences"))
2518           {
2519             newtitle = title;
2520           }
2521           else
2522           {
2523             newtitle = newtitle.concat("- from " + title);
2524           }
2525         }
2526         else
2527         {
2528           newtitle = new String("Pasted sequences");
2529         }
2530
2531         Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2532                 DEFAULT_HEIGHT);
2533
2534       }
2535
2536     } catch (Exception ex)
2537     {
2538       ex.printStackTrace();
2539       System.out.println("Exception whilst pasting: " + ex);
2540       // could be anything being pasted in here
2541     }
2542   }
2543
2544   @Override
2545   protected void expand_newalign(ActionEvent e)
2546   {
2547     try
2548     {
2549       AlignmentI alignment = AlignmentUtils
2550               .expandContext(getViewport().getAlignment(), -1);
2551       AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2552               DEFAULT_HEIGHT);
2553       String newtitle = new String("Flanking alignment");
2554
2555       if (Desktop.jalviewClipboard != null
2556               && Desktop.jalviewClipboard[2] != null)
2557       {
2558         HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2559         af.viewport.setHiddenColumns(hc);
2560       }
2561
2562       // >>>This is a fix for the moment, until a better solution is
2563       // found!!<<<
2564       af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2565               .transferSettings(alignPanel.getSeqPanel().seqCanvas
2566                       .getFeatureRenderer());
2567
2568       // TODO: maintain provenance of an alignment, rather than just make the
2569       // title a concatenation of operations.
2570       {
2571         if (title.startsWith("Copied sequences"))
2572         {
2573           newtitle = title;
2574         }
2575         else
2576         {
2577           newtitle = newtitle.concat("- from " + title);
2578         }
2579       }
2580
2581       Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2582
2583     } catch (Exception ex)
2584     {
2585       ex.printStackTrace();
2586       System.out.println("Exception whilst pasting: " + ex);
2587       // could be anything being pasted in here
2588     } catch (OutOfMemoryError oom)
2589     {
2590       new OOMWarning("Viewing flanking region of alignment", oom);
2591     }
2592   }
2593
2594   /**
2595    * DOCUMENT ME!
2596    * 
2597    * @param e
2598    *          DOCUMENT ME!
2599    */
2600   @Override
2601   protected void cut_actionPerformed(ActionEvent e)
2602   {
2603     copy_actionPerformed(null);
2604     delete_actionPerformed(null);
2605   }
2606
2607   /**
2608    * DOCUMENT ME!
2609    * 
2610    * @param e
2611    *          DOCUMENT ME!
2612    */
2613   @Override
2614   protected void delete_actionPerformed(ActionEvent evt)
2615   {
2616
2617     SequenceGroup sg = viewport.getSelectionGroup();
2618     if (sg == null)
2619     {
2620       return;
2621     }
2622
2623     /*
2624      * If the cut affects all sequences, warn, remove highlighted columns
2625      */
2626     if (sg.getSize() == viewport.getAlignment().getHeight())
2627     {
2628       boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2629               + 1) == viewport.getAlignment().getWidth()) ? true : false;
2630       if (isEntireAlignWidth)
2631       {
2632         int confirm = JvOptionPane.showConfirmDialog(this,
2633                 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2634                 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2635                 JvOptionPane.OK_CANCEL_OPTION);
2636
2637         if (confirm == JvOptionPane.CANCEL_OPTION
2638                 || confirm == JvOptionPane.CLOSED_OPTION)
2639         {
2640           return;
2641         }
2642       }
2643       viewport.getColumnSelection().removeElements(sg.getStartRes(),
2644               sg.getEndRes() + 1);
2645     }
2646     SequenceI[] cut = sg.getSequences()
2647             .toArray(new SequenceI[sg.getSize()]);
2648
2649     addHistoryItem(new EditCommand(
2650             MessageManager.getString("label.cut_sequences"), Action.CUT,
2651             cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2652             viewport.getAlignment()));
2653
2654     viewport.setSelectionGroup(null);
2655     viewport.sendSelection();
2656     viewport.getAlignment().deleteGroup(sg);
2657
2658     viewport.firePropertyChange("alignment", null,
2659             viewport.getAlignment().getSequences());
2660     if (viewport.getAlignment().getHeight() < 1)
2661     {
2662       try
2663       {
2664         this.setClosed(true);
2665       } catch (Exception ex)
2666       {
2667       }
2668     }
2669   }
2670
2671   /**
2672    * DOCUMENT ME!
2673    * 
2674    * @param e
2675    *          DOCUMENT ME!
2676    */
2677   @Override
2678   protected void deleteGroups_actionPerformed(ActionEvent e)
2679   {
2680     if (avc.deleteGroups())
2681     {
2682       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2683       alignPanel.updateAnnotation();
2684       alignPanel.paintAlignment(true, true);
2685     }
2686   }
2687
2688   /**
2689    * DOCUMENT ME!
2690    * 
2691    * @param e
2692    *          DOCUMENT ME!
2693    */
2694   @Override
2695   public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2696   {
2697     SequenceGroup sg = new SequenceGroup(
2698             viewport.getAlignment().getSequences());
2699
2700     sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2701     viewport.setSelectionGroup(sg);
2702     viewport.isSelectionGroupChanged(true);
2703     viewport.sendSelection();
2704     // JAL-2034 - should delegate to
2705     // alignPanel to decide if overview needs
2706     // updating.
2707     alignPanel.paintAlignment(false, false);
2708     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2709   }
2710
2711   /**
2712    * DOCUMENT ME!
2713    * 
2714    * @param e
2715    *          DOCUMENT ME!
2716    */
2717   @Override
2718   public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2719   {
2720     if (viewport.cursorMode)
2721     {
2722       alignPanel.getSeqPanel().keyboardNo1 = null;
2723       alignPanel.getSeqPanel().keyboardNo2 = null;
2724     }
2725     viewport.setSelectionGroup(null);
2726     viewport.getColumnSelection().clear();
2727     viewport.setSelectionGroup(null);
2728     alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2729     // JAL-2034 - should delegate to
2730     // alignPanel to decide if overview needs
2731     // updating.
2732     alignPanel.paintAlignment(false, false);
2733     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2734     viewport.sendSelection();
2735   }
2736
2737   /**
2738    * DOCUMENT ME!
2739    * 
2740    * @param e
2741    *          DOCUMENT ME!
2742    */
2743   @Override
2744   public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2745   {
2746     SequenceGroup sg = viewport.getSelectionGroup();
2747
2748     if (sg == null)
2749     {
2750       selectAllSequenceMenuItem_actionPerformed(null);
2751
2752       return;
2753     }
2754
2755     for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2756     {
2757       sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2758     }
2759     // JAL-2034 - should delegate to
2760     // alignPanel to decide if overview needs
2761     // updating.
2762
2763     alignPanel.paintAlignment(true, false);
2764     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2765     viewport.sendSelection();
2766   }
2767
2768   @Override
2769   public void invertColSel_actionPerformed(ActionEvent e)
2770   {
2771     viewport.invertColumnSelection();
2772     alignPanel.paintAlignment(true, false);
2773     viewport.sendSelection();
2774   }
2775
2776   /**
2777    * DOCUMENT ME!
2778    * 
2779    * @param e
2780    *          DOCUMENT ME!
2781    */
2782   @Override
2783   public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2784   {
2785     trimAlignment(true);
2786   }
2787
2788   /**
2789    * DOCUMENT ME!
2790    * 
2791    * @param e
2792    *          DOCUMENT ME!
2793    */
2794   @Override
2795   public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2796   {
2797     trimAlignment(false);
2798   }
2799
2800   void trimAlignment(boolean trimLeft)
2801   {
2802     ColumnSelection colSel = viewport.getColumnSelection();
2803     int column;
2804
2805     if (!colSel.isEmpty())
2806     {
2807       if (trimLeft)
2808       {
2809         column = colSel.getMin();
2810       }
2811       else
2812       {
2813         column = colSel.getMax();
2814       }
2815
2816       SequenceI[] seqs;
2817       if (viewport.getSelectionGroup() != null)
2818       {
2819         seqs = viewport.getSelectionGroup()
2820                 .getSequencesAsArray(viewport.getHiddenRepSequences());
2821       }
2822       else
2823       {
2824         seqs = viewport.getAlignment().getSequencesArray();
2825       }
2826
2827       TrimRegionCommand trimRegion;
2828       if (trimLeft)
2829       {
2830         trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2831                 column, viewport.getAlignment());
2832         viewport.getRanges().setStartRes(0);
2833       }
2834       else
2835       {
2836         trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2837                 column, viewport.getAlignment());
2838       }
2839
2840       statusBar.setText(MessageManager
2841               .formatMessage("label.removed_columns", new String[]
2842               { Integer.valueOf(trimRegion.getSize()).toString() }));
2843
2844       addHistoryItem(trimRegion);
2845
2846       for (SequenceGroup sg : viewport.getAlignment().getGroups())
2847       {
2848         if ((trimLeft && !sg.adjustForRemoveLeft(column))
2849                 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2850         {
2851           viewport.getAlignment().deleteGroup(sg);
2852         }
2853       }
2854
2855       viewport.firePropertyChange("alignment", null,
2856               viewport.getAlignment().getSequences());
2857     }
2858   }
2859
2860   /**
2861    * DOCUMENT ME!
2862    * 
2863    * @param e
2864    *          DOCUMENT ME!
2865    */
2866   @Override
2867   public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2868   {
2869     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2870
2871     SequenceI[] seqs;
2872     if (viewport.getSelectionGroup() != null)
2873     {
2874       seqs = viewport.getSelectionGroup()
2875               .getSequencesAsArray(viewport.getHiddenRepSequences());
2876       start = viewport.getSelectionGroup().getStartRes();
2877       end = viewport.getSelectionGroup().getEndRes();
2878     }
2879     else
2880     {
2881       seqs = viewport.getAlignment().getSequencesArray();
2882     }
2883
2884     RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2885             "Remove Gapped Columns", seqs, start, end,
2886             viewport.getAlignment());
2887
2888     addHistoryItem(removeGapCols);
2889
2890     statusBar.setText(MessageManager
2891             .formatMessage("label.removed_empty_columns", new Object[]
2892             { Integer.valueOf(removeGapCols.getSize()).toString() }));
2893
2894     // This is to maintain viewport position on first residue
2895     // of first sequence
2896     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2897     ViewportRanges ranges = viewport.getRanges();
2898     int startRes = seq.findPosition(ranges.getStartRes());
2899     // ShiftList shifts;
2900     // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2901     // edit.alColumnChanges=shifts.getInverse();
2902     // if (viewport.hasHiddenColumns)
2903     // viewport.getColumnSelection().compensateForEdits(shifts);
2904     ranges.setStartRes(seq.findIndex(startRes) - 1);
2905     viewport.firePropertyChange("alignment", null,
2906             viewport.getAlignment().getSequences());
2907
2908   }
2909
2910   /**
2911    * DOCUMENT ME!
2912    * 
2913    * @param e
2914    *          DOCUMENT ME!
2915    */
2916   @Override
2917   public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2918   {
2919     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2920
2921     SequenceI[] seqs;
2922     if (viewport.getSelectionGroup() != null)
2923     {
2924       seqs = viewport.getSelectionGroup()
2925               .getSequencesAsArray(viewport.getHiddenRepSequences());
2926       start = viewport.getSelectionGroup().getStartRes();
2927       end = viewport.getSelectionGroup().getEndRes();
2928     }
2929     else
2930     {
2931       seqs = viewport.getAlignment().getSequencesArray();
2932     }
2933
2934     // This is to maintain viewport position on first residue
2935     // of first sequence
2936     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2937     int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2938
2939     addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2940             viewport.getAlignment()));
2941
2942     viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2943
2944     viewport.firePropertyChange("alignment", null,
2945             viewport.getAlignment().getSequences());
2946
2947   }
2948
2949   /**
2950    * DOCUMENT ME!
2951    * 
2952    * @param e
2953    *          DOCUMENT ME!
2954    */
2955   @Override
2956   public void padGapsMenuitem_actionPerformed(ActionEvent e)
2957   {
2958     viewport.setPadGaps(padGapsMenuitem.isSelected());
2959     viewport.firePropertyChange("alignment", null,
2960             viewport.getAlignment().getSequences());
2961   }
2962
2963   /**
2964    * DOCUMENT ME!
2965    * 
2966    * @param e
2967    *          DOCUMENT ME!
2968    */
2969   @Override
2970   public void findMenuItem_actionPerformed(ActionEvent e)
2971   {
2972     new Finder();
2973   }
2974
2975   /**
2976    * Create a new view of the current alignment.
2977    */
2978   @Override
2979   public void newView_actionPerformed(ActionEvent e)
2980   {
2981     newView(null, true);
2982   }
2983
2984   /**
2985    * Creates and shows a new view of the current alignment.
2986    * 
2987    * @param viewTitle
2988    *          title of newly created view; if null, one will be generated
2989    * @param copyAnnotation
2990    *          if true then duplicate all annnotation, groups and settings
2991    * @return new alignment panel, already displayed.
2992    */
2993   public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2994   {
2995     /*
2996      * Create a new AlignmentPanel (with its own, new Viewport)
2997      */
2998     AlignmentPanel newap = new jalview.project.Jalview2XML()
2999             .copyAlignPanel(alignPanel);
3000     if (!copyAnnotation)
3001     {
3002       /*
3003        * remove all groups and annotation except for the automatic stuff
3004        */
3005       newap.av.getAlignment().deleteAllGroups();
3006       newap.av.getAlignment().deleteAllAnnotations(false);
3007     }
3008
3009     newap.av.setGatherViewsHere(false);
3010
3011     if (viewport.getViewName() == null)
3012     {
3013       viewport.setViewName(MessageManager
3014               .getString("label.view_name_original"));
3015     }
3016
3017     /*
3018      * Views share the same edits undo and redo stacks
3019      */
3020     newap.av.setHistoryList(viewport.getHistoryList());
3021     newap.av.setRedoList(viewport.getRedoList());
3022
3023     /*
3024      * copy any visualisation settings that are not saved in the project
3025      */
3026     newap.av.setColourAppliesToAllGroups(
3027             viewport.getColourAppliesToAllGroups());
3028
3029     /*
3030      * Views share the same mappings; need to deregister any new mappings
3031      * created by copyAlignPanel, and register the new reference to the shared
3032      * mappings
3033      */
3034     newap.av.replaceMappings(viewport.getAlignment());
3035
3036     /*
3037      * start up cDNA consensus (if applicable) now mappings are in place
3038      */
3039     if (newap.av.initComplementConsensus())
3040     {
3041       newap.refresh(true); // adjust layout of annotations
3042     }
3043
3044     newap.av.setViewName(getNewViewName(viewTitle));
3045
3046     addAlignmentPanel(newap, true);
3047     newap.alignmentChanged();
3048
3049     if (alignPanels.size() == 2)
3050     {
3051       viewport.setGatherViewsHere(true);
3052     }
3053     tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3054     return newap;
3055   }
3056
3057   /**
3058    * Make a new name for the view, ensuring it is unique within the current
3059    * sequenceSetId. (This used to be essential for Jalview Project archives, but
3060    * these now use viewId. Unique view names are still desirable for usability.)
3061    * 
3062    * @param viewTitle
3063    * @return
3064    */
3065   protected String getNewViewName(String viewTitle)
3066   {
3067     int index = Desktop.getViewCount(viewport.getSequenceSetId());
3068     boolean addFirstIndex = false;
3069     if (viewTitle == null || viewTitle.trim().length() == 0)
3070     {
3071       viewTitle = MessageManager.getString("action.view");
3072       addFirstIndex = true;
3073     }
3074     else
3075     {
3076       index = 1;// we count from 1 if given a specific name
3077     }
3078     String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3079
3080     List<Component> comps = PaintRefresher.components
3081             .get(viewport.getSequenceSetId());
3082
3083     List<String> existingNames = getExistingViewNames(comps);
3084
3085     while (existingNames.contains(newViewName))
3086     {
3087       newViewName = viewTitle + " " + (++index);
3088     }
3089     return newViewName;
3090   }
3091
3092   /**
3093    * Returns a list of distinct view names found in the given list of
3094    * components. View names are held on the viewport of an AlignmentPanel.
3095    * 
3096    * @param comps
3097    * @return
3098    */
3099   protected List<String> getExistingViewNames(List<Component> comps)
3100   {
3101     List<String> existingNames = new ArrayList<>();
3102     for (Component comp : comps)
3103     {
3104       if (comp instanceof AlignmentPanel)
3105       {
3106         AlignmentPanel ap = (AlignmentPanel) comp;
3107         if (!existingNames.contains(ap.av.getViewName()))
3108         {
3109           existingNames.add(ap.av.getViewName());
3110         }
3111       }
3112     }
3113     return existingNames;
3114   }
3115
3116   /**
3117    * Explode tabbed views into separate windows.
3118    */
3119   @Override
3120   public void expandViews_actionPerformed(ActionEvent e)
3121   {
3122     Desktop.explodeViews(this);
3123   }
3124
3125   /**
3126    * Gather views in separate windows back into a tabbed presentation.
3127    */
3128   @Override
3129   public void gatherViews_actionPerformed(ActionEvent e)
3130   {
3131     Desktop.instance.gatherViews(this);
3132   }
3133
3134   /**
3135    * DOCUMENT ME!
3136    * 
3137    * @param e
3138    *          DOCUMENT ME!
3139    */
3140   @Override
3141   public void font_actionPerformed(ActionEvent e)
3142   {
3143     new FontChooser(alignPanel);
3144   }
3145
3146   /**
3147    * DOCUMENT ME!
3148    * 
3149    * @param e
3150    *          DOCUMENT ME!
3151    */
3152   @Override
3153   protected void seqLimit_actionPerformed(ActionEvent e)
3154   {
3155     viewport.setShowJVSuffix(seqLimits.isSelected());
3156
3157     alignPanel.getIdPanel().getIdCanvas()
3158             .setPreferredSize(alignPanel.calculateIdWidth());
3159     alignPanel.paintAlignment(true, false);
3160   }
3161
3162   @Override
3163   public void idRightAlign_actionPerformed(ActionEvent e)
3164   {
3165     viewport.setRightAlignIds(idRightAlign.isSelected());
3166     alignPanel.paintAlignment(false, false);
3167   }
3168
3169   @Override
3170   public void centreColumnLabels_actionPerformed(ActionEvent e)
3171   {
3172     viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3173     alignPanel.paintAlignment(false, false);
3174   }
3175
3176   /*
3177    * (non-Javadoc)
3178    * 
3179    * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3180    */
3181   @Override
3182   protected void followHighlight_actionPerformed()
3183   {
3184     /*
3185      * Set the 'follow' flag on the Viewport (and scroll to position if now
3186      * true).
3187      */
3188     final boolean state = this.followHighlightMenuItem.getState();
3189     viewport.setFollowHighlight(state);
3190     if (state)
3191     {
3192       alignPanel.scrollToPosition(viewport.getSearchResults());
3193     }
3194   }
3195
3196   /**
3197    * DOCUMENT ME!
3198    * 
3199    * @param e
3200    *          DOCUMENT ME!
3201    */
3202   @Override
3203   protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3204   {
3205     viewport.setColourText(colourTextMenuItem.isSelected());
3206     alignPanel.paintAlignment(false, false);
3207   }
3208
3209   /**
3210    * DOCUMENT ME!
3211    * 
3212    * @param e
3213    *          DOCUMENT ME!
3214    */
3215   @Override
3216   public void wrapMenuItem_actionPerformed(ActionEvent e)
3217   {
3218     scaleAbove.setVisible(wrapMenuItem.isSelected());
3219     scaleLeft.setVisible(wrapMenuItem.isSelected());
3220     scaleRight.setVisible(wrapMenuItem.isSelected());
3221     viewport.setWrapAlignment(wrapMenuItem.isSelected());
3222     alignPanel.updateLayout();
3223   }
3224
3225   @Override
3226   public void showAllSeqs_actionPerformed(ActionEvent e)
3227   {
3228     viewport.showAllHiddenSeqs();
3229   }
3230
3231   @Override
3232   public void showAllColumns_actionPerformed(ActionEvent e)
3233   {
3234     viewport.showAllHiddenColumns();
3235     alignPanel.paintAlignment(true, true);
3236     viewport.sendSelection();
3237   }
3238
3239   @Override
3240   public void hideSelSequences_actionPerformed(ActionEvent e)
3241   {
3242     viewport.hideAllSelectedSeqs();
3243   }
3244
3245   /**
3246    * called by key handler and the hide all/show all menu items
3247    * 
3248    * @param toggleSeqs
3249    * @param toggleCols
3250    */
3251   private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3252   {
3253
3254     boolean hide = false;
3255     SequenceGroup sg = viewport.getSelectionGroup();
3256     if (!toggleSeqs && !toggleCols)
3257     {
3258       // Hide everything by the current selection - this is a hack - we do the
3259       // invert and then hide
3260       // first check that there will be visible columns after the invert.
3261       if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3262               && sg.getStartRes() <= sg.getEndRes()))
3263       {
3264         // now invert the sequence set, if required - empty selection implies
3265         // that no hiding is required.
3266         if (sg != null)
3267         {
3268           invertSequenceMenuItem_actionPerformed(null);
3269           sg = viewport.getSelectionGroup();
3270           toggleSeqs = true;
3271
3272         }
3273         viewport.expandColSelection(sg, true);
3274         // finally invert the column selection and get the new sequence
3275         // selection.
3276         invertColSel_actionPerformed(null);
3277         toggleCols = true;
3278       }
3279     }
3280
3281     if (toggleSeqs)
3282     {
3283       if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3284       {
3285         hideSelSequences_actionPerformed(null);
3286         hide = true;
3287       }
3288       else if (!(toggleCols && viewport.hasSelectedColumns()))
3289       {
3290         showAllSeqs_actionPerformed(null);
3291       }
3292     }
3293
3294     if (toggleCols)
3295     {
3296       if (viewport.hasSelectedColumns())
3297       {
3298         hideSelColumns_actionPerformed(null);
3299         if (!toggleSeqs)
3300         {
3301           viewport.setSelectionGroup(sg);
3302         }
3303       }
3304       else if (!hide)
3305       {
3306         showAllColumns_actionPerformed(null);
3307       }
3308     }
3309   }
3310
3311   /*
3312    * (non-Javadoc)
3313    * 
3314    * @see
3315    * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3316    * event.ActionEvent)
3317    */
3318   @Override
3319   public void hideAllButSelection_actionPerformed(ActionEvent e)
3320   {
3321     toggleHiddenRegions(false, false);
3322     viewport.sendSelection();
3323   }
3324
3325   /*
3326    * (non-Javadoc)
3327    * 
3328    * @see
3329    * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3330    * .ActionEvent)
3331    */
3332   @Override
3333   public void hideAllSelection_actionPerformed(ActionEvent e)
3334   {
3335     SequenceGroup sg = viewport.getSelectionGroup();
3336     viewport.expandColSelection(sg, false);
3337     viewport.hideAllSelectedSeqs();
3338     viewport.hideSelectedColumns();
3339     alignPanel.updateLayout();
3340     alignPanel.paintAlignment(true, true);
3341     viewport.sendSelection();
3342   }
3343
3344   /*
3345    * (non-Javadoc)
3346    * 
3347    * @see
3348    * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3349    * ActionEvent)
3350    */
3351   @Override
3352   public void showAllhidden_actionPerformed(ActionEvent e)
3353   {
3354     viewport.showAllHiddenColumns();
3355     viewport.showAllHiddenSeqs();
3356     alignPanel.paintAlignment(true, true);
3357     viewport.sendSelection();
3358   }
3359
3360   @Override
3361   public void hideSelColumns_actionPerformed(ActionEvent e)
3362   {
3363     viewport.hideSelectedColumns();
3364     alignPanel.updateLayout();
3365     alignPanel.paintAlignment(true, true);
3366     viewport.sendSelection();
3367   }
3368
3369   @Override
3370   public void hiddenMarkers_actionPerformed(ActionEvent e)
3371   {
3372     viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3373     repaint();
3374   }
3375
3376   /**
3377    * DOCUMENT ME!
3378    * 
3379    * @param e
3380    *          DOCUMENT ME!
3381    */
3382   @Override
3383   protected void scaleAbove_actionPerformed(ActionEvent e)
3384   {
3385     viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3386     alignPanel.updateLayout();
3387     alignPanel.paintAlignment(true, false);
3388   }
3389
3390   /**
3391    * DOCUMENT ME!
3392    * 
3393    * @param e
3394    *          DOCUMENT ME!
3395    */
3396   @Override
3397   protected void scaleLeft_actionPerformed(ActionEvent e)
3398   {
3399     viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3400     alignPanel.updateLayout();
3401     alignPanel.paintAlignment(true, false);
3402   }
3403
3404   /**
3405    * DOCUMENT ME!
3406    * 
3407    * @param e
3408    *          DOCUMENT ME!
3409    */
3410   @Override
3411   protected void scaleRight_actionPerformed(ActionEvent e)
3412   {
3413     viewport.setScaleRightWrapped(scaleRight.isSelected());
3414     alignPanel.updateLayout();
3415     alignPanel.paintAlignment(true, false);
3416   }
3417
3418   /**
3419    * DOCUMENT ME!
3420    * 
3421    * @param e
3422    *          DOCUMENT ME!
3423    */
3424   @Override
3425   public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3426   {
3427     viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3428     alignPanel.paintAlignment(false, false);
3429   }
3430
3431   /**
3432    * DOCUMENT ME!
3433    * 
3434    * @param e
3435    *          DOCUMENT ME!
3436    */
3437   @Override
3438   public void viewTextMenuItem_actionPerformed(ActionEvent e)
3439   {
3440     viewport.setShowText(viewTextMenuItem.isSelected());
3441     alignPanel.paintAlignment(false, false);
3442   }
3443
3444   /**
3445    * DOCUMENT ME!
3446    * 
3447    * @param e
3448    *          DOCUMENT ME!
3449    */
3450   @Override
3451   protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3452   {
3453     viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3454     alignPanel.paintAlignment(false, false);
3455   }
3456
3457   public FeatureSettings featureSettings;
3458
3459   @Override
3460   public FeatureSettingsControllerI getFeatureSettingsUI()
3461   {
3462     return featureSettings;
3463   }
3464
3465   @Override
3466   public void featureSettings_actionPerformed(ActionEvent e)
3467   {
3468     if (featureSettings != null)
3469     {
3470       featureSettings.close();
3471       featureSettings = null;
3472     }
3473     if (!showSeqFeatures.isSelected())
3474     {
3475       // make sure features are actually displayed
3476       showSeqFeatures.setSelected(true);
3477       showSeqFeatures_actionPerformed(null);
3478     }
3479     featureSettings = new FeatureSettings(this);
3480   }
3481
3482   /**
3483    * Set or clear 'Show Sequence Features'
3484    * 
3485    * @param evt
3486    *          DOCUMENT ME!
3487    */
3488   @Override
3489   public void showSeqFeatures_actionPerformed(ActionEvent evt)
3490   {
3491     viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3492     alignPanel.paintAlignment(true, true);
3493   }
3494
3495   /**
3496    * Action on toggle of the 'Show annotations' menu item. This shows or hides
3497    * the annotations panel as a whole.
3498    * 
3499    * The options to show/hide all annotations should be enabled when the panel
3500    * is shown, and disabled when the panel is hidden.
3501    * 
3502    * @param e
3503    */
3504   @Override
3505   public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3506   {
3507     final boolean setVisible = annotationPanelMenuItem.isSelected();
3508     viewport.setShowAnnotation(setVisible);
3509     this.showAllSeqAnnotations.setEnabled(setVisible);
3510     this.hideAllSeqAnnotations.setEnabled(setVisible);
3511     this.showAllAlAnnotations.setEnabled(setVisible);
3512     this.hideAllAlAnnotations.setEnabled(setVisible);
3513     alignPanel.updateLayout();
3514   }
3515
3516   @Override
3517   public void alignmentProperties()
3518   {
3519     JEditorPane editPane = new JEditorPane("text/html", "");
3520     editPane.setEditable(false);
3521     StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3522             .formatAsHtml();
3523     editPane.setText(
3524             MessageManager.formatMessage("label.html_content", new Object[]
3525             { contents.toString() }));
3526     JInternalFrame frame = new JInternalFrame();
3527     frame.getContentPane().add(new JScrollPane(editPane));
3528
3529     Desktop.addInternalFrame(frame, MessageManager
3530             .formatMessage("label.alignment_properties", new Object[]
3531             { getTitle() }), 500, 400);
3532   }
3533
3534   /**
3535    * DOCUMENT ME!
3536    * 
3537    * @param e
3538    *          DOCUMENT ME!
3539    */
3540   @Override
3541   public void overviewMenuItem_actionPerformed(ActionEvent e)
3542   {
3543     if (alignPanel.overviewPanel != null)
3544     {
3545       return;
3546     }
3547
3548     JInternalFrame frame = new JInternalFrame();
3549     final OverviewPanel overview = new OverviewPanel(alignPanel);
3550     frame.setContentPane(overview);
3551     Desktop.addInternalFrame(frame, MessageManager
3552             .formatMessage("label.overview_params", new Object[]
3553             { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3554             true, true);
3555     frame.pack();
3556     frame.setLayer(JLayeredPane.PALETTE_LAYER);
3557     frame.addInternalFrameListener(
3558             new javax.swing.event.InternalFrameAdapter()
3559             {
3560               @Override
3561               public void internalFrameClosed(
3562                       javax.swing.event.InternalFrameEvent evt)
3563               {
3564                 overview.dispose();
3565                 alignPanel.setOverviewPanel(null);
3566               };
3567             });
3568     if (getKeyListeners().length > 0)
3569     {
3570       frame.addKeyListener(getKeyListeners()[0]);
3571     }
3572
3573     alignPanel.setOverviewPanel(overview);
3574   }
3575
3576   @Override
3577   public void textColour_actionPerformed()
3578   {
3579     new TextColourChooser().chooseColour(alignPanel, null);
3580   }
3581
3582   /*
3583    * public void covariationColour_actionPerformed() {
3584    * changeColour(new
3585    * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3586    * ()[0])); }
3587    */
3588   @Override
3589   public void annotationColour_actionPerformed()
3590   {
3591     new AnnotationColourChooser(viewport, alignPanel);
3592   }
3593
3594   @Override
3595   public void annotationColumn_actionPerformed(ActionEvent e)
3596   {
3597     new AnnotationColumnChooser(viewport, alignPanel);
3598   }
3599
3600   /**
3601    * Action on the user checking or unchecking the option to apply the selected
3602    * colour scheme to all groups. If unchecked, groups may have their own
3603    * independent colour schemes.
3604    * 
3605    * @param selected
3606    */
3607   @Override
3608   public void applyToAllGroups_actionPerformed(boolean selected)
3609   {
3610     viewport.setColourAppliesToAllGroups(selected);
3611   }
3612
3613   /**
3614    * Action on user selecting a colour from the colour menu
3615    * 
3616    * @param name
3617    *          the name (not the menu item label!) of the colour scheme
3618    */
3619   @Override
3620   public void changeColour_actionPerformed(String name)
3621   {
3622     /*
3623      * 'User Defined' opens a panel to configure or load a
3624      * user-defined colour scheme
3625      */
3626     if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3627     {
3628       new UserDefinedColours(alignPanel);
3629       return;
3630     }
3631
3632     /*
3633      * otherwise set the chosen colour scheme (or null for 'None')
3634      */
3635     ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3636             viewport,
3637             viewport.getAlignment(), viewport.getHiddenRepSequences());
3638     changeColour(cs);
3639   }
3640
3641   /**
3642    * Actions on setting or changing the alignment colour scheme
3643    * 
3644    * @param cs
3645    */
3646   @Override
3647   public void changeColour(ColourSchemeI cs)
3648   {
3649     // TODO: pull up to controller method
3650     ColourMenuHelper.setColourSelected(colourMenu, cs);
3651
3652     viewport.setGlobalColourScheme(cs);
3653
3654     alignPanel.paintAlignment(true, true);
3655   }
3656
3657   /**
3658    * Show the PID threshold slider panel
3659    */
3660   @Override
3661   protected void modifyPID_actionPerformed()
3662   {
3663     SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3664             alignPanel.getViewName());
3665     SliderPanel.showPIDSlider();
3666   }
3667
3668   /**
3669    * Show the Conservation slider panel
3670    */
3671   @Override
3672   protected void modifyConservation_actionPerformed()
3673   {
3674     SliderPanel.setConservationSlider(alignPanel,
3675             viewport.getResidueShading(), alignPanel.getViewName());
3676     SliderPanel.showConservationSlider();
3677   }
3678
3679   /**
3680    * Action on selecting or deselecting (Colour) By Conservation
3681    */
3682   @Override
3683   public void conservationMenuItem_actionPerformed(boolean selected)
3684   {
3685     modifyConservation.setEnabled(selected);
3686     viewport.setConservationSelected(selected);
3687     viewport.getResidueShading().setConservationApplied(selected);
3688
3689     changeColour(viewport.getGlobalColourScheme());
3690     if (selected)
3691     {
3692       modifyConservation_actionPerformed();
3693     }
3694     else
3695     {
3696       SliderPanel.hideConservationSlider();
3697     }
3698   }
3699
3700   /**
3701    * Action on selecting or deselecting (Colour) Above PID Threshold
3702    */
3703   @Override
3704   public void abovePIDThreshold_actionPerformed(boolean selected)
3705   {
3706     modifyPID.setEnabled(selected);
3707     viewport.setAbovePIDThreshold(selected);
3708     if (!selected)
3709     {
3710       viewport.getResidueShading().setThreshold(0,
3711               viewport.isIgnoreGapsConsensus());
3712     }
3713
3714     changeColour(viewport.getGlobalColourScheme());
3715     if (selected)
3716     {
3717       modifyPID_actionPerformed();
3718     }
3719     else
3720     {
3721       SliderPanel.hidePIDSlider();
3722     }
3723   }
3724
3725   /**
3726    * DOCUMENT ME!
3727    * 
3728    * @param e
3729    *          DOCUMENT ME!
3730    */
3731   @Override
3732   public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3733   {
3734     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3735     AlignmentSorter.sortByPID(viewport.getAlignment(),
3736             viewport.getAlignment().getSequenceAt(0));
3737     addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3738             viewport.getAlignment()));
3739     alignPanel.paintAlignment(true, false);
3740   }
3741
3742   /**
3743    * DOCUMENT ME!
3744    * 
3745    * @param e
3746    *          DOCUMENT ME!
3747    */
3748   @Override
3749   public void sortIDMenuItem_actionPerformed(ActionEvent e)
3750   {
3751     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3752     AlignmentSorter.sortByID(viewport.getAlignment());
3753     addHistoryItem(
3754             new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3755     alignPanel.paintAlignment(true, false);
3756   }
3757
3758   /**
3759    * DOCUMENT ME!
3760    * 
3761    * @param e
3762    *          DOCUMENT ME!
3763    */
3764   @Override
3765   public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3766   {
3767     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3768     AlignmentSorter.sortByLength(viewport.getAlignment());
3769     addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3770             viewport.getAlignment()));
3771     alignPanel.paintAlignment(true, false);
3772   }
3773
3774   /**
3775    * DOCUMENT ME!
3776    * 
3777    * @param e
3778    *          DOCUMENT ME!
3779    */
3780   @Override
3781   public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3782   {
3783     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3784     AlignmentSorter.sortByGroup(viewport.getAlignment());
3785     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3786             viewport.getAlignment()));
3787
3788     alignPanel.paintAlignment(true, false);
3789   }
3790
3791   @Override
3792   public void sortEValueMenuItem_actionPerformed(ActionEvent e)
3793   {
3794     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3795     AlignmentSorter.sortByEValue(viewport.getAlignment());
3796     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3797             viewport.getAlignment()));
3798     alignPanel.paintAlignment(true, false);
3799
3800   }
3801
3802   @Override
3803   public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
3804   {
3805     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3806     AlignmentSorter.sortByBitScore(viewport.getAlignment());
3807     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3808             viewport.getAlignment()));
3809     alignPanel.paintAlignment(true, false);
3810
3811   }
3812   
3813   /**
3814    * DOCUMENT ME!
3815    * 
3816    * @param e
3817    *          DOCUMENT ME!
3818    */
3819   @Override
3820   public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3821   {
3822     new RedundancyPanel(alignPanel, this);
3823   }
3824
3825   /**
3826    * DOCUMENT ME!
3827    * 
3828    * @param e
3829    *          DOCUMENT ME!
3830    */
3831   @Override
3832   public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3833   {
3834     if ((viewport.getSelectionGroup() == null)
3835             || (viewport.getSelectionGroup().getSize() < 2))
3836     {
3837       JvOptionPane.showInternalMessageDialog(this,
3838               MessageManager.getString(
3839                       "label.you_must_select_least_two_sequences"),
3840               MessageManager.getString("label.invalid_selection"),
3841               JvOptionPane.WARNING_MESSAGE);
3842     }
3843     else
3844     {
3845       JInternalFrame frame = new JInternalFrame();
3846       frame.setContentPane(new PairwiseAlignPanel(viewport));
3847       Desktop.addInternalFrame(frame,
3848               MessageManager.getString("action.pairwise_alignment"), 600,
3849               500);
3850     }
3851   }
3852
3853   @Override
3854   public void autoCalculate_actionPerformed(ActionEvent e)
3855   {
3856     viewport.autoCalculateConsensus = autoCalculate.isSelected();
3857     if (viewport.autoCalculateConsensus)
3858     {
3859       viewport.firePropertyChange("alignment", null,
3860               viewport.getAlignment().getSequences());
3861     }
3862   }
3863
3864   @Override
3865   public void sortByTreeOption_actionPerformed(ActionEvent e)
3866   {
3867     viewport.sortByTree = sortByTree.isSelected();
3868   }
3869
3870   @Override
3871   protected void listenToViewSelections_actionPerformed(ActionEvent e)
3872   {
3873     viewport.followSelection = listenToViewSelections.isSelected();
3874   }
3875
3876   /**
3877    * Constructs a tree panel and adds it to the desktop
3878    * 
3879    * @param type
3880    *          tree type (NJ or AV)
3881    * @param modelName
3882    *          name of score model used to compute the tree
3883    * @param options
3884    *          parameters for the distance or similarity calculation
3885    */
3886   void newTreePanel(String type, String modelName,
3887           SimilarityParamsI options)
3888   {
3889     String frameTitle = "";
3890     TreePanel tp;
3891
3892     boolean onSelection = false;
3893     if (viewport.getSelectionGroup() != null
3894             && viewport.getSelectionGroup().getSize() > 0)
3895     {
3896       SequenceGroup sg = viewport.getSelectionGroup();
3897
3898       /* Decide if the selection is a column region */
3899       for (SequenceI _s : sg.getSequences())
3900       {
3901         if (_s.getLength() < sg.getEndRes())
3902         {
3903           JvOptionPane.showMessageDialog(Desktop.desktop,
3904                   MessageManager.getString(
3905                           "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3906                   MessageManager.getString(
3907                           "label.sequences_selection_not_aligned"),
3908                   JvOptionPane.WARNING_MESSAGE);
3909
3910           return;
3911         }
3912       }
3913       onSelection = true;
3914     }
3915     else
3916     {
3917       if (viewport.getAlignment().getHeight() < 2)
3918       {
3919         return;
3920       }
3921     }
3922
3923     tp = new TreePanel(alignPanel, type, modelName, options);
3924     frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3925
3926     frameTitle += " from ";
3927
3928     if (viewport.getViewName() != null)
3929     {
3930       frameTitle += viewport.getViewName() + " of ";
3931     }
3932
3933     frameTitle += this.title;
3934
3935     Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3936   }
3937
3938   /**
3939    * DOCUMENT ME!
3940    * 
3941    * @param title
3942    *          DOCUMENT ME!
3943    * @param order
3944    *          DOCUMENT ME!
3945    */
3946   public void addSortByOrderMenuItem(String title,
3947           final AlignmentOrder order)
3948   {
3949     final JMenuItem item = new JMenuItem(MessageManager
3950             .formatMessage("action.by_title_param", new Object[]
3951             { title }));
3952     sort.add(item);
3953     item.addActionListener(new java.awt.event.ActionListener()
3954     {
3955       @Override
3956       public void actionPerformed(ActionEvent e)
3957       {
3958         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3959
3960         // TODO: JBPNote - have to map order entries to curent SequenceI
3961         // pointers
3962         AlignmentSorter.sortBy(viewport.getAlignment(), order);
3963
3964         addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3965                 viewport.getAlignment()));
3966
3967         alignPanel.paintAlignment(true, false);
3968       }
3969     });
3970   }
3971
3972   /**
3973    * Add a new sort by annotation score menu item
3974    * 
3975    * @param sort
3976    *          the menu to add the option to
3977    * @param scoreLabel
3978    *          the label used to retrieve scores for each sequence on the
3979    *          alignment
3980    */
3981   public void addSortByAnnotScoreMenuItem(JMenu sort,
3982           final String scoreLabel)
3983   {
3984     final JMenuItem item = new JMenuItem(scoreLabel);
3985     sort.add(item);
3986     item.addActionListener(new java.awt.event.ActionListener()
3987     {
3988       @Override
3989       public void actionPerformed(ActionEvent e)
3990       {
3991         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3992         AlignmentSorter.sortByAnnotationScore(scoreLabel,
3993                 viewport.getAlignment());// ,viewport.getSelectionGroup());
3994         addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3995                 viewport.getAlignment()));
3996         alignPanel.paintAlignment(true, false);
3997       }
3998     });
3999   }
4000
4001   /**
4002    * last hash for alignment's annotation array - used to minimise cost of
4003    * rebuild.
4004    */
4005   protected int _annotationScoreVectorHash;
4006
4007   /**
4008    * search the alignment and rebuild the sort by annotation score submenu the
4009    * last alignment annotation vector hash is stored to minimize cost of
4010    * rebuilding in subsequence calls.
4011    * 
4012    */
4013   @Override
4014   public void buildSortByAnnotationScoresMenu()
4015   {
4016     if (viewport.getAlignment().getAlignmentAnnotation() == null)
4017     {
4018       return;
4019     }
4020
4021     if (viewport.getAlignment().getAlignmentAnnotation()
4022             .hashCode() == _annotationScoreVectorHash)
4023     {
4024       return;
4025     }
4026
4027     sortByAnnotScore.removeAll();
4028     Set<String> scoreSorts = new HashSet<>();
4029     for (SequenceI sqa : viewport.getAlignment().getSequences())
4030     {
4031       AlignmentAnnotation[] anns = sqa.getAnnotation();
4032       for (int i = 0; anns != null && i < anns.length; i++)
4033       {
4034         AlignmentAnnotation aa = anns[i];
4035         if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4036         {
4037           scoreSorts.add(aa.label);
4038         }
4039       }
4040     }
4041     for (String label : scoreSorts)
4042     {
4043       addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4044     }
4045     sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4046
4047     _annotationScoreVectorHash = viewport.getAlignment()
4048             .getAlignmentAnnotation().hashCode();
4049   }
4050
4051   /**
4052    * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4053    * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4054    * call. Listeners are added to remove the menu item when the treePanel is
4055    * closed, and adjust the tree leaf to sequence mapping when the alignment is
4056    * modified.
4057    */
4058   @Override
4059   public void buildTreeSortMenu()
4060   {
4061     sortByTreeMenu.removeAll();
4062
4063     List<Component> comps = PaintRefresher.components
4064             .get(viewport.getSequenceSetId());
4065     List<TreePanel> treePanels = new ArrayList<>();
4066     for (Component comp : comps)
4067     {
4068       if (comp instanceof TreePanel)
4069       {
4070         treePanels.add((TreePanel) comp);
4071       }
4072     }
4073
4074     if (treePanels.size() < 1)
4075     {
4076       sortByTreeMenu.setVisible(false);
4077       return;
4078     }
4079
4080     sortByTreeMenu.setVisible(true);
4081
4082     for (final TreePanel tp : treePanels)
4083     {
4084       final JMenuItem item = new JMenuItem(tp.getTitle());
4085       item.addActionListener(new java.awt.event.ActionListener()
4086       {
4087         @Override
4088         public void actionPerformed(ActionEvent e)
4089         {
4090           tp.sortByTree_actionPerformed();
4091           addHistoryItem(tp.sortAlignmentIn(alignPanel));
4092
4093         }
4094       });
4095
4096       sortByTreeMenu.add(item);
4097     }
4098   }
4099
4100   public boolean sortBy(AlignmentOrder alorder, String undoname)
4101   {
4102     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4103     AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4104     if (undoname != null)
4105     {
4106       addHistoryItem(new OrderCommand(undoname, oldOrder,
4107               viewport.getAlignment()));
4108     }
4109     alignPanel.paintAlignment(true, false);
4110     return true;
4111   }
4112
4113   /**
4114    * Work out whether the whole set of sequences or just the selected set will
4115    * be submitted for multiple alignment.
4116    * 
4117    */
4118   public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4119   {
4120     // Now, check we have enough sequences
4121     AlignmentView msa = null;
4122
4123     if ((viewport.getSelectionGroup() != null)
4124             && (viewport.getSelectionGroup().getSize() > 1))
4125     {
4126       // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4127       // some common interface!
4128       /*
4129        * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4130        * SequenceI[sz = seqs.getSize(false)];
4131        * 
4132        * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4133        * seqs.getSequenceAt(i); }
4134        */
4135       msa = viewport.getAlignmentView(true);
4136     }
4137     else if (viewport.getSelectionGroup() != null
4138             && viewport.getSelectionGroup().getSize() == 1)
4139     {
4140       int option = JvOptionPane.showConfirmDialog(this,
4141               MessageManager.getString("warn.oneseq_msainput_selection"),
4142               MessageManager.getString("label.invalid_selection"),
4143               JvOptionPane.OK_CANCEL_OPTION);
4144       if (option == JvOptionPane.OK_OPTION)
4145       {
4146         msa = viewport.getAlignmentView(false);
4147       }
4148     }
4149     else
4150     {
4151       msa = viewport.getAlignmentView(false);
4152     }
4153     return msa;
4154   }
4155
4156   /**
4157    * Decides what is submitted to a secondary structure prediction service: the
4158    * first sequence in the alignment, or in the current selection, or, if the
4159    * alignment is 'aligned' (ie padded with gaps), then the currently selected
4160    * region or the whole alignment. (where the first sequence in the set is the
4161    * one that the prediction will be for).
4162    */
4163   public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4164   {
4165     AlignmentView seqs = null;
4166
4167     if ((viewport.getSelectionGroup() != null)
4168             && (viewport.getSelectionGroup().getSize() > 0))
4169     {
4170       seqs = viewport.getAlignmentView(true);
4171     }
4172     else
4173     {
4174       seqs = viewport.getAlignmentView(false);
4175     }
4176     // limit sequences - JBPNote in future - could spawn multiple prediction
4177     // jobs
4178     // TODO: viewport.getAlignment().isAligned is a global state - the local
4179     // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4180     if (!viewport.getAlignment().isAligned(false))
4181     {
4182       seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4183       // TODO: if seqs.getSequences().length>1 then should really have warned
4184       // user!
4185
4186     }
4187     return seqs;
4188   }
4189
4190   /**
4191    * DOCUMENT ME!
4192    * 
4193    * @param e
4194    *          DOCUMENT ME!
4195    */
4196   @Override
4197   protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4198   {
4199     // Pick the tree file
4200     JalviewFileChooser chooser = new JalviewFileChooser(
4201             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4202     chooser.setFileView(new JalviewFileView());
4203     chooser.setDialogTitle(
4204             MessageManager.getString("label.select_newick_like_tree_file"));
4205     chooser.setToolTipText(
4206             MessageManager.getString("label.load_tree_file"));
4207
4208     int value = chooser.showOpenDialog(null);
4209
4210     if (value == JalviewFileChooser.APPROVE_OPTION)
4211     {
4212       String filePath = chooser.getSelectedFile().getPath();
4213       Cache.setProperty("LAST_DIRECTORY", filePath);
4214       NewickFile fin = null;
4215       try
4216       {
4217         fin = new NewickFile(filePath, DataSourceType.FILE);
4218         viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4219       } catch (Exception ex)
4220       {
4221         JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4222                 MessageManager.getString("label.problem_reading_tree_file"),
4223                 JvOptionPane.WARNING_MESSAGE);
4224         ex.printStackTrace();
4225       }
4226       if (fin != null && fin.hasWarningMessage())
4227       {
4228         JvOptionPane.showMessageDialog(Desktop.desktop,
4229                 fin.getWarningMessage(),
4230                 MessageManager
4231                         .getString("label.possible_problem_with_tree_file"),
4232                 JvOptionPane.WARNING_MESSAGE);
4233       }
4234     }
4235   }
4236
4237   public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4238   {
4239     return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4240   }
4241
4242   public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4243           int h, int x, int y)
4244   {
4245     return showNewickTree(nf, treeTitle, null, w, h, x, y);
4246   }
4247
4248   /**
4249    * Add a treeviewer for the tree extracted from a Newick file object to the
4250    * current alignment view
4251    * 
4252    * @param nf
4253    *          the tree
4254    * @param title
4255    *          tree viewer title
4256    * @param input
4257    *          Associated alignment input data (or null)
4258    * @param w
4259    *          width
4260    * @param h
4261    *          height
4262    * @param x
4263    *          position
4264    * @param y
4265    *          position
4266    * @return TreePanel handle
4267    */
4268   public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4269           AlignmentView input, int w, int h, int x, int y)
4270   {
4271     TreePanel tp = null;
4272
4273     try
4274     {
4275       nf.parse();
4276
4277       if (nf.getTree() != null)
4278       {
4279         tp = new TreePanel(alignPanel, nf, treeTitle, input);
4280
4281         tp.setSize(w, h);
4282
4283         if (x > 0 && y > 0)
4284         {
4285           tp.setLocation(x, y);
4286         }
4287
4288         Desktop.addInternalFrame(tp, treeTitle, w, h);
4289       }
4290     } catch (Exception ex)
4291     {
4292       ex.printStackTrace();
4293     }
4294
4295     return tp;
4296   }
4297
4298   private boolean buildingMenu = false;
4299
4300   /**
4301    * Generates menu items and listener event actions for web service clients
4302    * 
4303    */
4304   public void BuildWebServiceMenu()
4305   {
4306     while (buildingMenu)
4307     {
4308       try
4309       {
4310         System.err.println("Waiting for building menu to finish.");
4311         Thread.sleep(10);
4312       } catch (Exception e)
4313       {
4314       }
4315     }
4316     final AlignFrame me = this;
4317     buildingMenu = true;
4318     new Thread(new Runnable()
4319     {
4320       @Override
4321       public void run()
4322       {
4323         final List<JMenuItem> legacyItems = new ArrayList<>();
4324         try
4325         {
4326           // System.err.println("Building ws menu again "
4327           // + Thread.currentThread());
4328           // TODO: add support for context dependent disabling of services based
4329           // on
4330           // alignment and current selection
4331           // TODO: add additional serviceHandle parameter to specify abstract
4332           // handler
4333           // class independently of AbstractName
4334           // TODO: add in rediscovery GUI function to restart discoverer
4335           // TODO: group services by location as well as function and/or
4336           // introduce
4337           // object broker mechanism.
4338           final Vector<JMenu> wsmenu = new Vector<>();
4339           final IProgressIndicator af = me;
4340
4341           /*
4342            * do not i18n these strings - they are hard-coded in class
4343            * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4344            * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4345            */
4346           final JMenu msawsmenu = new JMenu("Alignment");
4347           final JMenu secstrmenu = new JMenu(
4348                   "Secondary Structure Prediction");
4349           final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4350           final JMenu analymenu = new JMenu("Analysis");
4351           final JMenu dismenu = new JMenu("Protein Disorder");
4352           // JAL-940 - only show secondary structure prediction services from
4353           // the legacy server
4354           if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4355               // &&
4356           Discoverer.services != null && (Discoverer.services.size() > 0))
4357           {
4358             // TODO: refactor to allow list of AbstractName/Handler bindings to
4359             // be
4360             // stored or retrieved from elsewhere
4361             // No MSAWS used any more:
4362             // Vector msaws = null; // (Vector)
4363             // Discoverer.services.get("MsaWS");
4364             Vector secstrpr = (Vector) Discoverer.services
4365                     .get("SecStrPred");
4366             if (secstrpr != null)
4367             {
4368               // Add any secondary structure prediction services
4369               for (int i = 0, j = secstrpr.size(); i < j; i++)
4370               {
4371                 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4372                         .get(i);
4373                 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4374                         .getServiceClient(sh);
4375                 int p = secstrmenu.getItemCount();
4376                 impl.attachWSMenuEntry(secstrmenu, me);
4377                 int q = secstrmenu.getItemCount();
4378                 for (int litm = p; litm < q; litm++)
4379                 {
4380                   legacyItems.add(secstrmenu.getItem(litm));
4381                 }
4382               }
4383             }
4384           }
4385
4386           // Add all submenus in the order they should appear on the web
4387           // services menu
4388           wsmenu.add(msawsmenu);
4389           wsmenu.add(secstrmenu);
4390           wsmenu.add(dismenu);
4391           wsmenu.add(analymenu);
4392           // No search services yet
4393           // wsmenu.add(seqsrchmenu);
4394
4395           javax.swing.SwingUtilities.invokeLater(new Runnable()
4396           {
4397             @Override
4398             public void run()
4399             {
4400               try
4401               {
4402                 webService.removeAll();
4403                 // first, add discovered services onto the webservices menu
4404                 if (wsmenu.size() > 0)
4405                 {
4406                   for (int i = 0, j = wsmenu.size(); i < j; i++)
4407                   {
4408                     webService.add(wsmenu.get(i));
4409                   }
4410                 }
4411                 else
4412                 {
4413                   webService.add(me.webServiceNoServices);
4414                 }
4415                 // TODO: move into separate menu builder class.
4416                 boolean new_sspred = false;
4417                 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4418                 {
4419                   Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4420                   if (jws2servs != null)
4421                   {
4422                     if (jws2servs.hasServices())
4423                     {
4424                       jws2servs.attachWSMenuEntry(webService, me);
4425                       for (ServiceWithParameters sv : jws2servs.getServices())
4426                       {
4427                         if (sv.getName().toLowerCase().contains("jpred"))
4428                         {
4429                           for (JMenuItem jmi : legacyItems)
4430                           {
4431                             jmi.setVisible(false);
4432                           }
4433                         }
4434                       }
4435
4436                     }
4437                     if (jws2servs.isRunning())
4438                     {
4439                       JMenuItem tm = new JMenuItem(
4440                               "Still discovering JABA Services");
4441                       tm.setEnabled(false);
4442                       webService.add(tm);
4443                     }
4444                   }
4445                 }
4446                 build_urlServiceMenu(me.webService);
4447
4448
4449                 // TODO Mateusz - follow pattern for adding web service
4450                 // JMenuItems for slivka-based services
4451
4452                 SlivkaWSDiscoverer slivkaDiscoverer = SlivkaWSDiscoverer.getInstance();
4453                 if (slivkaDiscoverer.hasServices())
4454                 {
4455                 slivkaDiscoverer.attachWSMenuEntry(webService, me);
4456                 } else {
4457                   if (slivkaDiscoverer.isRunning())
4458                   {
4459                     {
4460                       JMenuItem tm = new JMenuItem(
4461                               "Still discovering Slivka Services");
4462                       tm.setEnabled(false);
4463                       webService.add(tm);
4464                     }
4465
4466                   }
4467                 }
4468               
4469
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 }