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