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