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