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