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