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