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