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