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