JAL-3436 debug comments out in JSPopupMenuUI.js
[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 = Platform.getDimIfEmbedded(frame, -1, -1);
3397     if (dim != null && dim.width == 0)
3398     {
3399       dim = null; // hidden, not embedded
3400     }
3401     OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3402
3403     frame.setContentPane(overview);
3404     if (dim == null)
3405     {
3406       dim = new Dimension();
3407       // was frame.getSize(), but that is 0,0 at this point;
3408     }
3409     else
3410     {
3411       // we are imbedding, and so we have an undecorated frame
3412       // and we can set the the frame dimensions accordingly.
3413     }
3414     // allowing for unresizable option using, style="resize:none"
3415     boolean resizable = (Platform.getEmbeddedAttribute(frame,
3416             "resize") != "none");
3417     Desktop.addInternalFrame(frame, MessageManager
3418             .formatMessage("label.overview_params", new Object[]
3419             { this.getTitle() }), true, dim.width, dim.height, resizable,
3420             true);
3421     frame.pack();
3422     frame.setLayer(JLayeredPane.PALETTE_LAYER);
3423     frame.addInternalFrameListener(
3424             new javax.swing.event.InternalFrameAdapter()
3425             {
3426               @Override
3427               public void internalFrameClosed(
3428                       javax.swing.event.InternalFrameEvent evt)
3429               {
3430                 overview.dispose();
3431                 alignPanel.setOverviewPanel(null);
3432               }
3433             });
3434     if (getKeyListeners().length > 0)
3435     {
3436       frame.addKeyListener(getKeyListeners()[0]);
3437     }
3438
3439     alignPanel.setOverviewPanel(overview);
3440   }
3441
3442   @Override
3443   public void textColour_actionPerformed()
3444   {
3445     new TextColourChooser().chooseColour(alignPanel, null);
3446   }
3447
3448   /*
3449    * public void covariationColour_actionPerformed() {
3450    * changeColour(new
3451    * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3452    * ()[0])); }
3453    */
3454   @Override
3455   public void annotationColour_actionPerformed()
3456   {
3457     new AnnotationColourChooser(viewport, alignPanel);
3458   }
3459
3460   @Override
3461   public void annotationColumn_actionPerformed(ActionEvent e)
3462   {
3463     new AnnotationColumnChooser(viewport, alignPanel);
3464   }
3465
3466   /**
3467    * Action on the user checking or unchecking the option to apply the selected
3468    * colour scheme to all groups. If unchecked, groups may have their own
3469    * independent colour schemes.
3470    * 
3471    * @param selected
3472    */
3473   @Override
3474   public void applyToAllGroups_actionPerformed(boolean selected)
3475   {
3476     viewport.setColourAppliesToAllGroups(selected);
3477   }
3478
3479   /**
3480    * Action on user selecting a colour from the colour menu
3481    * 
3482    * @param name
3483    *          the name (not the menu item label!) of the colour scheme
3484    */
3485   @Override
3486   public void changeColour_actionPerformed(String name)
3487   {
3488     /*
3489      * 'User Defined' opens a panel to configure or load a
3490      * user-defined colour scheme
3491      */
3492     if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3493     {
3494       new UserDefinedColours(alignPanel);
3495       return;
3496     }
3497
3498     /*
3499      * otherwise set the chosen colour scheme (or null for 'None')
3500      */
3501     ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3502             viewport,
3503             viewport.getAlignment(), viewport.getHiddenRepSequences());
3504     changeColour(cs);
3505   }
3506
3507   /**
3508    * Actions on setting or changing the alignment colour scheme
3509    * 
3510    * @param cs
3511    */
3512   @Override
3513   public void changeColour(ColourSchemeI cs)
3514   {
3515     // TODO: pull up to controller method
3516     ColourMenuHelper.setColourSelected(colourMenu, cs);
3517
3518     viewport.setGlobalColourScheme(cs);
3519
3520     alignPanel.paintAlignment(true, true);
3521   }
3522
3523   /**
3524    * Show the PID threshold slider panel
3525    */
3526   @Override
3527   protected void modifyPID_actionPerformed()
3528   {
3529     SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3530             alignPanel.getViewName());
3531     SliderPanel.showPIDSlider();
3532   }
3533
3534   /**
3535    * Show the Conservation slider panel
3536    */
3537   @Override
3538   protected void modifyConservation_actionPerformed()
3539   {
3540     SliderPanel.setConservationSlider(alignPanel,
3541             viewport.getResidueShading(), alignPanel.getViewName());
3542     SliderPanel.showConservationSlider();
3543   }
3544
3545   /**
3546    * Action on selecting or deselecting (Colour) By Conservation
3547    */
3548   @Override
3549   public void conservationMenuItem_actionPerformed(boolean selected)
3550   {
3551     modifyConservation.setEnabled(selected);
3552     viewport.setConservationSelected(selected);
3553     viewport.getResidueShading().setConservationApplied(selected);
3554
3555     changeColour(viewport.getGlobalColourScheme());
3556     if (selected)
3557     {
3558       modifyConservation_actionPerformed();
3559     }
3560     else
3561     {
3562       SliderPanel.hideConservationSlider();
3563     }
3564   }
3565
3566   /**
3567    * Action on selecting or deselecting (Colour) Above PID Threshold
3568    */
3569   @Override
3570   public void abovePIDThreshold_actionPerformed(boolean selected)
3571   {
3572     modifyPID.setEnabled(selected);
3573     viewport.setAbovePIDThreshold(selected);
3574     if (!selected)
3575     {
3576       viewport.getResidueShading().setThreshold(0,
3577               viewport.isIgnoreGapsConsensus());
3578     }
3579
3580     changeColour(viewport.getGlobalColourScheme());
3581     if (selected)
3582     {
3583       modifyPID_actionPerformed();
3584     }
3585     else
3586     {
3587       SliderPanel.hidePIDSlider();
3588     }
3589   }
3590
3591   /**
3592    * DOCUMENT ME!
3593    * 
3594    * @param e
3595    *          DOCUMENT ME!
3596    */
3597   @Override
3598   public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3599   {
3600     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3601     AlignmentSorter.sortByPID(viewport.getAlignment(),
3602             viewport.getAlignment().getSequenceAt(0));
3603     addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3604             viewport.getAlignment()));
3605     alignPanel.paintAlignment(true, false);
3606   }
3607
3608   /**
3609    * DOCUMENT ME!
3610    * 
3611    * @param e
3612    *          DOCUMENT ME!
3613    */
3614   @Override
3615   public void sortIDMenuItem_actionPerformed(ActionEvent e)
3616   {
3617     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3618     AlignmentSorter.sortByID(viewport.getAlignment());
3619     addHistoryItem(
3620             new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3621     alignPanel.paintAlignment(true, false);
3622   }
3623
3624   /**
3625    * DOCUMENT ME!
3626    * 
3627    * @param e
3628    *          DOCUMENT ME!
3629    */
3630   @Override
3631   public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3632   {
3633     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3634     AlignmentSorter.sortByLength(viewport.getAlignment());
3635     addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3636             viewport.getAlignment()));
3637     alignPanel.paintAlignment(true, false);
3638   }
3639
3640   /**
3641    * DOCUMENT ME!
3642    * 
3643    * @param e
3644    *          DOCUMENT ME!
3645    */
3646   @Override
3647   public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3648   {
3649     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3650     AlignmentSorter.sortByGroup(viewport.getAlignment());
3651     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3652             viewport.getAlignment()));
3653
3654     alignPanel.paintAlignment(true, false);
3655   }
3656
3657   /**
3658    * DOCUMENT ME!
3659    * 
3660    * @param e
3661    *          DOCUMENT ME!
3662    */
3663   @Override
3664   public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3665   {
3666     new RedundancyPanel(alignPanel, this);
3667   }
3668
3669   /**
3670    * DOCUMENT ME!
3671    * 
3672    * @param e
3673    *          DOCUMENT ME!
3674    */
3675   @Override
3676   public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3677   {
3678     if ((viewport.getSelectionGroup() == null)
3679             || (viewport.getSelectionGroup().getSize() < 2))
3680     {
3681       JvOptionPane.showInternalMessageDialog(this,
3682               MessageManager.getString(
3683                       "label.you_must_select_least_two_sequences"),
3684               MessageManager.getString("label.invalid_selection"),
3685               JvOptionPane.WARNING_MESSAGE);
3686     }
3687     else
3688     {
3689       JInternalFrame frame = new JInternalFrame();
3690       frame.setContentPane(new PairwiseAlignPanel(viewport));
3691       Desktop.addInternalFrame(frame,
3692               MessageManager.getString("action.pairwise_alignment"), 600,
3693               500);
3694     }
3695   }
3696
3697   @Override
3698   public void autoCalculate_actionPerformed(ActionEvent e)
3699   {
3700     viewport.setAutoCalculateConsensusAndConservation(autoCalculate.isSelected());
3701     if (viewport.getAutoCalculateConsensusAndConservation())
3702     {
3703       viewport.firePropertyChange("alignment", null,
3704               viewport.getAlignment().getSequences());
3705     }
3706   }
3707
3708   @Override
3709   public void sortByTreeOption_actionPerformed(ActionEvent e)
3710   {
3711     viewport.sortByTree = sortByTree.isSelected();
3712   }
3713
3714   @Override
3715   protected void listenToViewSelections_actionPerformed(ActionEvent e)
3716   {
3717     viewport.followSelection = listenToViewSelections.isSelected();
3718   }
3719
3720   /**
3721    * Constructs a tree panel and adds it to the desktop
3722    * 
3723    * @param type
3724    *          tree type (NJ or AV)
3725    * @param modelName
3726    *          name of score model used to compute the tree
3727    * @param options
3728    *          parameters for the distance or similarity calculation
3729    */
3730   void newTreePanel(String type, String modelName,
3731           SimilarityParamsI options)
3732   {
3733     String frameTitle = "";
3734     TreePanel tp;
3735
3736     boolean onSelection = false;
3737     if (viewport.getSelectionGroup() != null
3738             && viewport.getSelectionGroup().getSize() > 0)
3739     {
3740       SequenceGroup sg = viewport.getSelectionGroup();
3741
3742       /* Decide if the selection is a column region */
3743       for (SequenceI _s : sg.getSequences())
3744       {
3745         if (_s.getLength() < sg.getEndRes())
3746         {
3747           JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
3748                   MessageManager.getString(
3749                           "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3750                   MessageManager.getString(
3751                           "label.sequences_selection_not_aligned"),
3752                   JvOptionPane.WARNING_MESSAGE);
3753
3754           return;
3755         }
3756       }
3757       onSelection = true;
3758     }
3759     else
3760     {
3761       if (viewport.getAlignment().getHeight() < 2)
3762       {
3763         return;
3764       }
3765     }
3766
3767     tp = new TreePanel(alignPanel, type, modelName, options);
3768     frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3769
3770     frameTitle += " from ";
3771
3772     if (viewport.getViewName() != null)
3773     {
3774       frameTitle += viewport.getViewName() + " of ";
3775     }
3776
3777     frameTitle += this.title;
3778
3779     Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
3780     Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
3781   }
3782
3783   /**
3784    * DOCUMENT ME!
3785    * 
3786    * @param title
3787    *          DOCUMENT ME!
3788    * @param order
3789    *          DOCUMENT ME!
3790    */
3791   public void addSortByOrderMenuItem(String title,
3792           final AlignmentOrder order)
3793   {
3794     final JMenuItem item = new JMenuItem(MessageManager
3795             .formatMessage("action.by_title_param", new Object[]
3796             { title }));
3797     sort.add(item);
3798     item.addActionListener(new java.awt.event.ActionListener()
3799     {
3800       @Override
3801       public void actionPerformed(ActionEvent e)
3802       {
3803         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3804
3805         // TODO: JBPNote - have to map order entries to curent SequenceI
3806         // pointers
3807         AlignmentSorter.sortBy(viewport.getAlignment(), order);
3808
3809         addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3810                 viewport.getAlignment()));
3811
3812         alignPanel.paintAlignment(true, false);
3813       }
3814     });
3815   }
3816
3817   /**
3818    * Add a new sort by annotation score menu item
3819    * 
3820    * @param sort
3821    *          the menu to add the option to
3822    * @param scoreLabel
3823    *          the label used to retrieve scores for each sequence on the
3824    *          alignment
3825    */
3826   public void addSortByAnnotScoreMenuItem(JMenu sort,
3827           final String scoreLabel)
3828   {
3829     final JMenuItem item = new JMenuItem(scoreLabel);
3830     sort.add(item);
3831     item.addActionListener(new java.awt.event.ActionListener()
3832     {
3833       @Override
3834       public void actionPerformed(ActionEvent e)
3835       {
3836         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3837         AlignmentSorter.sortByAnnotationScore(scoreLabel,
3838                 viewport.getAlignment());// ,viewport.getSelectionGroup());
3839         addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3840                 viewport.getAlignment()));
3841         alignPanel.paintAlignment(true, false);
3842       }
3843     });
3844   }
3845
3846   /**
3847    * last hash for alignment's annotation array - used to minimise cost of
3848    * rebuild.
3849    */
3850   protected int _annotationScoreVectorHash;
3851
3852   /**
3853    * search the alignment and rebuild the sort by annotation score submenu the
3854    * last alignment annotation vector hash is stored to minimize cost of
3855    * rebuilding in subsequence calls.
3856    * 
3857    */
3858   @Override
3859   public void buildSortByAnnotationScoresMenu()
3860   {
3861     if (viewport.getAlignment().getAlignmentAnnotation() == null)
3862     {
3863       return;
3864     }
3865
3866     if (viewport.getAlignment().getAlignmentAnnotation()
3867             .hashCode() != _annotationScoreVectorHash)
3868     {
3869       sortByAnnotScore.removeAll();
3870       // almost certainly a quicker way to do this - but we keep it simple
3871       Hashtable<String, String> scoreSorts = new Hashtable<>();
3872       AlignmentAnnotation aann[];
3873       for (SequenceI sqa : viewport.getAlignment().getSequences())
3874       {
3875         aann = sqa.getAnnotation();
3876         for (int i = 0; aann != null && i < aann.length; i++)
3877         {
3878           if (aann[i].hasScore() && aann[i].sequenceRef != null)
3879           {
3880             scoreSorts.put(aann[i].label, aann[i].label);
3881           }
3882         }
3883       }
3884       Enumeration<String> labels = scoreSorts.keys();
3885       while (labels.hasMoreElements())
3886       {
3887         addSortByAnnotScoreMenuItem(sortByAnnotScore,
3888                 labels.nextElement());
3889       }
3890       sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3891       scoreSorts.clear();
3892
3893       _annotationScoreVectorHash = viewport.getAlignment()
3894               .getAlignmentAnnotation().hashCode();
3895     }
3896   }
3897
3898   /**
3899    * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3900    * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3901    * call. Listeners are added to remove the menu item when the treePanel is
3902    * closed, and adjust the tree leaf to sequence mapping when the alignment is
3903    * modified.
3904    */
3905   @Override
3906   public void buildTreeSortMenu()
3907   {
3908     sortByTreeMenu.removeAll();
3909
3910     List<Component> comps = PaintRefresher.components
3911             .get(viewport.getSequenceSetId());
3912     List<TreePanel> treePanels = new ArrayList<>();
3913     for (Component comp : comps)
3914     {
3915       if (comp instanceof TreePanel)
3916       {
3917         treePanels.add((TreePanel) comp);
3918       }
3919     }
3920
3921     if (treePanels.size() < 1)
3922     {
3923       sortByTreeMenu.setVisible(false);
3924       return;
3925     }
3926
3927     sortByTreeMenu.setVisible(true);
3928
3929     for (final TreePanel tp : treePanels)
3930     {
3931       final JMenuItem item = new JMenuItem(tp.getTitle());
3932       item.addActionListener(new java.awt.event.ActionListener()
3933       {
3934         @Override
3935         public void actionPerformed(ActionEvent e)
3936         {
3937           tp.sortByTree_actionPerformed();
3938           addHistoryItem(tp.sortAlignmentIn(alignPanel));
3939
3940         }
3941       });
3942
3943       sortByTreeMenu.add(item);
3944     }
3945   }
3946
3947   public boolean sortBy(AlignmentOrder alorder, String undoname)
3948   {
3949     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3950     AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3951     if (undoname != null)
3952     {
3953       addHistoryItem(new OrderCommand(undoname, oldOrder,
3954               viewport.getAlignment()));
3955     }
3956     alignPanel.paintAlignment(true, false);
3957     return true;
3958   }
3959
3960   /**
3961    * Work out whether the whole set of sequences or just the selected set will
3962    * be submitted for multiple alignment.
3963    * 
3964    */
3965   public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3966   {
3967     // Now, check we have enough sequences
3968     AlignmentView msa = null;
3969
3970     if ((viewport.getSelectionGroup() != null)
3971             && (viewport.getSelectionGroup().getSize() > 1))
3972     {
3973       // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3974       // some common interface!
3975       /*
3976        * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3977        * SequenceI[sz = seqs.getSize(false)];
3978        * 
3979        * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3980        * seqs.getSequenceAt(i); }
3981        */
3982       msa = viewport.getAlignmentView(true);
3983     }
3984     else if (viewport.getSelectionGroup() != null
3985             && viewport.getSelectionGroup().getSize() == 1)
3986     {
3987       int option = JvOptionPane.showConfirmDialog(this,
3988               MessageManager.getString("warn.oneseq_msainput_selection"),
3989               MessageManager.getString("label.invalid_selection"),
3990               JvOptionPane.OK_CANCEL_OPTION);
3991       if (option == JvOptionPane.OK_OPTION)
3992       {
3993         msa = viewport.getAlignmentView(false);
3994       }
3995     }
3996     else
3997     {
3998       msa = viewport.getAlignmentView(false);
3999     }
4000     return msa;
4001   }
4002
4003   /**
4004    * Decides what is submitted to a secondary structure prediction service: the
4005    * first sequence in the alignment, or in the current selection, or, if the
4006    * alignment is 'aligned' (ie padded with gaps), then the currently selected
4007    * region or the whole alignment. (where the first sequence in the set is the
4008    * one that the prediction will be for).
4009    */
4010   public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4011   {
4012     AlignmentView seqs = null;
4013
4014     if ((viewport.getSelectionGroup() != null)
4015             && (viewport.getSelectionGroup().getSize() > 0))
4016     {
4017       seqs = viewport.getAlignmentView(true);
4018     }
4019     else
4020     {
4021       seqs = viewport.getAlignmentView(false);
4022     }
4023     // limit sequences - JBPNote in future - could spawn multiple prediction
4024     // jobs
4025     // TODO: viewport.getAlignment().isAligned is a global state - the local
4026     // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4027     if (!viewport.getAlignment().isAligned(false))
4028     {
4029       seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4030       // TODO: if seqs.getSequences().length>1 then should really have warned
4031       // user!
4032
4033     }
4034     return seqs;
4035   }
4036
4037   /**
4038    * DOCUMENT ME!
4039    * 
4040    * @param e
4041    *          DOCUMENT ME!
4042    */
4043   @Override
4044   protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4045   {
4046     // Pick the tree file
4047     JalviewFileChooser chooser = new JalviewFileChooser(
4048             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4049     chooser.setFileView(new JalviewFileView());
4050     chooser.setDialogTitle(
4051             MessageManager.getString("label.select_newick_like_tree_file"));
4052     chooser.setToolTipText(
4053             MessageManager.getString("label.load_tree_file"));
4054
4055     chooser.setResponseHandler(0,new Runnable()
4056     {
4057       @Override
4058       public void run()
4059       {
4060         String filePath = chooser.getSelectedFile().getPath();
4061         Cache.setProperty("LAST_DIRECTORY", filePath);
4062         NewickFile fin = null;
4063         try
4064         {
4065           fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4066                   DataSourceType.FILE));
4067           viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4068         } catch (Exception ex)
4069         {
4070           JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), ex.getMessage(),
4071                   MessageManager
4072                           .getString("label.problem_reading_tree_file"),
4073                   JvOptionPane.WARNING_MESSAGE);
4074           ex.printStackTrace();
4075         }
4076         if (fin != null && fin.hasWarningMessage())
4077         {
4078           JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4079                   fin.getWarningMessage(),
4080                   MessageManager.getString(
4081                           "label.possible_problem_with_tree_file"),
4082                   JvOptionPane.WARNING_MESSAGE);
4083         }
4084       }
4085     });
4086     chooser.showOpenDialog(this);
4087   }
4088
4089   public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4090   {
4091     return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4092   }
4093
4094   public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4095           int h, int x, int y)
4096   {
4097     return showNewickTree(nf, treeTitle, null, w, h, x, y);
4098   }
4099
4100   /**
4101    * Add a treeviewer for the tree extracted from a Newick file object to the
4102    * current alignment view
4103    * 
4104    * @param nf
4105    *          the tree
4106    * @param title
4107    *          tree viewer title
4108    * @param input
4109    *          Associated alignment input data (or null)
4110    * @param w
4111    *          width
4112    * @param h
4113    *          height
4114    * @param x
4115    *          position
4116    * @param y
4117    *          position
4118    * @return TreePanel handle
4119    */
4120   public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4121           AlignmentView input, int w, int h, int x, int y)
4122   {
4123     TreePanel tp = null;
4124
4125     try
4126     {
4127       nf.parse();
4128
4129       if (nf.getTree() != null)
4130       {
4131         tp = new TreePanel(alignPanel, nf, treeTitle, input);
4132         Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4133         if (dim == null)
4134         {
4135           dim = new Dimension(w, h);
4136         }
4137         else
4138         {
4139           // no offset, either
4140           x = 0;
4141         }
4142         tp.setSize(dim.width, dim.height);
4143
4144         if (x > 0 && y > 0)
4145         {
4146           tp.setLocation(x, y);
4147         }
4148
4149         Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4150       }
4151     } catch (Exception ex)
4152     {
4153       ex.printStackTrace();
4154     }
4155
4156     return tp;
4157   }
4158
4159   private boolean buildingMenu = false;
4160
4161   /**
4162    * Generates menu items and listener event actions for web service clients
4163    * 
4164    */
4165   public void BuildWebServiceMenu()
4166   {
4167     while (buildingMenu)
4168     {
4169       try
4170       {
4171         System.err.println("Waiting for building menu to finish.");
4172         Thread.sleep(10);
4173       } catch (Exception e)
4174       {
4175       }
4176     }
4177     final AlignFrame me = this;
4178     buildingMenu = true;
4179     new Thread(new Runnable()
4180     {
4181       @Override
4182       public void run()
4183       {
4184         final List<JMenuItem> legacyItems = new ArrayList<>();
4185         try
4186         {
4187           // System.err.println("Building ws menu again "
4188           // + Thread.currentThread());
4189           // TODO: add support for context dependent disabling of services based
4190           // on
4191           // alignment and current selection
4192           // TODO: add additional serviceHandle parameter to specify abstract
4193           // handler
4194           // class independently of AbstractName
4195           // TODO: add in rediscovery GUI function to restart discoverer
4196           // TODO: group services by location as well as function and/or
4197           // introduce
4198           // object broker mechanism.
4199           final Vector<JMenu> wsmenu = new Vector<>();
4200           final IProgressIndicator af = me;
4201
4202           /*
4203            * do not i18n these strings - they are hard-coded in class
4204            * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4205            * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4206            */
4207           final JMenu msawsmenu = new JMenu("Alignment");
4208           final JMenu secstrmenu = new JMenu(
4209                   "Secondary Structure Prediction");
4210           final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4211           final JMenu analymenu = new JMenu("Analysis");
4212           final JMenu dismenu = new JMenu("Protein Disorder");
4213           // JAL-940 - only show secondary structure prediction services from
4214           // the legacy server
4215           Hashtable<String, Vector<ServiceHandle>> services = Discoverer
4216                   .getInstance().getServices();
4217           if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4218           // &&
4219           services != null && (services.size() > 0))
4220           {
4221             // TODO: refactor to allow list of AbstractName/Handler bindings to
4222             // be
4223             // stored or retrieved from elsewhere
4224             // No MSAWS used any more:
4225             // Vector msaws = null; // (Vector)
4226             // Discoverer.services.get("MsaWS");
4227             Vector<ServiceHandle> secstrpr = services.get("SecStrPred");
4228             if (secstrpr != null)
4229             {
4230               // Add any secondary structure prediction services
4231               for (int i = 0, j = secstrpr.size(); i < j; i++)
4232               {
4233                 final ext.vamsas.ServiceHandle sh = secstrpr
4234                         .get(i);
4235                 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4236                         .getServiceClient(sh);
4237                 int p = secstrmenu.getItemCount();
4238                 impl.attachWSMenuEntry(secstrmenu, me);
4239                 int q = secstrmenu.getItemCount();
4240                 for (int litm = p; litm < q; litm++)
4241                 {
4242                   legacyItems.add(secstrmenu.getItem(litm));
4243                 }
4244               }
4245             }
4246           }
4247
4248           // Add all submenus in the order they should appear on the web
4249           // services menu
4250           wsmenu.add(msawsmenu);
4251           wsmenu.add(secstrmenu);
4252           wsmenu.add(dismenu);
4253           wsmenu.add(analymenu);
4254           // No search services yet
4255           // wsmenu.add(seqsrchmenu);
4256
4257           javax.swing.SwingUtilities.invokeLater(new Runnable()
4258           {
4259             @Override
4260             public void run()
4261             {
4262               try
4263               {
4264                 webService.removeAll();
4265                 // first, add discovered services onto the webservices menu
4266                 if (wsmenu.size() > 0)
4267                 {
4268                   for (int i = 0, j = wsmenu.size(); i < j; i++)
4269                   {
4270                     webService.add(wsmenu.get(i));
4271                   }
4272                 }
4273                 else
4274                 {
4275                   webService.add(me.webServiceNoServices);
4276                 }
4277                 // TODO: move into separate menu builder class.
4278                 // boolean new_sspred = false;
4279                 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4280                 {
4281                   Jws2Discoverer jws2servs = Jws2Discoverer.getInstance();
4282                   if (jws2servs != null)
4283                   {
4284                     if (jws2servs.hasServices())
4285                     {
4286                       jws2servs.attachWSMenuEntry(webService, me);
4287                       for (Jws2Instance sv : jws2servs.getServices())
4288                       {
4289                         if (sv.description.toLowerCase().contains("jpred"))
4290                         {
4291                           for (JMenuItem jmi : legacyItems)
4292                           {
4293                             jmi.setVisible(false);
4294                           }
4295                         }
4296                       }
4297
4298                     }
4299                     if (jws2servs.isRunning())
4300                     {
4301                       JMenuItem tm = new JMenuItem(
4302                               "Still discovering JABA Services");
4303                       tm.setEnabled(false);
4304                       webService.add(tm);
4305                     }
4306                   }
4307                 }
4308                 build_urlServiceMenu(me.webService);
4309                 build_fetchdbmenu(webService);
4310                 for (JMenu item : wsmenu)
4311                 {
4312                   if (item.getItemCount() == 0)
4313                   {
4314                     item.setEnabled(false);
4315                   }
4316                   else
4317                   {
4318                     item.setEnabled(true);
4319                   }
4320                 }
4321               } catch (Exception e)
4322               {
4323                 Cache.log.debug(
4324                         "Exception during web service menu building process.",
4325                         e);
4326               }
4327             }
4328           });
4329         } catch (Exception e)
4330         {
4331         }
4332         buildingMenu = false;
4333       }
4334     }).start();
4335
4336   }
4337
4338   /**
4339    * construct any groupURL type service menu entries.
4340    * 
4341    * @param webService
4342    */
4343   protected void build_urlServiceMenu(JMenu webService)
4344   {
4345     // TODO: remove this code when 2.7 is released
4346     // DEBUG - alignmentView
4347     /*
4348      * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4349      * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4350      * 
4351      * @Override public void actionPerformed(ActionEvent e) {
4352      * jalview.datamodel.AlignmentView
4353      * .testSelectionViews(af.viewport.getAlignment(),
4354      * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4355      * 
4356      * }); webService.add(testAlView);
4357      */
4358     // TODO: refactor to RestClient discoverer and merge menu entries for
4359     // rest-style services with other types of analysis/calculation service
4360     // SHmmr test client - still being implemented.
4361     // DEBUG - alignmentView
4362
4363     for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4364             .getRestClients())
4365     {
4366       client.attachWSMenuEntry(
4367               JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4368               this);
4369     }
4370   }
4371
4372   /**
4373    * Searches the alignment sequences for xRefs and builds the Show
4374    * Cross-References menu (formerly called Show Products), with database
4375    * sources for which cross-references are found (protein sources for a
4376    * nucleotide alignment and vice versa)
4377    * 
4378    * @return true if Show Cross-references menu should be enabled
4379    */
4380   public boolean canShowProducts()
4381   {
4382     SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4383     AlignmentI dataset = viewport.getAlignment().getDataset();
4384
4385     showProducts.removeAll();
4386     final boolean dna = viewport.getAlignment().isNucleotide();
4387
4388     if (seqs == null || seqs.length == 0)
4389     {
4390       // nothing to see here.
4391       return false;
4392     }
4393
4394     boolean showp = false;
4395     try
4396     {
4397       List<String> ptypes = new CrossRef(seqs, dataset)
4398               .findXrefSourcesForSequences(dna);
4399
4400       for (final String source : ptypes)
4401       {
4402         showp = true;
4403         final AlignFrame af = this;
4404         JMenuItem xtype = new JMenuItem(source);
4405         xtype.addActionListener(new ActionListener()
4406         {
4407           @Override
4408           public void actionPerformed(ActionEvent e)
4409           {
4410             showProductsFor(af.viewport.getSequenceSelection(), dna,
4411                     source);
4412           }
4413         });
4414         showProducts.add(xtype);
4415       }
4416       showProducts.setVisible(showp);
4417       showProducts.setEnabled(showp);
4418     } catch (Exception e)
4419     {
4420       Cache.log.warn(
4421               "canShowProducts threw an exception - please report to help@jalview.org",
4422               e);
4423       return false;
4424     }
4425     return showp;
4426   }
4427
4428   /**
4429    * Finds and displays cross-references for the selected sequences (protein
4430    * products for nucleotide sequences, dna coding sequences for peptides).
4431    * 
4432    * @param sel
4433    *          the sequences to show cross-references for
4434    * @param dna
4435    *          true if from a nucleotide alignment (so showing proteins)
4436    * @param source
4437    *          the database to show cross-references for
4438    */
4439   protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4440           final String source)
4441   {
4442     new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4443             .start();
4444   }
4445
4446   /**
4447    * Construct and display a new frame containing the translation of this
4448    * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4449    */
4450   @Override
4451   public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4452   {
4453     AlignmentI al = null;
4454     try
4455     {
4456       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4457
4458       al = dna.translateCdna(codeTable);
4459     } catch (Exception ex)
4460     {
4461       jalview.bin.Cache.log.error(
4462               "Exception during translation. Please report this !", ex);
4463       final String msg = MessageManager.getString(
4464               "label.error_when_translating_sequences_submit_bug_report");
4465       final String errorTitle = MessageManager
4466               .getString("label.implementation_error")
4467               + MessageManager.getString("label.translation_failed");
4468       JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg, errorTitle,
4469               JvOptionPane.ERROR_MESSAGE);
4470       return;
4471     }
4472     if (al == null || al.getHeight() == 0)
4473     {
4474       final String msg = MessageManager.getString(
4475               "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4476       final String errorTitle = MessageManager
4477               .getString("label.translation_failed");
4478       JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg, errorTitle,
4479               JvOptionPane.WARNING_MESSAGE);
4480     }
4481     else
4482     {
4483       AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4484       af.setFileFormat(this.currentFileFormat);
4485       final String newTitle = MessageManager
4486               .formatMessage("label.translation_of_params", new Object[]
4487               { this.getTitle(), codeTable.getId() });
4488       af.setTitle(newTitle);
4489       if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4490       {
4491         final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4492         AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4493       }
4494       else
4495       {
4496         Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4497                 DEFAULT_HEIGHT);
4498       }
4499     }
4500   }
4501
4502   /**
4503    * Set the file format
4504    * 
4505    * @param format
4506    */
4507   public void setFileFormat(FileFormatI format)
4508   {
4509     this.currentFileFormat = format;
4510   }
4511
4512   /**
4513    * Try to load a features file onto the alignment.
4514    * 
4515    * @param file
4516    *          contents or path to retrieve file or a File object
4517    * @param sourceType
4518    *          access mode of file (see jalview.io.AlignFile)
4519    * @return true if features file was parsed correctly.
4520    */
4521   public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4522   {
4523     // BH 2018
4524     return avc.parseFeaturesFile(file, sourceType,
4525             Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4526
4527   }
4528
4529   @Override
4530   public void refreshFeatureUI(boolean enableIfNecessary)
4531   {
4532     // note - currently this is only still here rather than in the controller
4533     // because of the featureSettings hard reference that is yet to be
4534     // abstracted
4535     if (enableIfNecessary)
4536     {
4537       viewport.setShowSequenceFeatures(true);
4538       showSeqFeatures.setSelected(true);
4539     }
4540
4541   }
4542
4543   @Override
4544   public void dragEnter(DropTargetDragEvent evt)
4545   {
4546   }
4547
4548   @Override
4549   public void dragExit(DropTargetEvent evt)
4550   {
4551   }
4552
4553   @Override
4554   public void dragOver(DropTargetDragEvent evt)
4555   {
4556   }
4557
4558   @Override
4559   public void dropActionChanged(DropTargetDragEvent evt)
4560   {
4561   }
4562
4563   @Override
4564   public void drop(DropTargetDropEvent evt)
4565   {
4566     // JAL-1552 - acceptDrop required before getTransferable call for
4567     // Java's Transferable for native dnd
4568     evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4569     Transferable t = evt.getTransferable();
4570
4571     final AlignFrame thisaf = this;
4572     final List<Object> files = new ArrayList<>();
4573     List<DataSourceType> protocols = new ArrayList<>();
4574
4575     try
4576     {
4577       Desktop.transferFromDropTarget(files, protocols, evt, t);
4578     } catch (Exception e)
4579     {
4580       e.printStackTrace();
4581     }
4582     if (files != null)
4583     {
4584       new Thread(new Runnable()
4585       {
4586         @Override
4587         public void run()
4588         {
4589           try
4590           {
4591             // check to see if any of these files have names matching sequences
4592             // in
4593             // the alignment
4594             SequenceIdMatcher idm = new SequenceIdMatcher(
4595                     viewport.getAlignment().getSequencesArray());
4596             /**
4597              * Object[] { String,SequenceI}
4598              */
4599             ArrayList<Object[]> filesmatched = new ArrayList<>();
4600             ArrayList<Object> filesnotmatched = new ArrayList<>();
4601             for (int i = 0; i < files.size(); i++)
4602             {
4603               // BH 2018
4604               Object file = files.get(i);
4605               String fileName = file.toString();
4606               String pdbfn = "";
4607               DataSourceType protocol = (file instanceof File
4608                       ? DataSourceType.FILE
4609                       : FormatAdapter.checkProtocol(fileName));
4610               if (protocol == DataSourceType.FILE)
4611               {
4612                 File fl;
4613                 if (file instanceof File) {
4614                   fl = (File) file;
4615                   Platform.cacheFileData(fl);
4616                 } else {
4617                   fl = new File(fileName);
4618                 }
4619                 pdbfn = fl.getName();
4620               }
4621               else if (protocol == DataSourceType.URL)
4622               {
4623                 URL url = new URL(fileName);
4624                 pdbfn = url.getFile();
4625               }
4626               if (pdbfn.length() > 0)
4627               {
4628                 // attempt to find a match in the alignment
4629                 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4630                 int l = 0, c = pdbfn.indexOf(".");
4631                 while (mtch == null && c != -1)
4632                 {
4633                   do
4634                   {
4635                     l = c;
4636                   } while ((c = pdbfn.indexOf(".", l)) > l);
4637                   if (l > -1)
4638                   {
4639                     pdbfn = pdbfn.substring(0, l);
4640                   }
4641                   mtch = idm.findAllIdMatches(pdbfn);
4642                 }
4643                 if (mtch != null)
4644                 {
4645                   FileFormatI type;
4646                   try
4647                   {
4648                     type = new IdentifyFile().identify(file, protocol);
4649                   } catch (Exception ex)
4650                   {
4651                     type = null;
4652                   }
4653                   if (type != null && type.isStructureFile())
4654                   {
4655                     filesmatched.add(new Object[] { file, protocol, mtch });
4656                     continue;
4657                   }
4658                 }
4659                 // File wasn't named like one of the sequences or wasn't a PDB
4660                 // file.
4661                 filesnotmatched.add(file);
4662               }
4663             }
4664             int assocfiles = 0;
4665             if (filesmatched.size() > 0)
4666             {
4667               boolean autoAssociate = Cache
4668                       .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
4669               if (!autoAssociate)
4670               {
4671                 String msg = MessageManager.formatMessage(
4672                         "label.automatically_associate_structure_files_with_sequences_same_name",
4673                         new Object[]
4674                         { Integer.valueOf(filesmatched.size())
4675                                 .toString() });
4676                 String ttl = MessageManager.getString(
4677                         "label.automatically_associate_structure_files_by_name");
4678                 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4679                         ttl, JvOptionPane.YES_NO_OPTION);
4680                 autoAssociate = choice == JvOptionPane.YES_OPTION;
4681               }
4682               if (autoAssociate)
4683               {
4684                 for (Object[] fm : filesmatched)
4685                 {
4686                   // try and associate
4687                   // TODO: may want to set a standard ID naming formalism for
4688                   // associating PDB files which have no IDs.
4689                   for (SequenceI toassoc : (SequenceI[]) fm[2])
4690                   {
4691                     PDBEntry pe = AssociatePdbFileWithSeq
4692                             .associatePdbWithSeq(fm[0].toString(),
4693                                     (DataSourceType) fm[1], toassoc, false);
4694                     if (pe != null)
4695                     {
4696                       System.err.println("Associated file : "
4697                               + (fm[0].toString()) + " with "
4698                               + toassoc.getDisplayId(true));
4699                       assocfiles++;
4700                     }
4701                   }
4702                   // TODO: do we need to update overview ? only if features are
4703                   // shown I guess
4704                   alignPanel.paintAlignment(true, false);
4705                 }
4706               }
4707               else
4708               {
4709                 /*
4710                  * add declined structures as sequences
4711                  */
4712                 for (Object[] o : filesmatched)
4713                 {
4714                   filesnotmatched.add(o[0]);
4715                 }
4716               }
4717             }
4718             if (filesnotmatched.size() > 0)
4719             {
4720               if (assocfiles > 0 && (Cache.getDefault(
4721                       "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4722                       || JvOptionPane.showConfirmDialog(thisaf,
4723                               "<html>" + MessageManager.formatMessage(
4724                                       "label.ignore_unmatched_dropped_files_info",
4725                                       new Object[]
4726                                       { Integer.valueOf(
4727                                               filesnotmatched.size())
4728                                               .toString() })
4729                                       + "</html>",
4730                               MessageManager.getString(
4731                                       "label.ignore_unmatched_dropped_files"),
4732                               JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4733               {
4734                 return;
4735               }
4736               for (Object fn : filesnotmatched)
4737               {
4738                 loadJalviewDataFile(fn, null, null, null);
4739               }
4740
4741             }
4742           } catch (Exception ex)
4743           {
4744             ex.printStackTrace();
4745           }
4746         }
4747       }).start();
4748     }
4749   }
4750
4751   /**
4752    * Attempt to load a "dropped" file or URL string, by testing in turn for
4753    * <ul>
4754    * <li>an Annotation file</li>
4755    * <li>a JNet file</li>
4756    * <li>a features file</li>
4757    * <li>else try to interpret as an alignment file</li>
4758    * </ul>
4759    * 
4760    * @param file
4761    *          either a filename or a URL string.
4762    */
4763   public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4764           FileFormatI format, SequenceI assocSeq)
4765   {
4766     // BH 2018 was String file
4767     try
4768     {
4769       if (sourceType == null)
4770       {
4771         sourceType = FormatAdapter.checkProtocol(file);
4772       }
4773       // if the file isn't identified, or not positively identified as some
4774       // other filetype (PFAM is default unidentified alignment file type) then
4775       // try to parse as annotation.
4776       boolean isAnnotation = (format == null
4777               || FileFormat.Pfam.equals(format))
4778                       ? new AnnotationFile().annotateAlignmentView(viewport,
4779                               file, sourceType)
4780                       : false;
4781
4782       if (!isAnnotation)
4783       {
4784         // first see if its a T-COFFEE score file
4785         TCoffeeScoreFile tcf = null;
4786         try
4787         {
4788           tcf = new TCoffeeScoreFile(file, sourceType);
4789           if (tcf.isValid())
4790           {
4791             if (tcf.annotateAlignment(viewport.getAlignment(), true))
4792             {
4793               buildColourMenu();
4794               changeColour(
4795                       new TCoffeeColourScheme(viewport.getAlignment()));
4796               isAnnotation = true;
4797               setStatus(MessageManager.getString(
4798                       "label.successfully_pasted_tcoffee_scores_to_alignment"));
4799             }
4800             else
4801             {
4802               // some problem - if no warning its probable that the ID matching
4803               // process didn't work
4804               JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4805                       tcf.getWarningMessage() == null
4806                               ? MessageManager.getString(
4807                                       "label.check_file_matches_sequence_ids_alignment")
4808                               : tcf.getWarningMessage(),
4809                       MessageManager.getString(
4810                               "label.problem_reading_tcoffee_score_file"),
4811                       JvOptionPane.WARNING_MESSAGE);
4812             }
4813           }
4814           else
4815           {
4816             tcf = null;
4817           }
4818         } catch (Exception x)
4819         {
4820           Cache.log.debug(
4821                   "Exception when processing data source as T-COFFEE score file",
4822                   x);
4823           tcf = null;
4824         }
4825         if (tcf == null)
4826         {
4827           // try to see if its a JNet 'concise' style annotation file *before*
4828           // we
4829           // try to parse it as a features file
4830           if (format == null)
4831           {
4832             format = new IdentifyFile().identify(file, sourceType);
4833           }
4834           if (FileFormat.ScoreMatrix == format)
4835           {
4836             ScoreMatrixFile sm = new ScoreMatrixFile(
4837                     new FileParse(file, sourceType));
4838             sm.parse();
4839             // todo: i18n this message
4840             setStatus(MessageManager.formatMessage(
4841                     "label.successfully_loaded_matrix",
4842                     sm.getMatrixName()));
4843           }
4844           else if (FileFormat.Jnet.equals(format))
4845           {
4846             JPredFile predictions = new JPredFile(file, sourceType);
4847             new JnetAnnotationMaker();
4848             JnetAnnotationMaker.add_annotation(predictions,
4849                     viewport.getAlignment(), 0, false);
4850             viewport.getAlignment().setupJPredAlignment();
4851             isAnnotation = true;
4852           }
4853           // else if (IdentifyFile.FeaturesFile.equals(format))
4854           else if (FileFormat.Features.equals(format))
4855           {
4856             if (parseFeaturesFile(file, sourceType))
4857             {
4858               alignPanel.paintAlignment(true, true);
4859             }
4860           }
4861           else
4862           {
4863             new FileLoader().loadFile(viewport, file, sourceType, format);
4864           }
4865         }
4866       }
4867       if (isAnnotation)
4868       {
4869         updateForAnnotations();
4870       }
4871     } catch (Exception ex)
4872     {
4873       ex.printStackTrace();
4874     } catch (OutOfMemoryError oom)
4875     {
4876       try
4877       {
4878         System.gc();
4879       } catch (Exception x)
4880       {
4881       }
4882       new OOMWarning(
4883               "loading data "
4884                       + (sourceType != null
4885                               ? (sourceType == DataSourceType.PASTE
4886                                       ? "from clipboard."
4887                                       : "using " + sourceType + " from "
4888                                               + file)
4889                               : ".")
4890                       + (format != null
4891                               ? "(parsing as '" + format + "' file)"
4892                               : ""),
4893               oom, Desktop.getDesktopPane());
4894     }
4895   }
4896
4897   /**
4898    * Do all updates necessary after an annotation file such as jnet. Also called
4899    * from Jalview.loadAppletParams for "annotations", "jnetFile"
4900    */
4901   public void updateForAnnotations()
4902   {
4903     alignPanel.adjustAnnotationHeight();
4904     viewport.updateSequenceIdColours();
4905     buildSortByAnnotationScoresMenu();
4906     alignPanel.paintAlignment(true, true);
4907   }
4908
4909   /**
4910    * Method invoked by the ChangeListener on the tabbed pane, in other words
4911    * when a different tabbed pane is selected by the user or programmatically.
4912    */
4913   @Override
4914   public void tabSelectionChanged(int index)
4915   {
4916     if (index > -1)
4917     {
4918       alignPanel = alignPanels.get(index);
4919       viewport = alignPanel.av;
4920       avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4921       setMenusFromViewport(viewport);
4922     }
4923
4924     /*
4925      * 'focus' any colour slider that is open to the selected viewport
4926      */
4927     if (viewport.getConservationSelected())
4928     {
4929       SliderPanel.setConservationSlider(alignPanel,
4930               viewport.getResidueShading(), alignPanel.getViewName());
4931     }
4932     else
4933     {
4934       SliderPanel.hideConservationSlider();
4935     }
4936     if (viewport.getAbovePIDThreshold())
4937     {
4938       SliderPanel.setPIDSliderSource(alignPanel,
4939               viewport.getResidueShading(), alignPanel.getViewName());
4940     }
4941     else
4942     {
4943       SliderPanel.hidePIDSlider();
4944     }
4945
4946     /*
4947      * If there is a frame linked to this one in a SplitPane, switch it to the
4948      * same view tab index. No infinite recursion of calls should happen, since
4949      * tabSelectionChanged() should not get invoked on setting the selected
4950      * index to an unchanged value. Guard against setting an invalid index
4951      * before the new view peer tab has been created.
4952      */
4953     final AlignViewportI peer = viewport.getCodingComplement();
4954     if (peer != null)
4955     {
4956       AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4957               .getAlignPanel().alignFrame;
4958       if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4959       {
4960         linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4961       }
4962     }
4963   }
4964
4965   /**
4966    * On right mouse click on view tab, prompt for and set new view name.
4967    */
4968   @Override
4969   public void tabbedPane_mousePressed(MouseEvent e)
4970   {
4971     if (e.isPopupTrigger())
4972     {
4973       String msg = MessageManager.getString("label.enter_view_name");
4974       String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4975       String reply = JvOptionPane.showInputDialog(msg, ttl);
4976
4977       if (reply != null)
4978       {
4979         viewport.setViewName(reply);
4980         // TODO warn if reply is in getExistingViewNames()?
4981         tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4982       }
4983     }
4984   }
4985
4986   public AlignViewport getCurrentView()
4987   {
4988     return viewport;
4989   }
4990
4991   /**
4992    * Change the display state for the given feature groups -- Added by BH from
4993    * JalviewLite
4994    * 
4995    * @param groups
4996    *          list of group strings
4997    * @param state
4998    *          visible or invisible
4999    */
5000   public void setFeatureGroupState(String[] groups, boolean state)
5001   {
5002     jalview.api.FeatureRenderer fr = null;
5003     viewport.setShowSequenceFeatures(true);
5004     if (alignPanel != null
5005             && (fr = alignPanel.getFeatureRenderer()) != null)
5006     {
5007
5008       fr.setGroupVisibility(Arrays.asList(groups), state);
5009       alignPanel.getSeqPanel().seqCanvas.repaint();
5010       if (alignPanel.overviewPanel != null)
5011       {
5012         alignPanel.overviewPanel.updateOverviewImage();
5013       }
5014     }
5015   }
5016
5017   /**
5018    * Open the dialog for regex description parsing.
5019    */
5020   @Override
5021   protected void extractScores_actionPerformed(ActionEvent e)
5022   {
5023     ParseProperties pp = new jalview.analysis.ParseProperties(
5024             viewport.getAlignment());
5025     // TODO: verify regex and introduce GUI dialog for version 2.5
5026     // if (pp.getScoresFromDescription("col", "score column ",
5027     // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5028     // true)>0)
5029     if (pp.getScoresFromDescription("description column",
5030             "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5031     {
5032       buildSortByAnnotationScoresMenu();
5033     }
5034   }
5035
5036   /*
5037    * (non-Javadoc)
5038    * 
5039    * @see
5040    * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5041    * )
5042    */
5043   @Override
5044   protected void showDbRefs_actionPerformed(ActionEvent e)
5045   {
5046     viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5047   }
5048
5049   /*
5050    * (non-Javadoc)
5051    * 
5052    * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5053    * ActionEvent)
5054    */
5055   @Override
5056   protected void showNpFeats_actionPerformed(ActionEvent e)
5057   {
5058     viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5059   }
5060
5061   /**
5062    * find the viewport amongst the tabs in this alignment frame and close that
5063    * tab
5064    * 
5065    * @param av
5066    */
5067   public boolean closeView(AlignViewportI av)
5068   {
5069     if (viewport == av)
5070     {
5071       this.closeMenuItem_actionPerformed(false);
5072       return true;
5073     }
5074     Component[] comp = tabbedPane.getComponents();
5075     for (int i = 0; comp != null && i < comp.length; i++)
5076     {
5077       if (comp[i] instanceof AlignmentPanel)
5078       {
5079         if (((AlignmentPanel) comp[i]).av == av)
5080         {
5081           // close the view.
5082           closeView((AlignmentPanel) comp[i]);
5083           return true;
5084         }
5085       }
5086     }
5087     return false;
5088   }
5089
5090   protected void build_fetchdbmenu(JMenu webService)
5091   {
5092     // Temporary hack - DBRef Fetcher always top level ws entry.
5093     // TODO We probably want to store a sequence database checklist in
5094     // preferences and have checkboxes.. rather than individual sources selected
5095     // here
5096     final JMenu rfetch = new JMenu(
5097             MessageManager.getString("action.fetch_db_references"));
5098     rfetch.setToolTipText(MessageManager.getString(
5099             "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5100     webService.add(rfetch);
5101
5102     final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5103             MessageManager.getString("option.trim_retrieved_seqs"));
5104     trimrs.setToolTipText(
5105             MessageManager.getString("label.trim_retrieved_sequences"));
5106     trimrs.setSelected(
5107             Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5108     trimrs.addActionListener(new ActionListener()
5109     {
5110       @Override
5111       public void actionPerformed(ActionEvent e)
5112       {
5113         trimrs.setSelected(trimrs.isSelected());
5114         Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5115                 Boolean.valueOf(trimrs.isSelected()).toString());
5116       }
5117     });
5118     rfetch.add(trimrs);
5119     JMenuItem fetchr = new JMenuItem(
5120             MessageManager.getString("label.standard_databases"));
5121     fetchr.setToolTipText(
5122             MessageManager.getString("label.fetch_embl_uniprot"));
5123     fetchr.addActionListener(new ActionListener()
5124     {
5125
5126       @Override
5127       public void actionPerformed(ActionEvent e)
5128       {
5129         new Thread(new Runnable()
5130         {
5131           @Override
5132           public void run()
5133           {
5134             boolean isNucleotide = alignPanel.alignFrame.getViewport()
5135                     .getAlignment().isNucleotide();
5136             DBRefFetcher dbRefFetcher = new DBRefFetcher(
5137                     alignPanel.av.getSequenceSelection(),
5138                     alignPanel.alignFrame, null,
5139                     alignPanel.alignFrame.featureSettings, isNucleotide);
5140             dbRefFetcher.addListener(new FetchFinishedListenerI()
5141             {
5142               @Override
5143               public void finished()
5144               {
5145                 AlignFrame.this.setMenusForViewport();
5146               }
5147             });
5148             dbRefFetcher.fetchDBRefs(false);
5149           }
5150         }).start();
5151
5152       }
5153
5154     });
5155     rfetch.add(fetchr);
5156     new Thread(new Runnable()
5157     {
5158       @Override
5159       public void run()
5160       {
5161         javax.swing.SwingUtilities.invokeLater(new Runnable()
5162         {
5163           @Override
5164           public void run()
5165           {
5166             String[] dbclasses = jalview.ws.SequenceFetcher.getInstance()
5167                     .getNonAlignmentSources();
5168             List<DbSourceProxy> otherdb;
5169             JMenu dfetch = new JMenu();
5170             JMenu ifetch = new JMenu();
5171             JMenuItem fetchr = null;
5172             int comp = 0, icomp = 0, mcomp = 15;
5173             String mname = null;
5174             int dbi = 0;
5175             for (String dbclass : dbclasses)
5176             {
5177               otherdb = jalview.ws.SequenceFetcher.getInstance()
5178                       .getSourceProxy(dbclass);
5179               // add a single entry for this class, or submenu allowing 'fetch
5180               // all' or pick one
5181               if (otherdb == null || otherdb.size() < 1)
5182               {
5183                 continue;
5184               }
5185               if (mname == null)
5186               {
5187                 mname = "From " + dbclass;
5188               }
5189               if (otherdb.size() == 1)
5190               {
5191                 DbSourceProxy src = otherdb.get(0);
5192                 DbSourceProxy[] dassource = new DbSourceProxy[] {
5193                     src };
5194                 fetchr = new JMenuItem(src.getDbSource());
5195                 fetchr.addActionListener(new ActionListener()
5196                 {
5197
5198                   @Override
5199                   public void actionPerformed(ActionEvent e)
5200                   {
5201                     new Thread(new Runnable()
5202                     {
5203
5204                       @Override
5205                       public void run()
5206                       {
5207                         boolean isNucleotide = alignPanel.alignFrame
5208                                 .getViewport().getAlignment()
5209                                 .isNucleotide();
5210                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5211                                 alignPanel.av.getSequenceSelection(),
5212                                 alignPanel.alignFrame, dassource,
5213                                 alignPanel.alignFrame.featureSettings,
5214                                 isNucleotide);
5215                         dbRefFetcher
5216                                 .addListener(new FetchFinishedListenerI()
5217                                 {
5218                                   @Override
5219                                   public void finished()
5220                                   {
5221                                     AlignFrame.this.setMenusForViewport();
5222                                   }
5223                                 });
5224                         dbRefFetcher.fetchDBRefs(false);
5225                       }
5226                     }).start();
5227                   }
5228
5229                 });
5230                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5231                         MessageManager.formatMessage(
5232                                 "label.fetch_retrieve_from", new Object[]
5233                                 { src.getDbName() })));
5234                 dfetch.add(fetchr);
5235                 comp++;
5236               }
5237               else
5238               {
5239                 final DbSourceProxy[] dassource = otherdb
5240                         .toArray(new DbSourceProxy[0]);
5241                 // fetch all entry
5242                 DbSourceProxy src = otherdb.get(0);
5243                 fetchr = new JMenuItem(MessageManager
5244                         .formatMessage("label.fetch_all_param", new Object[]
5245                         { src.getDbSource() }));
5246                 fetchr.addActionListener(new ActionListener()
5247                 {
5248                   @Override
5249                   public void actionPerformed(ActionEvent e)
5250                   {
5251                     new Thread(new Runnable()
5252                     {
5253
5254                       @Override
5255                       public void run()
5256                       {
5257                         boolean isNucleotide = alignPanel.alignFrame
5258                                 .getViewport().getAlignment()
5259                                 .isNucleotide();
5260                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5261                                 alignPanel.av.getSequenceSelection(),
5262                                 alignPanel.alignFrame, dassource,
5263                                 alignPanel.alignFrame.featureSettings,
5264                                 isNucleotide);
5265                         dbRefFetcher
5266                                 .addListener(new FetchFinishedListenerI()
5267                                 {
5268                                   @Override
5269                                   public void finished()
5270                                   {
5271                                     AlignFrame.this.setMenusForViewport();
5272                                   }
5273                                 });
5274                         dbRefFetcher.fetchDBRefs(false);
5275                       }
5276                     }).start();
5277                   }
5278                 });
5279
5280                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5281                         MessageManager.formatMessage(
5282                                 "label.fetch_retrieve_from_all_sources",
5283                                 new Object[]
5284                                 { Integer.valueOf(otherdb.size())
5285                                         .toString(),
5286                                     src.getDbSource(), src.getDbName() })));
5287                 dfetch.add(fetchr);
5288                 comp++;
5289                 // and then build the rest of the individual menus
5290                 ifetch = new JMenu(MessageManager.formatMessage(
5291                         "label.source_from_db_source", new Object[]
5292                         { src.getDbSource() }));
5293                 icomp = 0;
5294                 String imname = null;
5295                 int i = 0;
5296                 for (DbSourceProxy sproxy : otherdb)
5297                 {
5298                   String dbname = sproxy.getDbName();
5299                   String sname = dbname.length() > 5
5300                           ? dbname.substring(0, 5) + "..."
5301                           : dbname;
5302                   String msname = dbname.length() > 10
5303                           ? dbname.substring(0, 10) + "..."
5304                           : dbname;
5305                   if (imname == null)
5306                   {
5307                     imname = MessageManager
5308                             .formatMessage("label.from_msname", new Object[]
5309                             { sname });
5310                   }
5311                   fetchr = new JMenuItem(msname);
5312                   final DbSourceProxy[] dassrc = { sproxy };
5313                   fetchr.addActionListener(new ActionListener()
5314                   {
5315
5316                     @Override
5317                     public void actionPerformed(ActionEvent e)
5318                     {
5319                       new Thread(new Runnable()
5320                       {
5321
5322                         @Override
5323                         public void run()
5324                         {
5325                           boolean isNucleotide = alignPanel.alignFrame
5326                                   .getViewport().getAlignment()
5327                                   .isNucleotide();
5328                           DBRefFetcher dbRefFetcher = new DBRefFetcher(
5329                                   alignPanel.av.getSequenceSelection(),
5330                                   alignPanel.alignFrame, dassrc,
5331                                   alignPanel.alignFrame.featureSettings,
5332                                   isNucleotide);
5333                           dbRefFetcher
5334                                   .addListener(new FetchFinishedListenerI()
5335                                   {
5336                                     @Override
5337                                     public void finished()
5338                                     {
5339                                       AlignFrame.this.setMenusForViewport();
5340                                     }
5341                                   });
5342                           dbRefFetcher.fetchDBRefs(false);
5343                         }
5344                       }).start();
5345                     }
5346
5347                   });
5348                   fetchr.setToolTipText(
5349                           "<html>" + MessageManager.formatMessage(
5350                                   "label.fetch_retrieve_from", new Object[]
5351                                   { dbname }));
5352                   ifetch.add(fetchr);
5353                   ++i;
5354                   if (++icomp >= mcomp || i == (otherdb.size()))
5355                   {
5356                     ifetch.setText(MessageManager.formatMessage(
5357                             "label.source_to_target", imname, sname));
5358                     dfetch.add(ifetch);
5359                     ifetch = new JMenu();
5360                     imname = null;
5361                     icomp = 0;
5362                     comp++;
5363                   }
5364                 }
5365               }
5366               ++dbi;
5367               if (comp >= mcomp || dbi >= (dbclasses.length))
5368               {
5369                 dfetch.setText(MessageManager.formatMessage(
5370                         "label.source_to_target", mname, dbclass));
5371                 rfetch.add(dfetch);
5372                 dfetch = new JMenu();
5373                 mname = null;
5374                 comp = 0;
5375               }
5376             }
5377           }
5378         });
5379       }
5380     }).start();
5381
5382   }
5383
5384   /**
5385    * Left justify the whole alignment.
5386    */
5387   @Override
5388   protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5389   {
5390     AlignmentI al = viewport.getAlignment();
5391     al.justify(false);
5392     viewport.firePropertyChange("alignment", null, al);
5393   }
5394
5395   /**
5396    * Right justify the whole alignment.
5397    */
5398   @Override
5399   protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5400   {
5401     AlignmentI al = viewport.getAlignment();
5402     al.justify(true);
5403     viewport.firePropertyChange("alignment", null, al);
5404   }
5405
5406   @Override
5407   public void setShowSeqFeatures(boolean b)
5408   {
5409     showSeqFeatures.setSelected(b);
5410     viewport.setShowSequenceFeatures(b);
5411   }
5412
5413   /*
5414    * (non-Javadoc)
5415    * 
5416    * @see
5417    * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5418    * awt.event.ActionEvent)
5419    */
5420   @Override
5421   protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5422   {
5423     viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5424     alignPanel.paintAlignment(false, false);
5425   }
5426
5427   /*
5428    * (non-Javadoc)
5429    * 
5430    * @see
5431    * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5432    * .ActionEvent)
5433    */
5434   @Override
5435   protected void showGroupConsensus_actionPerformed(ActionEvent e)
5436   {
5437     viewport.setShowGroupConsensus(showGroupConsensus.getState());
5438     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5439
5440   }
5441
5442   /*
5443    * (non-Javadoc)
5444    * 
5445    * @see
5446    * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5447    * .event.ActionEvent)
5448    */
5449   @Override
5450   protected void showGroupConservation_actionPerformed(ActionEvent e)
5451   {
5452     viewport.setShowGroupConservation(showGroupConservation.getState());
5453     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5454   }
5455
5456   /*
5457    * (non-Javadoc)
5458    * 
5459    * @see
5460    * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5461    * .event.ActionEvent)
5462    */
5463   @Override
5464   protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5465   {
5466     viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5467     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5468   }
5469
5470   /*
5471    * (non-Javadoc)
5472    * 
5473    * @see
5474    * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5475    * .event.ActionEvent)
5476    */
5477   @Override
5478   protected void showSequenceLogo_actionPerformed(ActionEvent e)
5479   {
5480     viewport.setShowSequenceLogo(showSequenceLogo.getState());
5481     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5482   }
5483
5484   @Override
5485   protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5486   {
5487     showSequenceLogo.setState(true);
5488     viewport.setShowSequenceLogo(true);
5489     viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5490     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5491   }
5492
5493   @Override
5494   protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5495   {
5496     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5497   }
5498
5499   /*
5500    * (non-Javadoc)
5501    * 
5502    * @see
5503    * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5504    * .event.ActionEvent)
5505    */
5506   @Override
5507   protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5508   {
5509     if (avc.makeGroupsFromSelection())
5510     {
5511       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5512       alignPanel.updateAnnotation();
5513       alignPanel.paintAlignment(true,
5514               viewport.needToUpdateStructureViews());
5515     }
5516   }
5517
5518   public void clearAlignmentSeqRep()
5519   {
5520     // TODO refactor alignmentseqrep to controller
5521     if (viewport.getAlignment().hasSeqrep())
5522     {
5523       viewport.getAlignment().setSeqrep(null);
5524       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5525       alignPanel.updateAnnotation();
5526       alignPanel.paintAlignment(true, true);
5527     }
5528   }
5529
5530   @Override
5531   protected void createGroup_actionPerformed(ActionEvent e)
5532   {
5533     if (avc.createGroup())
5534     {
5535       if (applyAutoAnnotationSettings.isSelected())
5536       {
5537         alignPanel.updateAnnotation(true, false);
5538       }
5539       alignPanel.alignmentChanged();
5540     }
5541   }
5542
5543   @Override
5544   protected void unGroup_actionPerformed(ActionEvent e)
5545   {
5546     if (avc.unGroup())
5547     {
5548       alignPanel.alignmentChanged();
5549     }
5550   }
5551
5552   /**
5553    * make the given alignmentPanel the currently selected tab
5554    * 
5555    * @param alignmentPanel
5556    */
5557   public void setDisplayedView(AlignmentPanel alignmentPanel)
5558   {
5559     if (!viewport.getSequenceSetId()
5560             .equals(alignmentPanel.av.getSequenceSetId()))
5561     {
5562       throw new Error(MessageManager.getString(
5563               "error.implementation_error_cannot_show_view_alignment_frame"));
5564     }
5565     if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5566             .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5567     {
5568       tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5569     }
5570   }
5571
5572   /**
5573    * Action on selection of menu options to Show or Hide annotations.
5574    * 
5575    * @param visible
5576    * @param forSequences
5577    *          update sequence-related annotations
5578    * @param forAlignment
5579    *          update non-sequence-related annotations
5580    */
5581   @Override
5582   protected void setAnnotationsVisibility(boolean visible,
5583           boolean forSequences, boolean forAlignment)
5584   {
5585     AlignmentAnnotation[] anns = alignPanel.getAlignment()
5586             .getAlignmentAnnotation();
5587     if (anns == null)
5588     {
5589       return;
5590     }
5591     for (AlignmentAnnotation aa : anns)
5592     {
5593       /*
5594        * don't display non-positional annotations on an alignment
5595        */
5596       if (aa.annotations == null)
5597       {
5598         continue;
5599       }
5600       boolean apply = (aa.sequenceRef == null && forAlignment)
5601               || (aa.sequenceRef != null && forSequences);
5602       if (apply)
5603       {
5604         aa.visible = visible;
5605       }
5606     }
5607     alignPanel.validateAnnotationDimensions(true);
5608     alignPanel.alignmentChanged();
5609   }
5610
5611   /**
5612    * Store selected annotation sort order for the view and repaint.
5613    */
5614   @Override
5615   protected void sortAnnotations_actionPerformed()
5616   {
5617     this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5618     this.alignPanel.av
5619             .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5620     alignPanel.paintAlignment(false, false);
5621   }
5622
5623   /**
5624    * 
5625    * @return alignment panels in this alignment frame
5626    */
5627   public List<? extends AlignmentViewPanel> getAlignPanels()
5628   {
5629     // alignPanels is never null
5630     // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5631     return alignPanels;
5632   }
5633
5634   /**
5635    * Open a new alignment window, with the cDNA associated with this (protein)
5636    * alignment, aligned as is the protein.
5637    */
5638   protected void viewAsCdna_actionPerformed()
5639   {
5640     // TODO no longer a menu action - refactor as required
5641     final AlignmentI alignment = getViewport().getAlignment();
5642     List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5643     if (mappings == null)
5644     {
5645       return;
5646     }
5647     List<SequenceI> cdnaSeqs = new ArrayList<>();
5648     for (SequenceI aaSeq : alignment.getSequences())
5649     {
5650       for (AlignedCodonFrame acf : mappings)
5651       {
5652         SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5653         if (dnaSeq != null)
5654         {
5655           /*
5656            * There is a cDNA mapping for this protein sequence - add to new
5657            * alignment. It will share the same dataset sequence as other mapped
5658            * cDNA (no new mappings need to be created).
5659            */
5660           final Sequence newSeq = new Sequence(dnaSeq);
5661           newSeq.setDatasetSequence(dnaSeq);
5662           cdnaSeqs.add(newSeq);
5663         }
5664       }
5665     }
5666     if (cdnaSeqs.size() == 0)
5667     {
5668       // show a warning dialog no mapped cDNA
5669       return;
5670     }
5671     AlignmentI cdna = new Alignment(
5672             cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5673     GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5674             AlignFrame.DEFAULT_HEIGHT);
5675     cdna.alignAs(alignment);
5676     String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5677             + this.title;
5678     Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5679             AlignFrame.DEFAULT_HEIGHT);
5680   }
5681
5682   /**
5683    * Set visibility of dna/protein complement view (available when shown in a
5684    * split frame).
5685    * 
5686    * @param show
5687    */
5688   @Override
5689   protected void showComplement_actionPerformed(boolean show)
5690   {
5691     SplitContainerI sf = getSplitViewContainer();
5692     if (sf != null)
5693     {
5694       sf.setComplementVisible(this, show);
5695     }
5696   }
5697
5698   /**
5699    * Generate the reverse (optionally complemented) of the selected sequences,
5700    * and add them to the alignment
5701    */
5702   @Override
5703   protected void showReverse_actionPerformed(boolean complement)
5704   {
5705     AlignmentI al = null;
5706     try
5707     {
5708       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5709       al = dna.reverseCdna(complement);
5710       viewport.addAlignment(al, "");
5711       addHistoryItem(new EditCommand(
5712               MessageManager.getString("label.add_sequences"), Action.PASTE,
5713               al.getSequencesArray(), 0, al.getWidth(),
5714               viewport.getAlignment()));
5715     } catch (Exception ex)
5716     {
5717       System.err.println(ex.getMessage());
5718       return;
5719     }
5720   }
5721
5722   /**
5723    * Try to run a script in the Groovy console, having first ensured that this
5724    * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5725    * be targeted at this alignment.
5726    */
5727   @Override
5728   protected void runGroovy_actionPerformed()
5729   {
5730     Jalview.setCurrentAlignFrame(this);
5731     groovy.ui.Console console = Desktop.getGroovyConsole();
5732     if (console != null)
5733     {
5734       try
5735       {
5736         console.runScript();
5737       } catch (Exception ex)
5738       {
5739         System.err.println((ex.toString()));
5740         JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
5741                 MessageManager.getString("label.couldnt_run_groovy_script"),
5742                 MessageManager.getString("label.groovy_support_failed"),
5743                 JvOptionPane.ERROR_MESSAGE);
5744       }
5745     }
5746     else
5747     {
5748       System.err.println("Can't run Groovy script as console not found");
5749     }
5750   }
5751
5752   /**
5753    * Hides columns containing (or not containing) a specified feature, provided
5754    * that would not leave all columns hidden
5755    * 
5756    * @param featureType
5757    * @param columnsContaining
5758    * @return
5759    */
5760   public boolean hideFeatureColumns(String featureType,
5761           boolean columnsContaining)
5762   {
5763     boolean notForHiding = avc.markColumnsContainingFeatures(
5764             columnsContaining, false, false, featureType);
5765     if (notForHiding)
5766     {
5767       if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5768               false, featureType))
5769       {
5770         getViewport().hideSelectedColumns();
5771         return true;
5772       }
5773     }
5774     return false;
5775   }
5776
5777   @Override
5778   protected void selectHighlightedColumns_actionPerformed(
5779           ActionEvent actionEvent)
5780   {
5781     // include key modifier check in case user selects from menu
5782     avc.markHighlightedColumns(
5783             (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5784             (actionEvent.getModifiers() & (ActionEvent.META_MASK
5785                     | ActionEvent.CTRL_MASK)) != 0);
5786   }
5787
5788   /**
5789    * Rebuilds the Colour menu, including any user-defined colours which have
5790    * been loaded either on startup or during the session
5791    */
5792   public void buildColourMenu()
5793   {
5794     colourMenu.removeAll();
5795
5796     colourMenu.add(applyToAllGroups);
5797     colourMenu.add(textColour);
5798     colourMenu.addSeparator();
5799
5800     ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5801             viewport.getAlignment(), false);
5802
5803     colourMenu.add(annotationColour);
5804     bg.add(annotationColour);
5805     colourMenu.addSeparator();
5806     colourMenu.add(conservationMenuItem);
5807     colourMenu.add(modifyConservation);
5808     colourMenu.add(abovePIDThreshold);
5809     colourMenu.add(modifyPID);
5810
5811     ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5812     ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5813   }
5814
5815   /**
5816    * Open a dialog (if not already open) that allows the user to select and
5817    * calculate PCA or Tree analysis
5818    */
5819   protected void openTreePcaDialog()
5820   {
5821     if (alignPanel.getCalculationDialog() == null)
5822     {
5823       new CalculationChooser(AlignFrame.this);
5824     }
5825   }
5826
5827   @Override
5828   protected void loadVcf_actionPerformed()
5829   {
5830     JalviewFileChooser chooser = new JalviewFileChooser(
5831             Cache.getProperty("LAST_DIRECTORY"));
5832     chooser.setFileView(new JalviewFileView());
5833     chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5834     chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5835     final AlignFrame us = this;
5836     chooser.setResponseHandler(0, new Runnable()
5837     {
5838       @Override
5839       public void run()
5840       {
5841         String choice = chooser.getSelectedFile().getPath();
5842         Cache.setProperty("LAST_DIRECTORY", choice);
5843         SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5844         new VCFLoader(choice).loadVCF(seqs, us);
5845       }
5846     });
5847     chooser.showOpenDialog(null);
5848
5849   }
5850
5851   /**
5852    * BH 2019 from JalviewLite
5853    * 
5854    * get sequence feature groups that are hidden or shown
5855    * 
5856    * @param visible
5857    *          true is visible
5858    * @return list
5859    */
5860   public String[] getFeatureGroupsOfState(boolean visible)
5861   {
5862     jalview.api.FeatureRenderer fr = null;
5863     if (alignPanel != null
5864             && (fr = alignPanel
5865                     .getFeatureRenderer()) != null)
5866     {
5867       List<String> gps = fr.getGroups(visible);
5868       String[] _gps = gps.toArray(new String[gps.size()]);
5869       return _gps;
5870     }
5871     return null;
5872   }
5873
5874   public void scrollTo(int row, int column)
5875   {
5876     alignPanel.getSeqPanel().scrollTo(row, column);
5877   }
5878
5879   public void scrollToRow(int row)
5880   {
5881     alignPanel.getSeqPanel().scrollToRow(row);
5882   }
5883
5884   public void scrollToColumn(int column)
5885   {
5886     alignPanel.getSeqPanel().scrollToColumn(column);
5887   }
5888
5889   /**
5890    * 
5891    * @return list of feature groups on the view
5892    */
5893   public String[] getFeatureGroups()
5894   {
5895     jalview.api.FeatureRenderer fr = null;
5896     if (alignPanel != null
5897             && (fr = alignPanel.getFeatureRenderer()) != null)
5898     {
5899       List<String> gps = fr.getFeatureGroups();
5900       String[] _gps = gps.toArray(new String[gps.size()]);
5901       return _gps;
5902     }
5903     return null;
5904   }
5905
5906   public void select(SequenceGroup sel, ColumnSelection csel,
5907           HiddenColumns hidden)
5908   {
5909     alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
5910   }
5911
5912 }
5913
5914 class PrintThread extends Thread
5915 {
5916   AlignmentPanel ap;
5917
5918   public PrintThread(AlignmentPanel ap)
5919   {
5920     this.ap = ap;
5921   }
5922
5923   static PageFormat pf;
5924
5925   @Override
5926   public void run()
5927   {
5928     PrinterJob printJob = PrinterJob.getPrinterJob();
5929
5930     if (pf != null)
5931     {
5932       printJob.setPrintable(ap, pf);
5933     }
5934     else
5935     {
5936       printJob.setPrintable(ap);
5937     }
5938
5939     if (printJob.printDialog())
5940     {
5941       try
5942       {
5943         printJob.print();
5944       } catch (Exception PrintException)
5945       {
5946         PrintException.printStackTrace();
5947       }
5948     }
5949   }
5950
5951 }