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