Merge branch 'feature/JAL-3686_slivka_client_js_update' into alpha/merge_212_JalviewJ...
[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.WSDiscovererI;
159 import jalview.ws.api.ServiceWithParameters;
160 import jalview.ws.jws1.Discoverer;
161 import jalview.ws.jws2.Jws2Discoverer;
162 import jalview.ws.params.ArgumentI;
163 import jalview.ws.params.ParamDatastoreI;
164 import jalview.ws.params.WsParamSetI;
165 import jalview.ws.seqfetcher.DbSourceProxy;
166 import jalview.ws.slivkaws.SlivkaWSDiscoverer;
167 import java.io.IOException;
168 import java.util.HashSet;
169 import java.util.Set;
170
171 import javax.swing.JFileChooser;
172 import javax.swing.JOptionPane;
173
174 /**
175  * DOCUMENT ME!
176  * 
177  * @author $author$
178  * @version $Revision$
179  */
180 @SuppressWarnings("serial")
181 public class AlignFrame extends GAlignFrame implements DropTargetListener,
182         IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
183 {
184   public static final int DEFAULT_WIDTH = 700;
185
186   public static final int DEFAULT_HEIGHT = 500;
187
188   /*
189    * The currently displayed panel (selected tabbed view if more than one)
190    */
191   public AlignmentPanel alignPanel;
192
193   AlignViewport viewport;
194
195   public AlignViewControllerI avc;
196
197   List<AlignmentPanel> alignPanels = new ArrayList<>();
198
199   /**
200    * Last format used to load or save alignments in this window
201    */
202   FileFormatI currentFileFormat = null;
203
204   /**
205    * Current filename for this alignment
206    */
207   String fileName = null;
208
209   /**
210          * TODO: remove reference to 'FileObject' in AlignFrame - not correct mapping
211          */
212   File fileObject;
213
214   /**
215    * Creates a new AlignFrame object with specific width and height.
216    * 
217    * @param al
218    * @param width
219    * @param height
220    */
221   public AlignFrame(AlignmentI al, int width, int height)
222   {
223     this(al, null, width, height);
224   }
225
226   /**
227    * Creates a new AlignFrame object with specific width, height and
228    * sequenceSetId
229    * 
230    * @param al
231    * @param width
232    * @param height
233    * @param sequenceSetId
234    */
235   public AlignFrame(AlignmentI al, int width, int height,
236           String sequenceSetId)
237   {
238     this(al, null, width, height, sequenceSetId);
239   }
240
241   /**
242    * Creates a new AlignFrame object with specific width, height and
243    * sequenceSetId
244    * 
245    * @param al
246    * @param width
247    * @param height
248    * @param sequenceSetId
249    * @param viewId
250    */
251   public AlignFrame(AlignmentI al, int width, int height,
252           String sequenceSetId, String viewId)
253   {
254     this(al, null, width, height, sequenceSetId, viewId);
255   }
256
257   /**
258    * new alignment window with hidden columns
259    * 
260    * @param al
261    *          AlignmentI
262    * @param hiddenColumns
263    *          ColumnSelection or null
264    * @param width
265    *          Width of alignment frame
266    * @param height
267    *          height of frame.
268    */
269   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
270           int height)
271   {
272     this(al, hiddenColumns, width, height, null);
273   }
274
275   /**
276    * Create alignment frame for al with hiddenColumns, a specific width and
277    * height, and specific sequenceId
278    * 
279    * @param al
280    * @param hiddenColumns
281    * @param width
282    * @param height
283    * @param sequenceSetId
284    *          (may be null)
285    */
286   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
287           int height, String sequenceSetId)
288   {
289     this(al, hiddenColumns, width, height, sequenceSetId, null);
290   }
291
292   /**
293    * Create alignment frame for al with hiddenColumns, a specific width and
294    * height, and specific sequenceId
295    * 
296    * @param al
297    * @param hiddenColumns
298    * @param width
299    * @param height
300    * @param sequenceSetId
301    *          (may be null)
302    * @param viewId
303    *          (may be null)
304    */
305   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
306           int height, String sequenceSetId, String viewId)
307   {
308     setSize(width, height);
309
310     if (al.getDataset() == null)
311     {
312       al.setDataset(null);
313     }
314
315     viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
316
317     alignPanel = new AlignmentPanel(this, viewport);
318
319     addAlignmentPanel(alignPanel, true);
320     init();
321   }
322
323   public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
324           HiddenColumns hiddenColumns, int width, int height)
325   {
326     setSize(width, height);
327
328     if (al.getDataset() == null)
329     {
330       al.setDataset(null);
331     }
332
333     viewport = new AlignViewport(al, hiddenColumns);
334
335     if (hiddenSeqs != null && hiddenSeqs.length > 0)
336     {
337       viewport.hideSequence(hiddenSeqs);
338     }
339     alignPanel = new AlignmentPanel(this, viewport);
340     addAlignmentPanel(alignPanel, true);
341     init();
342   }
343
344   /**
345    * Make a new AlignFrame from existing alignmentPanels
346    * 
347    * @param ap
348    *          AlignmentPanel
349    * @param av
350    *          AlignViewport
351    */
352   public AlignFrame(AlignmentPanel ap)
353   {
354     viewport = ap.av;
355     alignPanel = ap;
356     addAlignmentPanel(ap, false);
357     init();
358   }
359
360   /**
361    * initalise the alignframe from the underlying viewport data and the
362    * configurations
363    */
364   void init()
365   {
366 //        setBackground(Color.white); // BH 2019
367                   
368     if (!Jalview.isHeadlessMode())
369     {
370       progressBar = new ProgressBar(this.statusPanel, this.statusBar);
371     }
372
373     avc = new jalview.controller.AlignViewController(this, viewport,
374             alignPanel);
375     if (viewport.getAlignmentConservationAnnotation() == null)
376     {
377       // BLOSUM62Colour.setEnabled(false);
378       conservationMenuItem.setEnabled(false);
379       modifyConservation.setEnabled(false);
380       // PIDColour.setEnabled(false);
381       // abovePIDThreshold.setEnabled(false);
382       // modifyPID.setEnabled(false);
383     }
384
385     String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
386             "No sort");
387
388     if (sortby.equals("Id"))
389     {
390       sortIDMenuItem_actionPerformed(null);
391     }
392     else if (sortby.equals("Pairwise Identity"))
393     {
394       sortPairwiseMenuItem_actionPerformed(null);
395     }
396
397     this.alignPanel.av
398             .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
399
400     setMenusFromViewport(viewport);
401     buildSortByAnnotationScoresMenu();
402     calculateTree.addActionListener(new ActionListener()
403     {
404
405       @Override
406       public void actionPerformed(ActionEvent e)
407       {
408         openTreePcaDialog();
409       }
410     });
411     buildColourMenu();
412
413     if (Desktop.desktop != null)
414     {
415       this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
416       if (!Platform.isJS())
417       {
418         addServiceListeners();
419       }
420       setGUINucleotide();
421     }
422
423     if (viewport.getWrapAlignment())
424     {
425       wrapMenuItem_actionPerformed(null);
426     }
427
428     if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
429     {
430       this.overviewMenuItem_actionPerformed(null);
431     }
432
433     addKeyListener();
434
435     final List<AlignmentPanel> selviews = new ArrayList<>();
436     final List<AlignmentPanel> origview = new ArrayList<>();
437     final String menuLabel = MessageManager
438             .getString("label.copy_format_from");
439     ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
440             new ViewSetProvider()
441             {
442
443               @Override
444               public AlignmentPanel[] getAllAlignmentPanels()
445               {
446                 origview.clear();
447                 origview.add(alignPanel);
448                 // make an array of all alignment panels except for this one
449                 List<AlignmentPanel> aps = new ArrayList<>(
450                         Arrays.asList(Desktop.getAlignmentPanels(null)));
451                 aps.remove(AlignFrame.this.alignPanel);
452                 return aps.toArray(new AlignmentPanel[aps.size()]);
453               }
454             }, selviews, new ItemListener()
455             {
456
457               @Override
458               public void itemStateChanged(ItemEvent e)
459               {
460                 if (origview.size() > 0)
461                 {
462                   final AlignmentPanel ap = origview.get(0);
463
464                   /*
465                    * Copy the ViewStyle of the selected panel to 'this one'.
466                    * Don't change value of 'scaleProteinAsCdna' unless copying
467                    * from a SplitFrame.
468                    */
469                   ViewStyleI vs = selviews.get(0).getAlignViewport()
470                           .getViewStyle();
471                   boolean fromSplitFrame = selviews.get(0)
472                           .getAlignViewport().getCodingComplement() != null;
473                   if (!fromSplitFrame)
474                   {
475                     vs.setScaleProteinAsCdna(ap.getAlignViewport()
476                             .getViewStyle().isScaleProteinAsCdna());
477                   }
478                   ap.getAlignViewport().setViewStyle(vs);
479
480                   /*
481                    * Also rescale ViewStyle of SplitFrame complement if there is
482                    * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
483                    * the whole ViewStyle (allow cDNA protein to have different
484                    * fonts)
485                    */
486                   AlignViewportI complement = ap.getAlignViewport()
487                           .getCodingComplement();
488                   if (complement != null && vs.isScaleProteinAsCdna())
489                   {
490                     AlignFrame af = Desktop.getAlignFrameFor(complement);
491                     ((SplitFrame) af.getSplitViewContainer())
492                             .adjustLayout();
493                     af.setMenusForViewport();
494                   }
495
496                   ap.updateLayout();
497                   ap.setSelected(true);
498                   ap.alignFrame.setMenusForViewport();
499
500                 }
501               }
502             });
503     if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
504             .indexOf("devel") > -1
505             || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
506                     .indexOf("test") > -1)
507     {
508       formatMenu.add(vsel);
509     }
510     addFocusListener(new FocusAdapter()
511     {
512       @Override
513       public void focusGained(FocusEvent e)
514       {
515         Jalview.setCurrentAlignFrame(AlignFrame.this);
516       }
517     });
518
519   }
520
521   /**
522    * Change the filename and format for the alignment, and enable the 'reload'
523    * button functionality.
524    * 
525    * @param file
526    *          valid filename
527    * @param format
528    *          format of file
529    */
530   public void setFileName(String file, FileFormatI format)
531   {
532     fileName = file;
533     setFileFormat(format);
534     reload.setEnabled(true);
535   }
536
537   /**
538    * JavaScript will have this, maybe others. More dependable than a file name
539    * and maintains a reference to the actual bytes loaded.
540    * 
541    * @param file
542    */
543   public void setFileObject(File file)
544   {
545     this.fileObject = file;
546   }
547
548   /**
549    * Add a KeyListener with handlers for various KeyPressed and KeyReleased
550    * events
551    */
552   void addKeyListener()
553   {
554     addKeyListener(new KeyAdapter()
555     {
556       @Override
557       public void keyPressed(KeyEvent evt)
558       {
559         if (viewport.cursorMode
560                 && ((evt.getKeyCode() >= KeyEvent.VK_0
561                         && evt.getKeyCode() <= KeyEvent.VK_9)
562                         || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
563                                 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
564                 && Character.isDigit(evt.getKeyChar()))
565         {
566           alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
567         }
568
569         switch (evt.getKeyCode())
570         {
571
572         case 27: // escape key
573           deselectAllSequenceMenuItem_actionPerformed(null);
574
575           break;
576
577         case KeyEvent.VK_DOWN:
578           if (evt.isAltDown() || !viewport.cursorMode)
579           {
580             moveSelectedSequences(false);
581           }
582           if (viewport.cursorMode)
583           {
584             alignPanel.getSeqPanel().moveCursor(0, 1);
585           }
586           break;
587
588         case KeyEvent.VK_UP:
589           if (evt.isAltDown() || !viewport.cursorMode)
590           {
591             moveSelectedSequences(true);
592           }
593           if (viewport.cursorMode)
594           {
595             alignPanel.getSeqPanel().moveCursor(0, -1);
596           }
597
598           break;
599
600         case KeyEvent.VK_LEFT:
601           if (evt.isAltDown() || !viewport.cursorMode)
602           {
603             slideSequences(false,
604                     alignPanel.getSeqPanel().getKeyboardNo1());
605           }
606           else
607           {
608             alignPanel.getSeqPanel().moveCursor(-1, 0);
609           }
610
611           break;
612
613         case KeyEvent.VK_RIGHT:
614           if (evt.isAltDown() || !viewport.cursorMode)
615           {
616             slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
617           }
618           else
619           {
620             alignPanel.getSeqPanel().moveCursor(1, 0);
621           }
622           break;
623
624         case KeyEvent.VK_SPACE:
625           if (viewport.cursorMode)
626           {
627             alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
628                     || evt.isShiftDown() || evt.isAltDown());
629           }
630           break;
631
632         // case KeyEvent.VK_A:
633         // if (viewport.cursorMode)
634         // {
635         // alignPanel.seqPanel.insertNucAtCursor(false,"A");
636         // //System.out.println("A");
637         // }
638         // break;
639         /*
640          * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
641          * System.out.println("closing bracket"); } break;
642          */
643         case KeyEvent.VK_DELETE:
644         case KeyEvent.VK_BACK_SPACE:
645           if (!viewport.cursorMode)
646           {
647             cut_actionPerformed();
648           }
649           else
650           {
651             alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
652                     || evt.isShiftDown() || evt.isAltDown());
653           }
654
655           break;
656
657         case KeyEvent.VK_S:
658           if (viewport.cursorMode)
659           {
660             alignPanel.getSeqPanel().setCursorRow();
661           }
662           break;
663         case KeyEvent.VK_C:
664           if (viewport.cursorMode && !evt.isControlDown())
665           {
666             alignPanel.getSeqPanel().setCursorColumn();
667           }
668           break;
669         case KeyEvent.VK_P:
670           if (viewport.cursorMode)
671           {
672             alignPanel.getSeqPanel().setCursorPosition();
673           }
674           break;
675
676         case KeyEvent.VK_ENTER:
677         case KeyEvent.VK_COMMA:
678           if (viewport.cursorMode)
679           {
680             alignPanel.getSeqPanel().setCursorRowAndColumn();
681           }
682           break;
683
684         case KeyEvent.VK_Q:
685           if (viewport.cursorMode)
686           {
687             alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
688           }
689           break;
690         case KeyEvent.VK_M:
691           if (viewport.cursorMode)
692           {
693             alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
694           }
695           break;
696
697         case KeyEvent.VK_F2:
698           viewport.cursorMode = !viewport.cursorMode;
699           setStatus(MessageManager
700                   .formatMessage("label.keyboard_editing_mode", new String[]
701                   { (viewport.cursorMode ? "on" : "off") }));
702           if (viewport.cursorMode)
703           {
704             ViewportRanges ranges = viewport.getRanges();
705             alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
706                     .getStartRes();
707             alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
708                     .getStartSeq();
709           }
710           alignPanel.getSeqPanel().seqCanvas.repaint();
711           break;
712
713         case KeyEvent.VK_F1:
714           try
715           {
716             Help.showHelpWindow();
717           } catch (Exception ex)
718           {
719             ex.printStackTrace();
720           }
721           break;
722         case KeyEvent.VK_H:
723         {
724           boolean toggleSeqs = !evt.isControlDown();
725           boolean toggleCols = !evt.isShiftDown();
726           toggleHiddenRegions(toggleSeqs, toggleCols);
727           break;
728         }
729         case KeyEvent.VK_B:
730         {
731           boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
732           boolean modifyExisting = true; // always modify, don't clear
733                                          // evt.isShiftDown();
734           boolean invertHighlighted = evt.isAltDown();
735           avc.markHighlightedColumns(invertHighlighted, modifyExisting,
736                   toggleSel);
737           break;
738         }
739         case KeyEvent.VK_PAGE_UP:
740           viewport.getRanges().pageUp();
741           break;
742         case KeyEvent.VK_PAGE_DOWN:
743           viewport.getRanges().pageDown();
744           break;
745         }
746       }
747
748       @Override
749       public void keyReleased(KeyEvent evt)
750       {
751         switch (evt.getKeyCode())
752         {
753         case KeyEvent.VK_LEFT:
754           if (evt.isAltDown() || !viewport.cursorMode)
755           {
756             viewport.firePropertyChange("alignment", null,
757                     viewport.getAlignment().getSequences());
758           }
759           break;
760
761         case KeyEvent.VK_RIGHT:
762           if (evt.isAltDown() || !viewport.cursorMode)
763           {
764             viewport.firePropertyChange("alignment", null,
765                     viewport.getAlignment().getSequences());
766           }
767           break;
768         }
769       }
770     });
771   }
772
773   public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
774   {
775     ap.alignFrame = this;
776     avc = new jalview.controller.AlignViewController(this, viewport,
777             alignPanel);
778
779     alignPanels.add(ap);
780
781     PaintRefresher.Register(ap, ap.av.getSequenceSetId());
782
783     int aSize = alignPanels.size();
784
785     tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
786
787     if (aSize == 1 && ap.av.getViewName() == null)
788     {
789       this.getContentPane().add(ap, BorderLayout.CENTER);
790     }
791     else
792     {
793       if (aSize == 2)
794       {
795         setInitialTabVisible();
796       }
797
798       expandViews.setEnabled(true);
799       gatherViews.setEnabled(true);
800       tabbedPane.addTab(ap.av.getViewName(), ap);
801
802       ap.setVisible(false);
803     }
804
805     if (newPanel)
806     {
807       if (ap.av.isPadGaps())
808       {
809         ap.av.getAlignment().padGaps();
810       }
811       ap.av.updateConservation(ap);
812       ap.av.updateConsensus(ap);
813       ap.av.updateStrucConsensus(ap);
814       ap.av.initInformationWorker(ap);
815     }
816   }
817
818   public void setInitialTabVisible()
819   {
820     expandViews.setEnabled(true);
821     gatherViews.setEnabled(true);
822     tabbedPane.setVisible(true);
823     AlignmentPanel first = alignPanels.get(0);
824     tabbedPane.addTab(first.av.getViewName(), first);
825     this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
826   }
827
828   public AlignViewport getViewport()
829   {
830     return viewport;
831   }
832
833   /* Set up intrinsic listeners for dynamically generated GUI bits. */
834   private void addServiceListeners()
835   {
836     final java.beans.PropertyChangeListener thisListener;
837     Desktop.instance.addJalviewPropertyChangeListener("services",
838             thisListener = new java.beans.PropertyChangeListener()
839             {
840               @Override
841               public void propertyChange(PropertyChangeEvent evt)
842               {
843                 // // System.out.println("Discoverer property change.");
844                 // if (evt.getPropertyName().equals("services"))
845                 {
846                   SwingUtilities.invokeLater(new Runnable()
847                   {
848
849                     @Override
850                     public void run()
851                     {
852                       System.err.println(
853                               "Rebuild WS Menu for service change");
854                       BuildWebServiceMenu();
855                     }
856
857                   });
858                 }
859               }
860             });
861     addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
862     {
863       @Override
864       public void internalFrameClosed(
865               javax.swing.event.InternalFrameEvent evt)
866       {
867         // System.out.println("deregistering discoverer listener");
868         Desktop.instance.removeJalviewPropertyChangeListener("services",
869                 thisListener);
870         closeMenuItem_actionPerformed(true);
871       }
872     });
873     // Finally, build the menu once to get current service state
874     new Thread(new Runnable()
875     {
876       @Override
877       public void run()
878       {
879         BuildWebServiceMenu();
880       }
881     }).start();
882   }
883
884   /**
885    * Configure menu items that vary according to whether the alignment is
886    * nucleotide or protein
887    */
888   public void setGUINucleotide()
889   {
890     AlignmentI al = getViewport().getAlignment();
891     boolean nucleotide = al.isNucleotide();
892
893     loadVcf.setVisible(nucleotide);
894     showTranslation.setVisible(nucleotide);
895     showReverse.setVisible(nucleotide);
896     showReverseComplement.setVisible(nucleotide);
897     conservationMenuItem.setEnabled(!nucleotide);
898     modifyConservation
899             .setEnabled(!nucleotide && conservationMenuItem.isSelected());
900     showGroupConservation.setEnabled(!nucleotide);
901
902     showComplementMenuItem
903             .setText(nucleotide ? MessageManager.getString("label.protein")
904                     : MessageManager.getString("label.nucleotide"));
905   }
906
907   /**
908    * set up menus for the current viewport. This may be called after any
909    * operation that affects the data in the current view (selection changed,
910    * etc) to update the menus to reflect the new state.
911    */
912   @Override
913   public void setMenusForViewport()
914   {
915     setMenusFromViewport(viewport);
916   }
917
918   /**
919    * Need to call this method when tabs are selected for multiple views, or when
920    * loading from Jalview2XML.java
921    * 
922    * @param av
923    *          AlignViewport
924    */
925   public void setMenusFromViewport(AlignViewport av)
926   {
927     padGapsMenuitem.setSelected(av.isPadGaps());
928     colourTextMenuItem.setSelected(av.isShowColourText());
929     abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
930     modifyPID.setEnabled(abovePIDThreshold.isSelected());
931     conservationMenuItem.setSelected(av.getConservationSelected());
932     modifyConservation.setEnabled(conservationMenuItem.isSelected());
933     seqLimits.setSelected(av.getShowJVSuffix());
934     idRightAlign.setSelected(av.isRightAlignIds());
935     centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
936     renderGapsMenuItem.setSelected(av.isRenderGaps());
937     wrapMenuItem.setSelected(av.getWrapAlignment());
938     scaleAbove.setVisible(av.getWrapAlignment());
939     scaleLeft.setVisible(av.getWrapAlignment());
940     scaleRight.setVisible(av.getWrapAlignment());
941     annotationPanelMenuItem.setState(av.isShowAnnotation());
942     /*
943      * Show/hide annotations only enabled if annotation panel is shown
944      */
945     showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
946     hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
947     showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
948     hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
949     viewBoxesMenuItem.setSelected(av.getShowBoxes());
950     viewTextMenuItem.setSelected(av.getShowText());
951     showNonconservedMenuItem.setSelected(av.getShowUnconserved());
952     showGroupConsensus.setSelected(av.isShowGroupConsensus());
953     showGroupConservation.setSelected(av.isShowGroupConservation());
954     showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
955     showSequenceLogo.setSelected(av.isShowSequenceLogo());
956     normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
957     showInformationHistogram.setSelected(av.isShowInformationHistogram());
958     showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
959     normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
960
961     ColourMenuHelper.setColourSelected(colourMenu,
962             av.getGlobalColourScheme());
963
964     showSeqFeatures.setSelected(av.isShowSequenceFeatures());
965     hiddenMarkers.setState(av.getShowHiddenMarkers());
966     applyToAllGroups.setState(av.getColourAppliesToAllGroups());
967     showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
968     showDbRefsMenuitem.setSelected(av.isShowDBRefs());
969     autoCalculate.setSelected(av.autoCalculateConsensus);
970     sortByTree.setSelected(av.sortByTree);
971     listenToViewSelections.setSelected(av.followSelection);
972
973     showProducts.setEnabled(canShowProducts());
974     setGroovyEnabled(Desktop.getGroovyConsole() != null);
975
976     updateEditMenuBar();
977   }
978
979   /**
980    * Set the enabled state of the 'Run Groovy' option in the Calculate menu
981    * 
982    * @param b
983    */
984   public void setGroovyEnabled(boolean b)
985   {
986     runGroovy.setEnabled(b);
987   }
988
989   private IProgressIndicator progressBar;
990
991   /*
992    * (non-Javadoc)
993    * 
994    * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
995    */
996   @Override
997   public void setProgressBar(String message, long id)
998   {
999     progressBar.setProgressBar(message, id);
1000   }
1001
1002   @Override
1003   public void registerHandler(final long id,
1004           final IProgressIndicatorHandler handler)
1005   {
1006     progressBar.registerHandler(id, handler);
1007   }
1008
1009   /**
1010    * 
1011    * @return true if any progress bars are still active
1012    */
1013   @Override
1014   public boolean operationInProgress()
1015   {
1016     return progressBar.operationInProgress();
1017   }
1018
1019   /**
1020    * Sets the text of the status bar. Note that setting a null or empty value
1021    * will cause the status bar to be hidden, with possibly undesirable flicker
1022    * of the screen layout.
1023    */
1024   @Override
1025   public void setStatus(String text)
1026   {
1027     statusBar.setText(text == null || text.isEmpty() ? " " : text);
1028   }
1029
1030   /*
1031    * Added so Castor Mapping file can obtain Jalview Version
1032    */
1033   public String getVersion()
1034   {
1035     return jalview.bin.Cache.getProperty("VERSION");
1036   }
1037
1038   public FeatureRenderer getFeatureRenderer()
1039   {
1040     return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1041   }
1042
1043   @Override
1044   public void fetchSequence_actionPerformed()
1045   {
1046     new SequenceFetcher(this);
1047   }
1048
1049   @Override
1050   public void addFromFile_actionPerformed(ActionEvent e)
1051   {
1052     Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1053   }
1054
1055   @Override
1056   public void hmmBuild_actionPerformed(boolean withDefaults)
1057   {
1058     if (!alignmentIsSufficient(1))
1059     {
1060       return;
1061     }
1062
1063     /*
1064      * get default parameters, and optionally show a dialog
1065      * to allow them to be modified
1066      */
1067     ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1068     List<ArgumentI> args = store.getServiceParameters();
1069
1070     if (!withDefaults)
1071     {
1072       WsParamSetI set = new HMMERPreset();
1073       WsJobParameters params = new WsJobParameters(store, set, args);
1074       if (params.showRunDialog())
1075       {
1076         args = params.getJobParams();
1077       }
1078       else
1079       {
1080         return; // user cancelled
1081       }
1082     }
1083     new Thread(new HMMBuild(this, args)).start();
1084   }
1085
1086   @Override
1087   public void hmmAlign_actionPerformed(boolean withDefaults)
1088   {
1089     if (!(checkForHMM() && alignmentIsSufficient(2)))
1090     {
1091       return;
1092     }
1093
1094     /*
1095      * get default parameters, and optionally show a dialog
1096      * to allow them to be modified
1097      */
1098     ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1099     List<ArgumentI> args = store.getServiceParameters();
1100
1101     if (!withDefaults)
1102     {
1103       WsParamSetI set = new HMMERPreset();
1104       WsJobParameters params = new WsJobParameters(store, set, args);
1105       if (params.showRunDialog())
1106       {
1107         args = params.getJobParams();
1108       }
1109       else
1110       {
1111         return; // user cancelled
1112       }
1113     }
1114     new Thread(new HMMAlign(this, args)).start();
1115   }
1116
1117   @Override
1118   public void hmmSearch_actionPerformed(boolean withDefaults)
1119   {
1120     if (!checkForHMM())
1121     {
1122       return;
1123     }
1124
1125     /*
1126      * get default parameters, and (if requested) show 
1127      * dialog to allow modification
1128      */
1129     ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1130     List<ArgumentI> args = store.getServiceParameters();
1131
1132     if (!withDefaults)
1133     {
1134       WsParamSetI set = new HMMERPreset();
1135       WsJobParameters params = new WsJobParameters(store, set, args);
1136       if (params.showRunDialog())
1137       {
1138         args = params.getJobParams();
1139       }
1140       else
1141       {
1142         return; // user cancelled
1143       }
1144     }
1145     new Thread(new HMMSearch(this, args)).start();
1146     alignPanel.repaint();
1147   }
1148   
1149   @Override
1150   public void jackhmmer_actionPerformed(boolean withDefaults)
1151   {
1152     
1153     /*
1154      * get default parameters, and (if requested) show 
1155      * dialog to allow modification
1156      */
1157     
1158     ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
1159     List<ArgumentI> args = store.getServiceParameters();
1160
1161     if (!withDefaults)
1162     {
1163       WsParamSetI set = new HMMERPreset();
1164       WsJobParameters params = new WsJobParameters(store, set, args);
1165       if (params.showRunDialog())
1166       {
1167         args = params.getJobParams();
1168       }
1169       else
1170       {
1171         return; // user cancelled
1172       }
1173     }
1174     new Thread(new JackHMMER(this, args)).start();
1175     alignPanel.repaint();
1176     
1177   }
1178
1179   /**
1180    * Checks if the alignment has at least one hidden Markov model, if not shows
1181    * a dialog advising to run hmmbuild or load an HMM profile
1182    * 
1183    * @return
1184    */
1185   private boolean checkForHMM()
1186   {
1187     if (viewport.getAlignment().getHmmSequences().isEmpty())
1188     {
1189       JOptionPane.showMessageDialog(this,
1190               MessageManager.getString("warn.no_hmm"));
1191       return false;
1192     }
1193     return true;
1194   }
1195   
1196   @Override
1197   protected void filterByEValue_actionPerformed()
1198   {
1199     viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
1200   }
1201   
1202   @Override
1203   protected void filterByScore_actionPerformed()
1204   {
1205     viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
1206   }
1207   
1208   private double inputDouble(String message)
1209   {
1210     String str = null;
1211     Double d = null;
1212     while(d == null || d <= 0)
1213     {
1214       str = JOptionPane.showInputDialog(this.alignPanel, message);
1215       try
1216       {
1217         d = Double.valueOf(str);
1218       }
1219       catch (NumberFormatException e)
1220       {
1221       }
1222     }
1223     return d;
1224   }
1225
1226   /**
1227    * Checks if the alignment contains the required number of sequences.
1228    * 
1229    * @param required
1230    * @return
1231    */
1232   public boolean alignmentIsSufficient(int required)
1233   {
1234       if (getViewport().getSequenceSelection().length < required)
1235       {
1236         JOptionPane.showMessageDialog(this,
1237                 MessageManager.getString("label.not_enough_sequences"));
1238         return false;
1239       }
1240       return true;
1241   }
1242
1243   /**
1244    * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1245    * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1246    * comma-separated list)
1247    */
1248   @Override
1249   public void addDatabase_actionPerformed() throws IOException
1250   {
1251     if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1252     {
1253       Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1254     }
1255
1256     String path = openFileChooser(false);
1257     if (path != null && new File(path).exists())
1258     {
1259       IdentifyFile identifier = new IdentifyFile();
1260       FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1261       if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1262               || format == FileFormat.Pfam)
1263       {
1264         String currentDbPaths = Cache
1265                 .getProperty(Preferences.HMMSEARCH_DBS);
1266         currentDbPaths += Preferences.COMMA + path;
1267         Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1268       }
1269       else
1270       {
1271         JOptionPane.showMessageDialog(this,
1272                 MessageManager.getString("warn.invalid_format"));
1273       }
1274     }
1275   }
1276
1277   /**
1278    * Opens a file chooser, optionally restricted to selecting folders
1279    * (directories) only. Answers the path to the selected file or folder, or
1280    * null if none is chosen.
1281    * 
1282    * @param
1283    * @return
1284    */
1285   protected String openFileChooser(boolean forFolder)
1286   {
1287     // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1288     String choice = null;
1289     JFileChooser chooser = new JFileChooser();
1290     if (forFolder)
1291     {
1292       chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1293     }
1294     chooser.setDialogTitle(
1295             MessageManager.getString("label.open_local_file"));
1296     chooser.setToolTipText(MessageManager.getString("action.open"));
1297
1298     int value = chooser.showOpenDialog(this);
1299
1300     if (value == JFileChooser.APPROVE_OPTION)
1301     {
1302       choice = chooser.getSelectedFile().getPath();
1303     }
1304     return choice;
1305   }
1306
1307   @Override
1308   public void reload_actionPerformed(ActionEvent e)
1309   {
1310     if (fileName != null)
1311     {
1312       // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1313       // originating file's format
1314       // TODO: work out how to recover feature settings for correct view(s) when
1315       // file is reloaded.
1316       if (FileFormat.Jalview.equals(currentFileFormat))
1317       {
1318         JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1319         for (int i = 0; i < frames.length; i++)
1320         {
1321           if (frames[i] instanceof AlignFrame && frames[i] != this
1322                   && ((AlignFrame) frames[i]).fileName != null
1323                   && ((AlignFrame) frames[i]).fileName.equals(fileName))
1324           {
1325             try
1326             {
1327               frames[i].setSelected(true);
1328               Desktop.instance.closeAssociatedWindows();
1329             } catch (java.beans.PropertyVetoException ex)
1330             {
1331             }
1332           }
1333
1334         }
1335         Desktop.instance.closeAssociatedWindows();
1336
1337         FileLoader loader = new FileLoader();
1338         DataSourceType protocol = fileName.startsWith("http:")
1339                 ? DataSourceType.URL
1340                 : DataSourceType.FILE;
1341         loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1342       }
1343       else
1344       {
1345         Rectangle bounds = this.getBounds();
1346
1347         FileLoader loader = new FileLoader();
1348
1349         AlignFrame newframe = null;
1350
1351         if (fileObject == null)
1352         {
1353
1354           DataSourceType protocol = (fileName.startsWith("http:")
1355                   ? DataSourceType.URL
1356                   : DataSourceType.FILE);
1357           newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1358                   currentFileFormat);
1359         }
1360         else
1361         {
1362           newframe = loader.LoadFileWaitTillLoaded(fileObject,
1363                   DataSourceType.FILE, currentFileFormat);
1364         }
1365
1366         newframe.setBounds(bounds);
1367         if (featureSettings != null && featureSettings.isShowing())
1368         {
1369           final Rectangle fspos = featureSettings.frame.getBounds();
1370           // TODO: need a 'show feature settings' function that takes bounds -
1371           // need to refactor Desktop.addFrame
1372           newframe.featureSettings_actionPerformed(null);
1373           final FeatureSettings nfs = newframe.featureSettings;
1374           SwingUtilities.invokeLater(new Runnable()
1375           {
1376             @Override
1377             public void run()
1378             {
1379               nfs.frame.setBounds(fspos);
1380             }
1381           });
1382           this.featureSettings.close();
1383           this.featureSettings = null;
1384         }
1385         this.closeMenuItem_actionPerformed(true);
1386       }
1387     }
1388   }
1389
1390   @Override
1391   public void addFromText_actionPerformed(ActionEvent e)
1392   {
1393     Desktop.instance
1394             .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1395   }
1396
1397   @Override
1398   public void addFromURL_actionPerformed(ActionEvent e)
1399   {
1400     Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1401   }
1402
1403   @Override
1404   public void save_actionPerformed(ActionEvent e)
1405   {
1406     if (fileName == null || (currentFileFormat == null)
1407             || fileName.startsWith("http"))
1408     {
1409       saveAs_actionPerformed();
1410     }
1411     else
1412     {
1413       saveAlignment(fileName, currentFileFormat);
1414     }
1415   }
1416
1417   /**
1418    * Saves the alignment to a file with a name chosen by the user, if necessary
1419    * warning if a file would be overwritten
1420    */
1421   @Override
1422   public void saveAs_actionPerformed()
1423   {
1424     String format = currentFileFormat == null ? null
1425             : currentFileFormat.getName();
1426     JalviewFileChooser chooser = JalviewFileChooser
1427             .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1428
1429     chooser.setFileView(new JalviewFileView());
1430     chooser.setDialogTitle(
1431             MessageManager.getString("label.save_alignment_to_file"));
1432     chooser.setToolTipText(MessageManager.getString("action.save"));
1433
1434     int value = chooser.showSaveDialog(this);
1435
1436     if (value != JalviewFileChooser.APPROVE_OPTION)
1437     {
1438       return;
1439     }
1440     currentFileFormat = chooser.getSelectedFormat();
1441     // todo is this (2005) test now obsolete - value is never null?
1442     while (currentFileFormat == null)
1443     {
1444       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1445               MessageManager
1446                       .getString("label.select_file_format_before_saving"),
1447               MessageManager.getString("label.file_format_not_specified"),
1448               JvOptionPane.WARNING_MESSAGE);
1449       currentFileFormat = chooser.getSelectedFormat();
1450       value = chooser.showSaveDialog(this);
1451       if (value != JalviewFileChooser.APPROVE_OPTION)
1452       {
1453         return;
1454       }
1455     }
1456
1457     fileName = chooser.getSelectedFile().getPath();
1458
1459     Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1460     Cache.setProperty("LAST_DIRECTORY", fileName);
1461     saveAlignment(fileName, currentFileFormat);
1462   }
1463
1464   boolean lastSaveSuccessful = false;
1465
1466   FileFormatI lastFormatSaved;
1467
1468   String lastFilenameSaved;
1469
1470   /**
1471    * Raise a dialog or status message for the last call to saveAlignment.
1472    *
1473    * @return true if last call to saveAlignment(file, format) was successful.
1474    */
1475   public boolean isSaveAlignmentSuccessful()
1476   {
1477
1478     if (!lastSaveSuccessful)
1479     {
1480       JvOptionPane.showInternalMessageDialog(this, MessageManager
1481               .formatMessage("label.couldnt_save_file", new Object[]
1482               { lastFilenameSaved }),
1483               MessageManager.getString("label.error_saving_file"),
1484               JvOptionPane.WARNING_MESSAGE);
1485     }
1486     else
1487     {
1488
1489       setStatus(MessageManager.formatMessage(
1490               "label.successfully_saved_to_file_in_format", new Object[]
1491               { lastFilenameSaved, lastFormatSaved }));
1492
1493     }
1494     return lastSaveSuccessful;
1495   }
1496
1497   /**
1498    * Saves the alignment to the specified file path, in the specified format,
1499    * which may be an alignment format, or Jalview project format. If the
1500    * alignment has hidden regions, or the format is one capable of including
1501    * non-sequence data (features, annotations, groups), then the user may be
1502    * prompted to specify what to include in the output.
1503    * 
1504    * @param file
1505    * @param format
1506    */
1507   public void saveAlignment(String file, FileFormatI format)
1508   {
1509     lastSaveSuccessful = true;
1510     lastFilenameSaved = file;
1511     lastFormatSaved = format;
1512
1513     if (FileFormat.Jalview.equals(format))
1514     {
1515       String shortName = title;
1516       if (shortName.indexOf(File.separatorChar) > -1)
1517       {
1518         shortName = shortName.substring(
1519                 shortName.lastIndexOf(File.separatorChar) + 1);
1520       }
1521       lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file, shortName);
1522       
1523       statusBar.setText(MessageManager.formatMessage(
1524               "label.successfully_saved_to_file_in_format", new Object[]
1525               { fileName, format }));
1526       
1527       return;
1528     }
1529
1530     AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1531     Runnable cancelAction = new Runnable()
1532     {
1533       @Override
1534       public void run()
1535       {
1536         lastSaveSuccessful = false;
1537       }
1538     };
1539     Runnable outputAction = new Runnable()
1540     {
1541       @Override
1542       public void run()
1543       {
1544         // todo defer this to inside formatSequences (or later)
1545         AlignmentExportData exportData = viewport
1546                 .getAlignExportData(options);
1547         String output = new FormatAdapter(alignPanel, options)
1548                 .formatSequences(format, exportData.getAlignment(),
1549                         exportData.getOmitHidden(),
1550                         exportData.getStartEndPostions(),
1551                         viewport.getAlignment().getHiddenColumns());
1552         if (output == null)
1553         {
1554           lastSaveSuccessful = false;
1555         }
1556         else
1557         {
1558           // create backupfiles object and get new temp filename destination
1559           boolean doBackup = BackupFiles.getEnabled();
1560           BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1561           try
1562           {
1563             String tempFilePath = doBackup ? backupfiles.getTempFilePath() : file;
1564                         PrintWriter out = new PrintWriter(
1565                     new FileWriter(tempFilePath));
1566
1567             out.print(output);
1568             out.close();
1569             AlignFrame.this.setTitle(file);
1570             statusBar.setText(MessageManager.formatMessage(
1571                   "label.successfully_saved_to_file_in_format", new Object[]
1572                   { fileName, format.getName() }));
1573             lastSaveSuccessful = true;
1574           } catch (Exception ex)
1575           {
1576             lastSaveSuccessful = false;
1577             ex.printStackTrace();
1578           }
1579
1580           if (doBackup)
1581           {
1582             backupfiles.setWriteSuccess(lastSaveSuccessful);
1583             // do the backup file roll and rename the temp file to actual file
1584             lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1585           }
1586         }
1587       }
1588     };
1589
1590     /*
1591      * show dialog with export options if applicable; else just do it
1592      */
1593     if (AlignExportOptions.isNeeded(viewport, format))
1594     {
1595       AlignExportOptions choices = new AlignExportOptions(
1596               alignPanel.getAlignViewport(), format, options);
1597       choices.setResponseAction(0, outputAction);
1598       choices.setResponseAction(1, cancelAction);
1599       choices.showDialog();
1600     }
1601     else
1602     {
1603       outputAction.run();
1604     }
1605   }
1606
1607   /**
1608    * Outputs the alignment to textbox in the requested format, if necessary
1609    * first prompting the user for whether to include hidden regions or
1610    * non-sequence data
1611    * 
1612    * @param fileFormatName
1613    */
1614   @Override
1615   protected void outputText_actionPerformed(String fileFormatName)
1616   {
1617     FileFormatI fileFormat = FileFormats.getInstance()
1618             .forName(fileFormatName);
1619     AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1620     Runnable outputAction = new Runnable()
1621     {
1622       @Override
1623       public void run()
1624       {
1625         // todo defer this to inside formatSequences (or later)
1626         AlignmentExportData exportData = viewport
1627                 .getAlignExportData(options);
1628         CutAndPasteTransfer cap = new CutAndPasteTransfer();
1629         cap.setForInput(null);
1630         try
1631         {
1632           FileFormatI format = fileFormat;
1633           cap.setText(new FormatAdapter(alignPanel, options)
1634                   .formatSequences(format, exportData.getAlignment(),
1635                           exportData.getOmitHidden(),
1636                           exportData.getStartEndPostions(),
1637                           viewport.getAlignment().getHiddenColumns()));
1638           Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1639                   "label.alignment_output_command", new Object[]
1640                   { fileFormat.getName() }), 600, 500);
1641         } catch (OutOfMemoryError oom)
1642         {
1643           new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1644                   oom);
1645           cap.dispose();
1646         }
1647       }
1648     };
1649
1650     /*
1651      * show dialog with export options if applicable; else just do it
1652      */
1653     if (AlignExportOptions.isNeeded(viewport, fileFormat))
1654     {
1655       AlignExportOptions choices = new AlignExportOptions(
1656               alignPanel.getAlignViewport(), fileFormat, options);
1657       choices.setResponseAction(0, outputAction);
1658       choices.showDialog();
1659     }
1660     else
1661     {
1662       outputAction.run();
1663     }
1664   }
1665
1666   /**
1667    * DOCUMENT ME!
1668    * 
1669    * @param e
1670    *          DOCUMENT ME!
1671    */
1672   @Override
1673   protected void htmlMenuItem_actionPerformed(ActionEvent e)
1674   {
1675     HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1676     htmlSVG.exportHTML(null);
1677   }
1678
1679   @Override
1680   public void bioJSMenuItem_actionPerformed(ActionEvent e)
1681   {
1682     BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1683     bjs.exportHTML(null);
1684   }
1685
1686   public void createImageMap(File file, String image)
1687   {
1688     alignPanel.makePNGImageMap(file, image);
1689   }
1690
1691   /**
1692    * Creates a PNG image of the alignment and writes it to the given file. If
1693    * the file is null, the user is prompted to choose a file.
1694    * 
1695    * @param f
1696    */
1697   @Override
1698   public void createPNG(File f)
1699   {
1700     alignPanel.makeAlignmentImage(TYPE.PNG, f);
1701   }
1702
1703   /**
1704    * Creates an EPS image of the alignment and writes it to the given file. If
1705    * the file is null, the user is prompted to choose a file.
1706    * 
1707    * @param f
1708    */
1709   @Override
1710   public void createEPS(File f)
1711   {
1712     alignPanel.makeAlignmentImage(TYPE.EPS, f);
1713   }
1714
1715   /**
1716    * Creates an SVG image of the alignment and writes it to the given file. If
1717    * the file is null, the user is prompted to choose a file.
1718    * 
1719    * @param f
1720    */
1721   @Override
1722   public void createSVG(File f)
1723   {
1724     alignPanel.makeAlignmentImage(TYPE.SVG, f);
1725   }
1726
1727   @Override
1728   public void pageSetup_actionPerformed(ActionEvent e)
1729   {
1730     PrinterJob printJob = PrinterJob.getPrinterJob();
1731     PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1732   }
1733
1734   /**
1735    * DOCUMENT ME!
1736    * 
1737    * @param e
1738    *          DOCUMENT ME!
1739    */
1740   @Override
1741   public void printMenuItem_actionPerformed(ActionEvent e)
1742   {
1743     // Putting in a thread avoids Swing painting problems
1744     PrintThread thread = new PrintThread(alignPanel);
1745     thread.start();
1746   }
1747
1748   @Override
1749   public void exportFeatures_actionPerformed(ActionEvent e)
1750   {
1751     new AnnotationExporter(alignPanel).exportFeatures();
1752   }
1753
1754   @Override
1755   public void exportAnnotations_actionPerformed(ActionEvent e)
1756   {
1757     new AnnotationExporter(alignPanel).exportAnnotations();
1758   }
1759
1760   @Override
1761   public void associatedData_actionPerformed(ActionEvent e)
1762           throws IOException, InterruptedException
1763   {
1764     final JalviewFileChooser chooser = new JalviewFileChooser(
1765             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1766     chooser.setFileView(new JalviewFileView());
1767     String tooltip = MessageManager.getString("label.load_jalview_annotations");
1768     chooser.setDialogTitle(tooltip);
1769     chooser.setToolTipText(tooltip);
1770     chooser.setResponseHandler(0, new Runnable()
1771     {
1772       @Override
1773       public void run()
1774       {
1775         String choice = chooser.getSelectedFile().getPath();
1776         jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1777         loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1778       }
1779     });
1780
1781     chooser.showOpenDialog(this);
1782   }
1783
1784   /**
1785    * Close the current view or all views in the alignment frame. If the frame
1786    * only contains one view then the alignment will be removed from memory.
1787    * 
1788    * @param closeAllTabs
1789    */
1790   @Override
1791   public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1792   {
1793     if (alignPanels != null && alignPanels.size() < 2)
1794     {
1795       closeAllTabs = true;
1796     }
1797
1798     try
1799     {
1800       if (alignPanels != null)
1801       {
1802         if (closeAllTabs)
1803         {
1804           if (this.isClosed())
1805           {
1806             // really close all the windows - otherwise wait till
1807             // setClosed(true) is called
1808             for (int i = 0; i < alignPanels.size(); i++)
1809             {
1810               AlignmentPanel ap = alignPanels.get(i);
1811               ap.closePanel();
1812             }
1813           }
1814         }
1815         else
1816         {
1817           closeView(alignPanel);
1818         }
1819       }
1820       if (closeAllTabs)
1821       {
1822         if (featureSettings != null && featureSettings.isOpen())
1823         {
1824           featureSettings.close();
1825           featureSettings = null;
1826         }
1827         /*
1828          * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1829          * be called recursively, with the frame now in 'closed' state
1830          */
1831         this.setClosed(true);
1832       }
1833     } catch (Exception ex)
1834     {
1835       ex.printStackTrace();
1836     }
1837   }
1838
1839   /**
1840    * Close the specified panel and close up tabs appropriately.
1841    * 
1842    * @param panelToClose
1843    */
1844   public void closeView(AlignmentPanel panelToClose)
1845   {
1846     int index = tabbedPane.getSelectedIndex();
1847     int closedindex = tabbedPane.indexOfComponent(panelToClose);
1848     alignPanels.remove(panelToClose);
1849     panelToClose.closePanel();
1850     panelToClose = null;
1851
1852     tabbedPane.removeTabAt(closedindex);
1853     tabbedPane.validate();
1854
1855     if (index > closedindex || index == tabbedPane.getTabCount())
1856     {
1857       // modify currently selected tab index if necessary.
1858       index--;
1859     }
1860
1861     this.tabSelectionChanged(index);
1862   }
1863
1864   /**
1865    * DOCUMENT ME!
1866    */
1867   void updateEditMenuBar()
1868   {
1869
1870     if (viewport.getHistoryList().size() > 0)
1871     {
1872       undoMenuItem.setEnabled(true);
1873       CommandI command = viewport.getHistoryList().peek();
1874       undoMenuItem.setText(MessageManager
1875               .formatMessage("label.undo_command", new Object[]
1876               { command.getDescription() }));
1877     }
1878     else
1879     {
1880       undoMenuItem.setEnabled(false);
1881       undoMenuItem.setText(MessageManager.getString("action.undo"));
1882     }
1883
1884     if (viewport.getRedoList().size() > 0)
1885     {
1886       redoMenuItem.setEnabled(true);
1887
1888       CommandI command = viewport.getRedoList().peek();
1889       redoMenuItem.setText(MessageManager
1890               .formatMessage("label.redo_command", new Object[]
1891               { command.getDescription() }));
1892     }
1893     else
1894     {
1895       redoMenuItem.setEnabled(false);
1896       redoMenuItem.setText(MessageManager.getString("action.redo"));
1897     }
1898   }
1899
1900   @Override
1901   public void addHistoryItem(CommandI command)
1902   {
1903     if (command.getSize() > 0)
1904     {
1905       viewport.addToHistoryList(command);
1906       viewport.clearRedoList();
1907       updateEditMenuBar();
1908       viewport.updateHiddenColumns();
1909       // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1910       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1911       // viewport.getColumnSelection()
1912       // .getHiddenColumns().size() > 0);
1913     }
1914   }
1915
1916   /**
1917    * 
1918    * @return alignment objects for all views
1919    */
1920   AlignmentI[] getViewAlignments()
1921   {
1922     if (alignPanels != null)
1923     {
1924       AlignmentI[] als = new AlignmentI[alignPanels.size()];
1925       int i = 0;
1926       for (AlignmentPanel ap : alignPanels)
1927       {
1928         als[i++] = ap.av.getAlignment();
1929       }
1930       return als;
1931     }
1932     if (viewport != null)
1933     {
1934       return new AlignmentI[] { viewport.getAlignment() };
1935     }
1936     return null;
1937   }
1938
1939   /**
1940    * DOCUMENT ME!
1941    * 
1942    * @param e
1943    *          DOCUMENT ME!
1944    */
1945   @Override
1946   protected void undoMenuItem_actionPerformed(ActionEvent e)
1947   {
1948     if (viewport.getHistoryList().isEmpty())
1949     {
1950       return;
1951     }
1952     CommandI command = viewport.getHistoryList().pop();
1953     viewport.addToRedoList(command);
1954     command.undoCommand(getViewAlignments());
1955
1956     AlignmentViewport originalSource = getOriginatingSource(command);
1957     updateEditMenuBar();
1958
1959     if (originalSource != null)
1960     {
1961       if (originalSource != viewport)
1962       {
1963         Cache.log.warn(
1964                 "Implementation worry: mismatch of viewport origin for undo");
1965       }
1966       originalSource.updateHiddenColumns();
1967       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1968       // null
1969       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1970       // viewport.getColumnSelection()
1971       // .getHiddenColumns().size() > 0);
1972       originalSource.firePropertyChange("alignment", null,
1973               originalSource.getAlignment().getSequences());
1974     }
1975   }
1976
1977   /**
1978    * DOCUMENT ME!
1979    * 
1980    * @param e
1981    *          DOCUMENT ME!
1982    */
1983   @Override
1984   protected void redoMenuItem_actionPerformed(ActionEvent e)
1985   {
1986     if (viewport.getRedoList().size() < 1)
1987     {
1988       return;
1989     }
1990
1991     CommandI command = viewport.getRedoList().pop();
1992     viewport.addToHistoryList(command);
1993     command.doCommand(getViewAlignments());
1994
1995     AlignmentViewport originalSource = getOriginatingSource(command);
1996     updateEditMenuBar();
1997
1998     if (originalSource != null)
1999     {
2000
2001       if (originalSource != viewport)
2002       {
2003         Cache.log.warn(
2004                 "Implementation worry: mismatch of viewport origin for redo");
2005       }
2006       originalSource.updateHiddenColumns();
2007       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2008       // null
2009       // && viewport.getColumnSelection().getHiddenColumns() != null &&
2010       // viewport.getColumnSelection()
2011       // .getHiddenColumns().size() > 0);
2012       originalSource.firePropertyChange("alignment", null,
2013               originalSource.getAlignment().getSequences());
2014     }
2015   }
2016
2017   AlignmentViewport getOriginatingSource(CommandI command)
2018   {
2019     AlignmentViewport originalSource = null;
2020     // For sequence removal and addition, we need to fire
2021     // the property change event FROM the viewport where the
2022     // original alignment was altered
2023     AlignmentI al = null;
2024     if (command instanceof EditCommand)
2025     {
2026       EditCommand editCommand = (EditCommand) command;
2027       al = editCommand.getAlignment();
2028       List<Component> comps = PaintRefresher.components
2029               .get(viewport.getSequenceSetId());
2030
2031       for (Component comp : comps)
2032       {
2033         if (comp instanceof AlignmentPanel)
2034         {
2035           if (al == ((AlignmentPanel) comp).av.getAlignment())
2036           {
2037             originalSource = ((AlignmentPanel) comp).av;
2038             break;
2039           }
2040         }
2041       }
2042     }
2043
2044     if (originalSource == null)
2045     {
2046       // The original view is closed, we must validate
2047       // the current view against the closed view first
2048       if (al != null)
2049       {
2050         PaintRefresher.validateSequences(al, viewport.getAlignment());
2051       }
2052
2053       originalSource = viewport;
2054     }
2055
2056     return originalSource;
2057   }
2058
2059   /**
2060    * DOCUMENT ME!
2061    * 
2062    * @param up
2063    *          DOCUMENT ME!
2064    */
2065   public void moveSelectedSequences(boolean up)
2066   {
2067     SequenceGroup sg = viewport.getSelectionGroup();
2068
2069     if (sg == null)
2070     {
2071       return;
2072     }
2073     viewport.getAlignment().moveSelectedSequencesByOne(sg,
2074             viewport.getHiddenRepSequences(), up);
2075     alignPanel.paintAlignment(true, false);
2076   }
2077
2078   synchronized void slideSequences(boolean right, int size)
2079   {
2080     List<SequenceI> sg = new ArrayList<>();
2081     if (viewport.cursorMode)
2082     {
2083       sg.add(viewport.getAlignment()
2084               .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2085     }
2086     else if (viewport.getSelectionGroup() != null
2087             && viewport.getSelectionGroup().getSize() != viewport
2088                     .getAlignment().getHeight())
2089     {
2090       sg = viewport.getSelectionGroup()
2091               .getSequences(viewport.getHiddenRepSequences());
2092     }
2093
2094     if (sg.size() < 1)
2095     {
2096       return;
2097     }
2098
2099     List<SequenceI> invertGroup = new ArrayList<>();
2100
2101     for (SequenceI seq : viewport.getAlignment().getSequences())
2102     {
2103       if (!sg.contains(seq))
2104       {
2105         invertGroup.add(seq);
2106       }
2107     }
2108
2109     SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2110
2111     SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2112     for (int i = 0; i < invertGroup.size(); i++)
2113     {
2114       seqs2[i] = invertGroup.get(i);
2115     }
2116
2117     SlideSequencesCommand ssc;
2118     if (right)
2119     {
2120       ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2121               viewport.getGapCharacter());
2122     }
2123     else
2124     {
2125       ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2126               viewport.getGapCharacter());
2127     }
2128
2129     int groupAdjustment = 0;
2130     if (ssc.getGapsInsertedBegin() && right)
2131     {
2132       if (viewport.cursorMode)
2133       {
2134         alignPanel.getSeqPanel().moveCursor(size, 0);
2135       }
2136       else
2137       {
2138         groupAdjustment = size;
2139       }
2140     }
2141     else if (!ssc.getGapsInsertedBegin() && !right)
2142     {
2143       if (viewport.cursorMode)
2144       {
2145         alignPanel.getSeqPanel().moveCursor(-size, 0);
2146       }
2147       else
2148       {
2149         groupAdjustment = -size;
2150       }
2151     }
2152
2153     if (groupAdjustment != 0)
2154     {
2155       viewport.getSelectionGroup().setStartRes(
2156               viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2157       viewport.getSelectionGroup().setEndRes(
2158               viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2159     }
2160
2161     /*
2162      * just extend the last slide command if compatible; but not if in
2163      * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2164      */
2165     boolean appendHistoryItem = false;
2166     Deque<CommandI> historyList = viewport.getHistoryList();
2167     boolean inSplitFrame = getSplitViewContainer() != null;
2168     if (!inSplitFrame && historyList != null && historyList.size() > 0
2169             && historyList.peek() instanceof SlideSequencesCommand)
2170     {
2171       appendHistoryItem = ssc.appendSlideCommand(
2172               (SlideSequencesCommand) historyList.peek());
2173     }
2174
2175     if (!appendHistoryItem)
2176     {
2177       addHistoryItem(ssc);
2178     }
2179
2180     repaint();
2181   }
2182
2183   /**
2184    * DOCUMENT ME!
2185    * 
2186    * @param e
2187    *          DOCUMENT ME!
2188    */
2189   @Override
2190   protected void copy_actionPerformed()
2191   {
2192     if (viewport.getSelectionGroup() == null)
2193     {
2194       return;
2195     }
2196     // TODO: preserve the ordering of displayed alignment annotation in any
2197     // internal paste (particularly sequence associated annotation)
2198     SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2199     String[] omitHidden = null;
2200
2201     if (viewport.hasHiddenColumns())
2202     {
2203       omitHidden = viewport.getViewAsString(true);
2204     }
2205
2206     String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2207             seqs, omitHidden, null);
2208
2209     StringSelection ss = new StringSelection(output);
2210
2211     try
2212     {
2213       jalview.gui.Desktop.internalCopy = true;
2214       // Its really worth setting the clipboard contents
2215       // to empty before setting the large StringSelection!!
2216       Toolkit.getDefaultToolkit().getSystemClipboard()
2217               .setContents(new StringSelection(""), null);
2218
2219       Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2220               Desktop.instance);
2221     } catch (OutOfMemoryError er)
2222     {
2223       new OOMWarning("copying region", er);
2224       return;
2225     }
2226
2227     HiddenColumns hiddenColumns = null;
2228     if (viewport.hasHiddenColumns())
2229     {
2230       int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2231       int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2232
2233       // create new HiddenColumns object with copy of hidden regions
2234       // between startRes and endRes, offset by startRes
2235       hiddenColumns = new HiddenColumns(
2236               viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2237               hiddenCutoff, hiddenOffset);
2238     }
2239
2240     Desktop.jalviewClipboard = new Object[] { seqs,
2241         viewport.getAlignment().getDataset(), hiddenColumns };
2242     setStatus(MessageManager.formatMessage(
2243             "label.copied_sequences_to_clipboard", new Object[]
2244             { Integer.valueOf(seqs.length).toString() }));
2245   }
2246
2247   /**
2248    * DOCUMENT ME!
2249    * 
2250    * @param e
2251    *          DOCUMENT ME!
2252    * @throws InterruptedException
2253    * @throws IOException
2254    */
2255   @Override
2256   protected void pasteNew_actionPerformed(ActionEvent e)
2257           throws IOException, InterruptedException
2258   {
2259     paste(true);
2260   }
2261
2262   /**
2263    * DOCUMENT ME!
2264    * 
2265    * @param e
2266    *          DOCUMENT ME!
2267    * @throws InterruptedException
2268    * @throws IOException
2269    */
2270   @Override
2271   protected void pasteThis_actionPerformed(ActionEvent e)
2272           throws IOException, InterruptedException
2273   {
2274     paste(false);
2275   }
2276
2277   /**
2278    * Paste contents of Jalview clipboard
2279    * 
2280    * @param newAlignment
2281    *          true to paste to a new alignment, otherwise add to this.
2282    * @throws InterruptedException
2283    * @throws IOException
2284    */
2285   void paste(boolean newAlignment) throws IOException, InterruptedException
2286   {
2287     boolean externalPaste = true;
2288     try
2289     {
2290       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2291       Transferable contents = c.getContents(this);
2292
2293       if (contents == null)
2294       {
2295         return;
2296       }
2297
2298       String str;
2299       FileFormatI format;
2300       try
2301       {
2302         str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2303         if (str.length() < 1)
2304         {
2305           return;
2306         }
2307
2308         format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2309
2310       } catch (OutOfMemoryError er)
2311       {
2312         new OOMWarning("Out of memory pasting sequences!!", er);
2313         return;
2314       }
2315
2316       SequenceI[] sequences;
2317       boolean annotationAdded = false;
2318       AlignmentI alignment = null;
2319
2320       if (Desktop.jalviewClipboard != null)
2321       {
2322         // The clipboard was filled from within Jalview, we must use the
2323         // sequences
2324         // And dataset from the copied alignment
2325         SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2326         // be doubly sure that we create *new* sequence objects.
2327         sequences = new SequenceI[newseq.length];
2328         for (int i = 0; i < newseq.length; i++)
2329         {
2330           sequences[i] = new Sequence(newseq[i]);
2331         }
2332         alignment = new Alignment(sequences);
2333         externalPaste = false;
2334       }
2335       else
2336       {
2337         // parse the clipboard as an alignment.
2338         alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2339                 format);
2340         sequences = alignment.getSequencesArray();
2341       }
2342
2343       int alwidth = 0;
2344       ArrayList<Integer> newGraphGroups = new ArrayList<>();
2345       int fgroup = -1;
2346
2347       if (newAlignment)
2348       {
2349
2350         if (Desktop.jalviewClipboard != null)
2351         {
2352           // dataset is inherited
2353           alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2354         }
2355         else
2356         {
2357           // new dataset is constructed
2358           alignment.setDataset(null);
2359         }
2360         alwidth = alignment.getWidth() + 1;
2361       }
2362       else
2363       {
2364         AlignmentI pastedal = alignment; // preserve pasted alignment object
2365         // Add pasted sequences and dataset into existing alignment.
2366         alignment = viewport.getAlignment();
2367         alwidth = alignment.getWidth() + 1;
2368         // decide if we need to import sequences from an existing dataset
2369         boolean importDs = Desktop.jalviewClipboard != null
2370                 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2371         // importDs==true instructs us to copy over new dataset sequences from
2372         // an existing alignment
2373         Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2374                                                                       // create
2375         // minimum dataset set
2376
2377         for (int i = 0; i < sequences.length; i++)
2378         {
2379           if (importDs)
2380           {
2381             newDs.addElement(null);
2382           }
2383           SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2384           // paste
2385           if (importDs && ds != null)
2386           {
2387             if (!newDs.contains(ds))
2388             {
2389               newDs.setElementAt(ds, i);
2390               ds = new Sequence(ds);
2391               // update with new dataset sequence
2392               sequences[i].setDatasetSequence(ds);
2393             }
2394             else
2395             {
2396               ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2397             }
2398           }
2399           else
2400           {
2401             // copy and derive new dataset sequence
2402             sequences[i] = sequences[i].deriveSequence();
2403             alignment.getDataset()
2404                     .addSequence(sequences[i].getDatasetSequence());
2405             // TODO: avoid creation of duplicate dataset sequences with a
2406             // 'contains' method using SequenceI.equals()/SequenceI.contains()
2407           }
2408           alignment.addSequence(sequences[i]); // merges dataset
2409         }
2410         if (newDs != null)
2411         {
2412           newDs.clear(); // tidy up
2413         }
2414         if (alignment.getAlignmentAnnotation() != null)
2415         {
2416           for (AlignmentAnnotation alan : alignment
2417                   .getAlignmentAnnotation())
2418           {
2419             if (alan.graphGroup > fgroup)
2420             {
2421               fgroup = alan.graphGroup;
2422             }
2423           }
2424         }
2425         if (pastedal.getAlignmentAnnotation() != null)
2426         {
2427           // Add any annotation attached to alignment.
2428           AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2429           for (int i = 0; i < alann.length; i++)
2430           {
2431             annotationAdded = true;
2432             if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2433             {
2434               AlignmentAnnotation newann = new AlignmentAnnotation(
2435                       alann[i]);
2436               if (newann.graphGroup > -1)
2437               {
2438                 if (newGraphGroups.size() <= newann.graphGroup
2439                         || newGraphGroups.get(newann.graphGroup) == null)
2440                 {
2441                   for (int q = newGraphGroups
2442                           .size(); q <= newann.graphGroup; q++)
2443                   {
2444                     newGraphGroups.add(q, null);
2445                   }
2446                   newGraphGroups.set(newann.graphGroup,
2447                           Integer.valueOf(++fgroup));
2448                 }
2449                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2450                         .intValue();
2451               }
2452
2453               newann.padAnnotation(alwidth);
2454               alignment.addAnnotation(newann);
2455             }
2456           }
2457         }
2458       }
2459       if (!newAlignment)
2460       {
2461         // /////
2462         // ADD HISTORY ITEM
2463         //
2464         addHistoryItem(new EditCommand(
2465                 MessageManager.getString("label.add_sequences"),
2466                 Action.PASTE, sequences, 0, alignment.getWidth(),
2467                 alignment));
2468       }
2469       // Add any annotations attached to sequences
2470       for (int i = 0; i < sequences.length; i++)
2471       {
2472         if (sequences[i].getAnnotation() != null)
2473         {
2474           AlignmentAnnotation newann;
2475           for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2476           {
2477             annotationAdded = true;
2478             newann = sequences[i].getAnnotation()[a];
2479             newann.adjustForAlignment();
2480             newann.padAnnotation(alwidth);
2481             if (newann.graphGroup > -1)
2482             {
2483               if (newann.graphGroup > -1)
2484               {
2485                 if (newGraphGroups.size() <= newann.graphGroup
2486                         || newGraphGroups.get(newann.graphGroup) == null)
2487                 {
2488                   for (int q = newGraphGroups
2489                           .size(); q <= newann.graphGroup; q++)
2490                   {
2491                     newGraphGroups.add(q, null);
2492                   }
2493                   newGraphGroups.set(newann.graphGroup,
2494                           Integer.valueOf(++fgroup));
2495                 }
2496                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2497                         .intValue();
2498               }
2499             }
2500             alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2501             // was
2502             // duplicated
2503             // earlier
2504             alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2505                     a);
2506           }
2507         }
2508       }
2509       if (!newAlignment)
2510       {
2511
2512         // propagate alignment changed.
2513         viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2514         if (annotationAdded)
2515         {
2516           // Duplicate sequence annotation in all views.
2517           AlignmentI[] alview = this.getViewAlignments();
2518           for (int i = 0; i < sequences.length; i++)
2519           {
2520             AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2521             if (sann == null)
2522             {
2523               continue;
2524             }
2525             for (int avnum = 0; avnum < alview.length; avnum++)
2526             {
2527               if (alview[avnum] != alignment)
2528               {
2529                 // duplicate in a view other than the one with input focus
2530                 int avwidth = alview[avnum].getWidth() + 1;
2531                 // this relies on sann being preserved after we
2532                 // modify the sequence's annotation array for each duplication
2533                 for (int a = 0; a < sann.length; a++)
2534                 {
2535                   AlignmentAnnotation newann = new AlignmentAnnotation(
2536                           sann[a]);
2537                   sequences[i].addAlignmentAnnotation(newann);
2538                   newann.padAnnotation(avwidth);
2539                   alview[avnum].addAnnotation(newann); // annotation was
2540                   // duplicated earlier
2541                   // TODO JAL-1145 graphGroups are not updated for sequence
2542                   // annotation added to several views. This may cause
2543                   // strangeness
2544                   alview[avnum].setAnnotationIndex(newann, a);
2545                 }
2546               }
2547             }
2548           }
2549           buildSortByAnnotationScoresMenu();
2550         }
2551         viewport.firePropertyChange("alignment", null,
2552                 alignment.getSequences());
2553         if (alignPanels != null)
2554         {
2555           for (AlignmentPanel ap : alignPanels)
2556           {
2557             ap.validateAnnotationDimensions(false);
2558           }
2559         }
2560         else
2561         {
2562           alignPanel.validateAnnotationDimensions(false);
2563         }
2564
2565       }
2566       else
2567       {
2568         AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2569                 DEFAULT_HEIGHT);
2570         String newtitle = new String("Copied sequences");
2571
2572         if (Desktop.jalviewClipboard != null
2573                 && Desktop.jalviewClipboard[2] != null)
2574         {
2575           HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2576           af.viewport.setHiddenColumns(hc);
2577         }
2578
2579         // >>>This is a fix for the moment, until a better solution is
2580         // found!!<<<
2581         af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2582                 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2583                         .getFeatureRenderer());
2584
2585         // TODO: maintain provenance of an alignment, rather than just make the
2586         // title a concatenation of operations.
2587         if (!externalPaste)
2588         {
2589           if (title.startsWith("Copied sequences"))
2590           {
2591             newtitle = title;
2592           }
2593           else
2594           {
2595             newtitle = newtitle.concat("- from " + title);
2596           }
2597         }
2598         else
2599         {
2600           newtitle = new String("Pasted sequences");
2601         }
2602
2603         Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2604                 DEFAULT_HEIGHT);
2605
2606       }
2607
2608     } catch (Exception ex)
2609     {
2610       ex.printStackTrace();
2611       System.out.println("Exception whilst pasting: " + ex);
2612       // could be anything being pasted in here
2613     }
2614   }
2615
2616   @Override
2617   protected void expand_newalign(ActionEvent e)
2618   {
2619     try
2620     {
2621       AlignmentI alignment = AlignmentUtils
2622               .expandContext(getViewport().getAlignment(), -1);
2623       AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2624               DEFAULT_HEIGHT);
2625       String newtitle = new String("Flanking alignment");
2626
2627       if (Desktop.jalviewClipboard != null
2628               && Desktop.jalviewClipboard[2] != null)
2629       {
2630         HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2631         af.viewport.setHiddenColumns(hc);
2632       }
2633
2634       // >>>This is a fix for the moment, until a better solution is
2635       // found!!<<<
2636       af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2637               .transferSettings(alignPanel.getSeqPanel().seqCanvas
2638                       .getFeatureRenderer());
2639
2640       // TODO: maintain provenance of an alignment, rather than just make the
2641       // title a concatenation of operations.
2642       {
2643         if (title.startsWith("Copied sequences"))
2644         {
2645           newtitle = title;
2646         }
2647         else
2648         {
2649           newtitle = newtitle.concat("- from " + title);
2650         }
2651       }
2652
2653       Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2654
2655     } catch (Exception ex)
2656     {
2657       ex.printStackTrace();
2658       System.out.println("Exception whilst pasting: " + ex);
2659       // could be anything being pasted in here
2660     } catch (OutOfMemoryError oom)
2661     {
2662       new OOMWarning("Viewing flanking region of alignment", oom);
2663     }
2664   }
2665
2666   /**
2667    * Action Cut (delete and copy) the selected region
2668    */
2669   @Override
2670   protected void cut_actionPerformed()
2671   {
2672     copy_actionPerformed();
2673     delete_actionPerformed();
2674   }
2675
2676   /**
2677    * Performs menu option to Delete the currently selected region
2678    */
2679   @Override
2680   protected void delete_actionPerformed()
2681   {
2682
2683     SequenceGroup sg = viewport.getSelectionGroup();
2684     if (sg == null)
2685     {
2686       return;
2687     }
2688
2689     Runnable okAction = new Runnable() 
2690     {
2691                 @Override
2692                 public void run() 
2693                 {
2694                     SequenceI[] cut = sg.getSequences()
2695                             .toArray(new SequenceI[sg.getSize()]);
2696
2697                     addHistoryItem(new EditCommand(
2698                             MessageManager.getString("label.cut_sequences"), Action.CUT,
2699                             cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2700                             viewport.getAlignment()));
2701
2702                     viewport.setSelectionGroup(null);
2703                     viewport.sendSelection();
2704                     viewport.getAlignment().deleteGroup(sg);
2705
2706                     viewport.firePropertyChange("alignment", null,
2707                             viewport.getAlignment().getSequences());
2708                     if (viewport.getAlignment().getHeight() < 1)
2709                     {
2710                       try
2711                       {
2712                         AlignFrame.this.setClosed(true);
2713                       } catch (Exception ex)
2714                       {
2715                       }
2716                     }
2717                 }};
2718
2719     /*
2720      * If the cut affects all sequences, prompt for confirmation
2721      */
2722     boolean wholeHeight = sg.getSize() == viewport.getAlignment().getHeight();
2723     boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2724             + 1) == viewport.getAlignment().getWidth()) ? true : false;
2725         if (wholeHeight && wholeWidth)
2726         {
2727             JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
2728                 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2729             Object[] options = new Object[] { MessageManager.getString("action.ok"),
2730                     MessageManager.getString("action.cancel") };
2731                 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2732                     MessageManager.getString("label.delete_all"),
2733                     JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2734                     options, options[0]);
2735         } else 
2736         {
2737                 okAction.run();
2738         }
2739   }
2740
2741   /**
2742    * DOCUMENT ME!
2743    * 
2744    * @param e
2745    *          DOCUMENT ME!
2746    */
2747   @Override
2748   protected void deleteGroups_actionPerformed(ActionEvent e)
2749   {
2750     if (avc.deleteGroups())
2751     {
2752       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2753       alignPanel.updateAnnotation();
2754       alignPanel.paintAlignment(true, true);
2755     }
2756   }
2757
2758   /**
2759    * DOCUMENT ME!
2760    * 
2761    * @param e
2762    *          DOCUMENT ME!
2763    */
2764   @Override
2765   public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2766   {
2767     SequenceGroup sg = new SequenceGroup(
2768             viewport.getAlignment().getSequences());
2769
2770     sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2771     viewport.setSelectionGroup(sg);
2772     viewport.isSelectionGroupChanged(true);
2773     viewport.sendSelection();
2774     // JAL-2034 - should delegate to
2775     // alignPanel to decide if overview needs
2776     // updating.
2777     alignPanel.paintAlignment(false, false);
2778     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2779   }
2780
2781   /**
2782    * DOCUMENT ME!
2783    * 
2784    * @param e
2785    *          DOCUMENT ME!
2786    */
2787   @Override
2788   public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2789   {
2790     if (viewport.cursorMode)
2791     {
2792       alignPanel.getSeqPanel().keyboardNo1 = null;
2793       alignPanel.getSeqPanel().keyboardNo2 = null;
2794     }
2795     viewport.setSelectionGroup(null);
2796     viewport.getColumnSelection().clear();
2797     viewport.setSelectionGroup(null);
2798     alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2799     // JAL-2034 - should delegate to
2800     // alignPanel to decide if overview needs
2801     // updating.
2802     alignPanel.paintAlignment(false, false);
2803     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2804     viewport.sendSelection();
2805   }
2806
2807   /**
2808    * DOCUMENT ME!
2809    * 
2810    * @param e
2811    *          DOCUMENT ME!
2812    */
2813   @Override
2814   public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2815   {
2816     SequenceGroup sg = viewport.getSelectionGroup();
2817
2818     if (sg == null)
2819     {
2820       selectAllSequenceMenuItem_actionPerformed(null);
2821
2822       return;
2823     }
2824
2825     for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2826     {
2827       sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2828     }
2829     // JAL-2034 - should delegate to
2830     // alignPanel to decide if overview needs
2831     // updating.
2832
2833     alignPanel.paintAlignment(true, false);
2834     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2835     viewport.sendSelection();
2836   }
2837
2838   @Override
2839   public void invertColSel_actionPerformed(ActionEvent e)
2840   {
2841     viewport.invertColumnSelection();
2842     alignPanel.paintAlignment(true, false);
2843     viewport.sendSelection();
2844   }
2845
2846   /**
2847    * DOCUMENT ME!
2848    * 
2849    * @param e
2850    *          DOCUMENT ME!
2851    */
2852   @Override
2853   public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2854   {
2855     trimAlignment(true);
2856   }
2857
2858   /**
2859    * DOCUMENT ME!
2860    * 
2861    * @param e
2862    *          DOCUMENT ME!
2863    */
2864   @Override
2865   public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2866   {
2867     trimAlignment(false);
2868   }
2869
2870   void trimAlignment(boolean trimLeft)
2871   {
2872     ColumnSelection colSel = viewport.getColumnSelection();
2873     int column;
2874
2875     if (!colSel.isEmpty())
2876     {
2877       if (trimLeft)
2878       {
2879         column = colSel.getMin();
2880       }
2881       else
2882       {
2883         column = colSel.getMax();
2884       }
2885
2886       SequenceI[] seqs;
2887       if (viewport.getSelectionGroup() != null)
2888       {
2889         seqs = viewport.getSelectionGroup()
2890                 .getSequencesAsArray(viewport.getHiddenRepSequences());
2891       }
2892       else
2893       {
2894         seqs = viewport.getAlignment().getSequencesArray();
2895       }
2896
2897       TrimRegionCommand trimRegion;
2898       if (trimLeft)
2899       {
2900         trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2901                 column, viewport.getAlignment());
2902         viewport.getRanges().setStartRes(0);
2903       }
2904       else
2905       {
2906         trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2907                 column, viewport.getAlignment());
2908       }
2909
2910       setStatus(MessageManager
2911               .formatMessage("label.removed_columns", new String[]
2912               { Integer.valueOf(trimRegion.getSize()).toString() }));
2913
2914       addHistoryItem(trimRegion);
2915
2916       for (SequenceGroup sg : viewport.getAlignment().getGroups())
2917       {
2918         if ((trimLeft && !sg.adjustForRemoveLeft(column))
2919                 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2920         {
2921           viewport.getAlignment().deleteGroup(sg);
2922         }
2923       }
2924
2925       viewport.firePropertyChange("alignment", null,
2926               viewport.getAlignment().getSequences());
2927     }
2928   }
2929
2930   /**
2931    * DOCUMENT ME!
2932    * 
2933    * @param e
2934    *          DOCUMENT ME!
2935    */
2936   @Override
2937   public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2938   {
2939     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2940
2941     SequenceI[] seqs;
2942     if (viewport.getSelectionGroup() != null)
2943     {
2944       seqs = viewport.getSelectionGroup()
2945               .getSequencesAsArray(viewport.getHiddenRepSequences());
2946       start = viewport.getSelectionGroup().getStartRes();
2947       end = viewport.getSelectionGroup().getEndRes();
2948     }
2949     else
2950     {
2951       seqs = viewport.getAlignment().getSequencesArray();
2952     }
2953
2954     RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2955             "Remove Gapped Columns", seqs, start, end,
2956             viewport.getAlignment());
2957
2958     addHistoryItem(removeGapCols);
2959
2960     setStatus(MessageManager
2961             .formatMessage("label.removed_empty_columns", new Object[]
2962             { Integer.valueOf(removeGapCols.getSize()).toString() }));
2963
2964     // This is to maintain viewport position on first residue
2965     // of first sequence
2966     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2967     ViewportRanges ranges = viewport.getRanges();
2968     int startRes = seq.findPosition(ranges.getStartRes());
2969     // ShiftList shifts;
2970     // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2971     // edit.alColumnChanges=shifts.getInverse();
2972     // if (viewport.hasHiddenColumns)
2973     // viewport.getColumnSelection().compensateForEdits(shifts);
2974     ranges.setStartRes(seq.findIndex(startRes) - 1);
2975     viewport.firePropertyChange("alignment", null,
2976             viewport.getAlignment().getSequences());
2977
2978   }
2979
2980   /**
2981    * DOCUMENT ME!
2982    * 
2983    * @param e
2984    *          DOCUMENT ME!
2985    */
2986   @Override
2987   public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2988   {
2989     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2990
2991     SequenceI[] seqs;
2992     if (viewport.getSelectionGroup() != null)
2993     {
2994       seqs = viewport.getSelectionGroup()
2995               .getSequencesAsArray(viewport.getHiddenRepSequences());
2996       start = viewport.getSelectionGroup().getStartRes();
2997       end = viewport.getSelectionGroup().getEndRes();
2998     }
2999     else
3000     {
3001       seqs = viewport.getAlignment().getSequencesArray();
3002     }
3003
3004     // This is to maintain viewport position on first residue
3005     // of first sequence
3006     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3007     int startRes = seq.findPosition(viewport.getRanges().getStartRes());
3008
3009     addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
3010             viewport.getAlignment()));
3011
3012     viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
3013
3014     viewport.firePropertyChange("alignment", null,
3015             viewport.getAlignment().getSequences());
3016
3017   }
3018
3019   /**
3020    * DOCUMENT ME!
3021    * 
3022    * @param e
3023    *          DOCUMENT ME!
3024    */
3025   @Override
3026   public void padGapsMenuitem_actionPerformed(ActionEvent e)
3027   {
3028     viewport.setPadGaps(padGapsMenuitem.isSelected());
3029     viewport.firePropertyChange("alignment", null,
3030             viewport.getAlignment().getSequences());
3031   }
3032
3033   /**
3034    * DOCUMENT ME!
3035    * 
3036    * @param e
3037    *          DOCUMENT ME!
3038    */
3039   @Override
3040   public void findMenuItem_actionPerformed(ActionEvent e)
3041   {
3042     new Finder();
3043   }
3044
3045   /**
3046    * Create a new view of the current alignment.
3047    */
3048   @Override
3049   public void newView_actionPerformed(ActionEvent e)
3050   {
3051     newView(null, true);
3052   }
3053
3054   /**
3055    * Creates and shows a new view of the current alignment.
3056    * 
3057    * @param viewTitle
3058    *          title of newly created view; if null, one will be generated
3059    * @param copyAnnotation
3060    *          if true then duplicate all annnotation, groups and settings
3061    * @return new alignment panel, already displayed.
3062    */
3063   public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
3064   {
3065     /*
3066      * Create a new AlignmentPanel (with its own, new Viewport)
3067      */
3068     AlignmentPanel newap = new jalview.project.Jalview2XML()
3069             .copyAlignPanel(alignPanel);
3070     if (!copyAnnotation)
3071     {
3072       /*
3073        * remove all groups and annotation except for the automatic stuff
3074        */
3075       newap.av.getAlignment().deleteAllGroups();
3076       newap.av.getAlignment().deleteAllAnnotations(false);
3077     }
3078
3079     newap.av.setGatherViewsHere(false);
3080
3081     if (viewport.getViewName() == null)
3082     {
3083       viewport.setViewName(MessageManager
3084               .getString("label.view_name_original"));
3085     }
3086
3087     /*
3088      * Views share the same edits undo and redo stacks
3089      */
3090     newap.av.setHistoryList(viewport.getHistoryList());
3091     newap.av.setRedoList(viewport.getRedoList());
3092
3093     /*
3094      * copy any visualisation settings that are not saved in the project
3095      */
3096     newap.av.setColourAppliesToAllGroups(
3097             viewport.getColourAppliesToAllGroups());
3098
3099     /*
3100      * Views share the same mappings; need to deregister any new mappings
3101      * created by copyAlignPanel, and register the new reference to the shared
3102      * mappings
3103      */
3104     newap.av.replaceMappings(viewport.getAlignment());
3105
3106     /*
3107      * start up cDNA consensus (if applicable) now mappings are in place
3108      */
3109     if (newap.av.initComplementConsensus())
3110     {
3111       newap.refresh(true); // adjust layout of annotations
3112     }
3113
3114     newap.av.setViewName(getNewViewName(viewTitle));
3115
3116     addAlignmentPanel(newap, true);
3117     newap.alignmentChanged();
3118
3119     if (alignPanels.size() == 2)
3120     {
3121       viewport.setGatherViewsHere(true);
3122     }
3123     tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3124     return newap;
3125   }
3126
3127   /**
3128    * Make a new name for the view, ensuring it is unique within the current
3129    * sequenceSetId. (This used to be essential for Jalview Project archives, but
3130    * these now use viewId. Unique view names are still desirable for usability.)
3131    * 
3132    * @param viewTitle
3133    * @return
3134    */
3135   protected String getNewViewName(String viewTitle)
3136   {
3137     int index = Desktop.getViewCount(viewport.getSequenceSetId());
3138     boolean addFirstIndex = false;
3139     if (viewTitle == null || viewTitle.trim().length() == 0)
3140     {
3141       viewTitle = MessageManager.getString("action.view");
3142       addFirstIndex = true;
3143     }
3144     else
3145     {
3146       index = 1;// we count from 1 if given a specific name
3147     }
3148     String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3149
3150     List<Component> comps = PaintRefresher.components
3151             .get(viewport.getSequenceSetId());
3152
3153     List<String> existingNames = getExistingViewNames(comps);
3154
3155     while (existingNames.contains(newViewName))
3156     {
3157       newViewName = viewTitle + " " + (++index);
3158     }
3159     return newViewName;
3160   }
3161
3162   /**
3163    * Returns a list of distinct view names found in the given list of
3164    * components. View names are held on the viewport of an AlignmentPanel.
3165    * 
3166    * @param comps
3167    * @return
3168    */
3169   protected List<String> getExistingViewNames(List<Component> comps)
3170   {
3171     List<String> existingNames = new ArrayList<>();
3172     for (Component comp : comps)
3173     {
3174       if (comp instanceof AlignmentPanel)
3175       {
3176         AlignmentPanel ap = (AlignmentPanel) comp;
3177         if (!existingNames.contains(ap.av.getViewName()))
3178         {
3179           existingNames.add(ap.av.getViewName());
3180         }
3181       }
3182     }
3183     return existingNames;
3184   }
3185
3186   /**
3187    * Explode tabbed views into separate windows.
3188    */
3189   @Override
3190   public void expandViews_actionPerformed(ActionEvent e)
3191   {
3192     Desktop.explodeViews(this);
3193   }
3194
3195   /**
3196    * Gather views in separate windows back into a tabbed presentation.
3197    */
3198   @Override
3199   public void gatherViews_actionPerformed(ActionEvent e)
3200   {
3201     Desktop.instance.gatherViews(this);
3202   }
3203
3204   /**
3205    * DOCUMENT ME!
3206    * 
3207    * @param e
3208    *          DOCUMENT ME!
3209    */
3210   @Override
3211   public void font_actionPerformed(ActionEvent e)
3212   {
3213     new FontChooser(alignPanel);
3214   }
3215
3216   /**
3217    * DOCUMENT ME!
3218    * 
3219    * @param e
3220    *          DOCUMENT ME!
3221    */
3222   @Override
3223   protected void seqLimit_actionPerformed(ActionEvent e)
3224   {
3225     viewport.setShowJVSuffix(seqLimits.isSelected());
3226
3227     alignPanel.getIdPanel().getIdCanvas()
3228             .setPreferredSize(alignPanel.calculateIdWidth());
3229     alignPanel.paintAlignment(true, false);
3230   }
3231
3232   @Override
3233   public void idRightAlign_actionPerformed(ActionEvent e)
3234   {
3235     viewport.setRightAlignIds(idRightAlign.isSelected());
3236     alignPanel.paintAlignment(false, false);
3237   }
3238
3239   @Override
3240   public void centreColumnLabels_actionPerformed(ActionEvent e)
3241   {
3242     viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3243     alignPanel.paintAlignment(false, false);
3244   }
3245
3246   /*
3247    * (non-Javadoc)
3248    * 
3249    * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3250    */
3251   @Override
3252   protected void followHighlight_actionPerformed()
3253   {
3254     /*
3255      * Set the 'follow' flag on the Viewport (and scroll to position if now
3256      * true).
3257      */
3258     final boolean state = this.followHighlightMenuItem.getState();
3259     viewport.setFollowHighlight(state);
3260     if (state)
3261     {
3262       alignPanel.scrollToPosition(viewport.getSearchResults());
3263     }
3264   }
3265
3266   /**
3267    * DOCUMENT ME!
3268    * 
3269    * @param e
3270    *          DOCUMENT ME!
3271    */
3272   @Override
3273   protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3274   {
3275     viewport.setColourText(colourTextMenuItem.isSelected());
3276     alignPanel.paintAlignment(false, false);
3277   }
3278
3279   /**
3280    * DOCUMENT ME!
3281    * 
3282    * @param e
3283    *          DOCUMENT ME!
3284    */
3285   @Override
3286   public void wrapMenuItem_actionPerformed(ActionEvent e)
3287   {
3288     scaleAbove.setVisible(wrapMenuItem.isSelected());
3289     scaleLeft.setVisible(wrapMenuItem.isSelected());
3290     scaleRight.setVisible(wrapMenuItem.isSelected());
3291     viewport.setWrapAlignment(wrapMenuItem.isSelected());
3292     alignPanel.updateLayout();
3293   }
3294
3295   @Override
3296   public void showAllSeqs_actionPerformed(ActionEvent e)
3297   {
3298     viewport.showAllHiddenSeqs();
3299   }
3300
3301   @Override
3302   public void showAllColumns_actionPerformed(ActionEvent e)
3303   {
3304     viewport.showAllHiddenColumns();
3305     alignPanel.paintAlignment(true, true);
3306     viewport.sendSelection();
3307   }
3308
3309   @Override
3310   public void hideSelSequences_actionPerformed(ActionEvent e)
3311   {
3312     viewport.hideAllSelectedSeqs();
3313   }
3314
3315   /**
3316    * called by key handler and the hide all/show all menu items
3317    * 
3318    * @param toggleSeqs
3319    * @param toggleCols
3320    */
3321   protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3322   {
3323
3324     boolean hide = false;
3325     SequenceGroup sg = viewport.getSelectionGroup();
3326     if (!toggleSeqs && !toggleCols)
3327     {
3328       // Hide everything by the current selection - this is a hack - we do the
3329       // invert and then hide
3330       // first check that there will be visible columns after the invert.
3331       if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3332               && sg.getStartRes() <= sg.getEndRes()))
3333       {
3334         // now invert the sequence set, if required - empty selection implies
3335         // that no hiding is required.
3336         if (sg != null)
3337         {
3338           invertSequenceMenuItem_actionPerformed(null);
3339           sg = viewport.getSelectionGroup();
3340           toggleSeqs = true;
3341
3342         }
3343         viewport.expandColSelection(sg, true);
3344         // finally invert the column selection and get the new sequence
3345         // selection.
3346         invertColSel_actionPerformed(null);
3347         toggleCols = true;
3348       }
3349     }
3350
3351     if (toggleSeqs)
3352     {
3353       if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3354       {
3355         hideSelSequences_actionPerformed(null);
3356         hide = true;
3357       }
3358       else if (!(toggleCols && viewport.hasSelectedColumns()))
3359       {
3360         showAllSeqs_actionPerformed(null);
3361       }
3362     }
3363
3364     if (toggleCols)
3365     {
3366       if (viewport.hasSelectedColumns())
3367       {
3368         hideSelColumns_actionPerformed(null);
3369         if (!toggleSeqs)
3370         {
3371           viewport.setSelectionGroup(sg);
3372         }
3373       }
3374       else if (!hide)
3375       {
3376         showAllColumns_actionPerformed(null);
3377       }
3378     }
3379   }
3380
3381   /*
3382    * (non-Javadoc)
3383    * 
3384    * @see
3385    * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3386    * event.ActionEvent)
3387    */
3388   @Override
3389   public void hideAllButSelection_actionPerformed(ActionEvent e)
3390   {
3391     toggleHiddenRegions(false, false);
3392     viewport.sendSelection();
3393   }
3394
3395   /*
3396    * (non-Javadoc)
3397    * 
3398    * @see
3399    * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3400    * .ActionEvent)
3401    */
3402   @Override
3403   public void hideAllSelection_actionPerformed(ActionEvent e)
3404   {
3405     SequenceGroup sg = viewport.getSelectionGroup();
3406     viewport.expandColSelection(sg, false);
3407     viewport.hideAllSelectedSeqs();
3408     viewport.hideSelectedColumns();
3409     alignPanel.updateLayout();
3410     alignPanel.paintAlignment(true, true);
3411     viewport.sendSelection();
3412   }
3413
3414   /*
3415    * (non-Javadoc)
3416    * 
3417    * @see
3418    * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3419    * ActionEvent)
3420    */
3421   @Override
3422   public void showAllhidden_actionPerformed(ActionEvent e)
3423   {
3424     viewport.showAllHiddenColumns();
3425     viewport.showAllHiddenSeqs();
3426     alignPanel.paintAlignment(true, true);
3427     viewport.sendSelection();
3428   }
3429
3430   @Override
3431   public void hideSelColumns_actionPerformed(ActionEvent e)
3432   {
3433     viewport.hideSelectedColumns();
3434     alignPanel.updateLayout();
3435     alignPanel.paintAlignment(true, true);
3436     viewport.sendSelection();
3437   }
3438
3439   @Override
3440   public void hiddenMarkers_actionPerformed(ActionEvent e)
3441   {
3442     viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3443     repaint();
3444   }
3445
3446   /**
3447    * DOCUMENT ME!
3448    * 
3449    * @param e
3450    *          DOCUMENT ME!
3451    */
3452   @Override
3453   protected void scaleAbove_actionPerformed(ActionEvent e)
3454   {
3455     viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3456     alignPanel.updateLayout();
3457     alignPanel.paintAlignment(true, false);
3458   }
3459
3460   /**
3461    * DOCUMENT ME!
3462    * 
3463    * @param e
3464    *          DOCUMENT ME!
3465    */
3466   @Override
3467   protected void scaleLeft_actionPerformed(ActionEvent e)
3468   {
3469     viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3470     alignPanel.updateLayout();
3471     alignPanel.paintAlignment(true, false);
3472   }
3473
3474   /**
3475    * DOCUMENT ME!
3476    * 
3477    * @param e
3478    *          DOCUMENT ME!
3479    */
3480   @Override
3481   protected void scaleRight_actionPerformed(ActionEvent e)
3482   {
3483     viewport.setScaleRightWrapped(scaleRight.isSelected());
3484     alignPanel.updateLayout();
3485     alignPanel.paintAlignment(true, false);
3486   }
3487
3488   /**
3489    * DOCUMENT ME!
3490    * 
3491    * @param e
3492    *          DOCUMENT ME!
3493    */
3494   @Override
3495   public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3496   {
3497     viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3498     alignPanel.paintAlignment(false, false);
3499   }
3500
3501   /**
3502    * DOCUMENT ME!
3503    * 
3504    * @param e
3505    *          DOCUMENT ME!
3506    */
3507   @Override
3508   public void viewTextMenuItem_actionPerformed(ActionEvent e)
3509   {
3510     viewport.setShowText(viewTextMenuItem.isSelected());
3511     alignPanel.paintAlignment(false, false);
3512   }
3513
3514   /**
3515    * DOCUMENT ME!
3516    * 
3517    * @param e
3518    *          DOCUMENT ME!
3519    */
3520   @Override
3521   protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3522   {
3523     viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3524     alignPanel.paintAlignment(false, false);
3525   }
3526
3527   public FeatureSettings featureSettings;
3528
3529   @Override
3530   public FeatureSettingsControllerI getFeatureSettingsUI()
3531   {
3532     return featureSettings;
3533   }
3534
3535   @Override
3536   public void featureSettings_actionPerformed(ActionEvent e)
3537   {
3538     showFeatureSettingsUI();
3539   }
3540
3541   @Override
3542   public FeatureSettingsControllerI showFeatureSettingsUI()
3543   {
3544     if (featureSettings != null)
3545     {
3546       featureSettings.closeOldSettings();
3547       featureSettings = null;
3548     }
3549     if (!showSeqFeatures.isSelected())
3550     {
3551       // make sure features are actually displayed
3552       showSeqFeatures.setSelected(true);
3553       showSeqFeatures_actionPerformed(null);
3554     }
3555     featureSettings = new FeatureSettings(this);
3556     return featureSettings;
3557   }
3558
3559   /**
3560    * Set or clear 'Show Sequence Features'
3561    * 
3562    * @param evt
3563    *          DOCUMENT ME!
3564    */
3565   @Override
3566   public void showSeqFeatures_actionPerformed(ActionEvent evt)
3567   {
3568     viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3569     alignPanel.paintAlignment(true, true);
3570   }
3571
3572   /**
3573    * Action on toggle of the 'Show annotations' menu item. This shows or hides
3574    * the annotations panel as a whole.
3575    * 
3576    * The options to show/hide all annotations should be enabled when the panel
3577    * is shown, and disabled when the panel is hidden.
3578    * 
3579    * @param e
3580    */
3581   @Override
3582   public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3583   {
3584     final boolean setVisible = annotationPanelMenuItem.isSelected();
3585     viewport.setShowAnnotation(setVisible);
3586     this.showAllSeqAnnotations.setEnabled(setVisible);
3587     this.hideAllSeqAnnotations.setEnabled(setVisible);
3588     this.showAllAlAnnotations.setEnabled(setVisible);
3589     this.hideAllAlAnnotations.setEnabled(setVisible);
3590     alignPanel.updateLayout();
3591   }
3592
3593   @Override
3594   public void alignmentProperties()
3595   {
3596     JComponent pane;
3597     StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3598
3599             .formatAsHtml();
3600     String content = MessageManager.formatMessage("label.html_content",
3601             new Object[]
3602             { contents.toString() });
3603     contents = null;
3604
3605     if (Platform.isJS())
3606     {
3607       JLabel textLabel = new JLabel();
3608       textLabel.setText(content);
3609       textLabel.setBackground(Color.WHITE);
3610       
3611       pane = new JPanel(new BorderLayout());
3612       ((JPanel) pane).setOpaque(true);
3613       pane.setBackground(Color.WHITE);
3614       ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3615     }
3616     else
3617     /**
3618      * Java only
3619      * 
3620      * @j2sIgnore
3621      */
3622     {
3623       JEditorPane editPane = new JEditorPane("text/html", "");
3624       editPane.setEditable(false);
3625       editPane.setText(content);
3626       pane = editPane;
3627     }
3628
3629     JInternalFrame frame = new JInternalFrame();
3630
3631     frame.getContentPane().add(new JScrollPane(pane));
3632
3633     Desktop.addInternalFrame(frame, MessageManager
3634             .formatMessage("label.alignment_properties", new Object[]
3635             { getTitle() }), 500, 400);
3636   }
3637
3638   /**
3639    * DOCUMENT ME!
3640    * 
3641    * @param e
3642    *          DOCUMENT ME!
3643    */
3644   @Override
3645   public void overviewMenuItem_actionPerformed(ActionEvent e)
3646   {
3647     if (alignPanel.overviewPanel != null)
3648     {
3649       return;
3650     }
3651
3652     JInternalFrame frame = new JInternalFrame();
3653     final OverviewPanel overview = new OverviewPanel(alignPanel);
3654     frame.setContentPane(overview);
3655     Desktop.addInternalFrame(frame, MessageManager
3656             .formatMessage("label.overview_params", new Object[]
3657             { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3658             true, true);
3659     frame.pack();
3660     frame.setLayer(JLayeredPane.PALETTE_LAYER);
3661     frame.addInternalFrameListener(
3662             new javax.swing.event.InternalFrameAdapter()
3663             {
3664               @Override
3665               public void internalFrameClosed(
3666                       javax.swing.event.InternalFrameEvent evt)
3667               {
3668                 overview.dispose();
3669                 alignPanel.setOverviewPanel(null);
3670               }
3671             });
3672     if (getKeyListeners().length > 0)
3673     {
3674       frame.addKeyListener(getKeyListeners()[0]);
3675     }
3676
3677     alignPanel.setOverviewPanel(overview);
3678   }
3679
3680   @Override
3681   public void textColour_actionPerformed()
3682   {
3683     new TextColourChooser().chooseColour(alignPanel, null);
3684   }
3685
3686   /*
3687    * public void covariationColour_actionPerformed() {
3688    * changeColour(new
3689    * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3690    * ()[0])); }
3691    */
3692   @Override
3693   public void annotationColour_actionPerformed()
3694   {
3695     new AnnotationColourChooser(viewport, alignPanel);
3696   }
3697
3698   @Override
3699   public void annotationColumn_actionPerformed(ActionEvent e)
3700   {
3701     new AnnotationColumnChooser(viewport, alignPanel);
3702   }
3703
3704   /**
3705    * Action on the user checking or unchecking the option to apply the selected
3706    * colour scheme to all groups. If unchecked, groups may have their own
3707    * independent colour schemes.
3708    * 
3709    * @param selected
3710    */
3711   @Override
3712   public void applyToAllGroups_actionPerformed(boolean selected)
3713   {
3714     viewport.setColourAppliesToAllGroups(selected);
3715   }
3716
3717   /**
3718    * Action on user selecting a colour from the colour menu
3719    * 
3720    * @param name
3721    *          the name (not the menu item label!) of the colour scheme
3722    */
3723   @Override
3724   public void changeColour_actionPerformed(String name)
3725   {
3726     /*
3727      * 'User Defined' opens a panel to configure or load a
3728      * user-defined colour scheme
3729      */
3730     if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3731     {
3732       new UserDefinedColours(alignPanel);
3733       return;
3734     }
3735
3736     /*
3737      * otherwise set the chosen colour scheme (or null for 'None')
3738      */
3739     ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3740             viewport,
3741             viewport.getAlignment(), viewport.getHiddenRepSequences());
3742     changeColour(cs);
3743   }
3744
3745   /**
3746    * Actions on setting or changing the alignment colour scheme
3747    * 
3748    * @param cs
3749    */
3750   @Override
3751   public void changeColour(ColourSchemeI cs)
3752   {
3753     // TODO: pull up to controller method
3754     ColourMenuHelper.setColourSelected(colourMenu, cs);
3755
3756     viewport.setGlobalColourScheme(cs);
3757
3758     alignPanel.paintAlignment(true, true);
3759   }
3760
3761   /**
3762    * Show the PID threshold slider panel
3763    */
3764   @Override
3765   protected void modifyPID_actionPerformed()
3766   {
3767     SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3768             alignPanel.getViewName());
3769     SliderPanel.showPIDSlider();
3770   }
3771
3772   /**
3773    * Show the Conservation slider panel
3774    */
3775   @Override
3776   protected void modifyConservation_actionPerformed()
3777   {
3778     SliderPanel.setConservationSlider(alignPanel,
3779             viewport.getResidueShading(), alignPanel.getViewName());
3780     SliderPanel.showConservationSlider();
3781   }
3782
3783   /**
3784    * Action on selecting or deselecting (Colour) By Conservation
3785    */
3786   @Override
3787   public void conservationMenuItem_actionPerformed(boolean selected)
3788   {
3789     modifyConservation.setEnabled(selected);
3790     viewport.setConservationSelected(selected);
3791     viewport.getResidueShading().setConservationApplied(selected);
3792
3793     changeColour(viewport.getGlobalColourScheme());
3794     if (selected)
3795     {
3796       modifyConservation_actionPerformed();
3797     }
3798     else
3799     {
3800       SliderPanel.hideConservationSlider();
3801     }
3802   }
3803
3804   /**
3805    * Action on selecting or deselecting (Colour) Above PID Threshold
3806    */
3807   @Override
3808   public void abovePIDThreshold_actionPerformed(boolean selected)
3809   {
3810     modifyPID.setEnabled(selected);
3811     viewport.setAbovePIDThreshold(selected);
3812     if (!selected)
3813     {
3814       viewport.getResidueShading().setThreshold(0,
3815               viewport.isIgnoreGapsConsensus());
3816     }
3817
3818     changeColour(viewport.getGlobalColourScheme());
3819     if (selected)
3820     {
3821       modifyPID_actionPerformed();
3822     }
3823     else
3824     {
3825       SliderPanel.hidePIDSlider();
3826     }
3827   }
3828
3829   /**
3830    * DOCUMENT ME!
3831    * 
3832    * @param e
3833    *          DOCUMENT ME!
3834    */
3835   @Override
3836   public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3837   {
3838     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3839     AlignmentSorter.sortByPID(viewport.getAlignment(),
3840             viewport.getAlignment().getSequenceAt(0));
3841     addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3842             viewport.getAlignment()));
3843     alignPanel.paintAlignment(true, false);
3844   }
3845
3846   /**
3847    * DOCUMENT ME!
3848    * 
3849    * @param e
3850    *          DOCUMENT ME!
3851    */
3852   @Override
3853   public void sortIDMenuItem_actionPerformed(ActionEvent e)
3854   {
3855     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3856     AlignmentSorter.sortByID(viewport.getAlignment());
3857     addHistoryItem(
3858             new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3859     alignPanel.paintAlignment(true, false);
3860   }
3861
3862   /**
3863    * DOCUMENT ME!
3864    * 
3865    * @param e
3866    *          DOCUMENT ME!
3867    */
3868   @Override
3869   public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3870   {
3871     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3872     AlignmentSorter.sortByLength(viewport.getAlignment());
3873     addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3874             viewport.getAlignment()));
3875     alignPanel.paintAlignment(true, false);
3876   }
3877
3878   /**
3879    * DOCUMENT ME!
3880    * 
3881    * @param e
3882    *          DOCUMENT ME!
3883    */
3884   @Override
3885   public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3886   {
3887     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3888     AlignmentSorter.sortByGroup(viewport.getAlignment());
3889     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3890             viewport.getAlignment()));
3891
3892     alignPanel.paintAlignment(true, false);
3893   }
3894
3895   @Override
3896   public void sortEValueMenuItem_actionPerformed(ActionEvent e)
3897   {
3898     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3899     AlignmentSorter.sortByEValue(viewport.getAlignment());
3900     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3901             viewport.getAlignment()));
3902     alignPanel.paintAlignment(true, false);
3903
3904   }
3905
3906   @Override
3907   public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
3908   {
3909     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3910     AlignmentSorter.sortByBitScore(viewport.getAlignment());
3911     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3912             viewport.getAlignment()));
3913     alignPanel.paintAlignment(true, false);
3914
3915   }
3916   
3917   /**
3918    * DOCUMENT ME!
3919    * 
3920    * @param e
3921    *          DOCUMENT ME!
3922    */
3923   @Override
3924   public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3925   {
3926     new RedundancyPanel(alignPanel, this);
3927   }
3928
3929   /**
3930    * DOCUMENT ME!
3931    * 
3932    * @param e
3933    *          DOCUMENT ME!
3934    */
3935   @Override
3936   public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3937   {
3938     if ((viewport.getSelectionGroup() == null)
3939             || (viewport.getSelectionGroup().getSize() < 2))
3940     {
3941       JvOptionPane.showInternalMessageDialog(this,
3942               MessageManager.getString(
3943                       "label.you_must_select_least_two_sequences"),
3944               MessageManager.getString("label.invalid_selection"),
3945               JvOptionPane.WARNING_MESSAGE);
3946     }
3947     else
3948     {
3949       JInternalFrame frame = new JInternalFrame();
3950       frame.setContentPane(new PairwiseAlignPanel(viewport));
3951       Desktop.addInternalFrame(frame,
3952               MessageManager.getString("action.pairwise_alignment"), 600,
3953               500);
3954     }
3955   }
3956
3957   @Override
3958   public void autoCalculate_actionPerformed(ActionEvent e)
3959   {
3960     viewport.autoCalculateConsensus = autoCalculate.isSelected();
3961     if (viewport.autoCalculateConsensus)
3962     {
3963       viewport.firePropertyChange("alignment", null,
3964               viewport.getAlignment().getSequences());
3965     }
3966   }
3967
3968   @Override
3969   public void sortByTreeOption_actionPerformed(ActionEvent e)
3970   {
3971     viewport.sortByTree = sortByTree.isSelected();
3972   }
3973
3974   @Override
3975   protected void listenToViewSelections_actionPerformed(ActionEvent e)
3976   {
3977     viewport.followSelection = listenToViewSelections.isSelected();
3978   }
3979
3980   /**
3981    * Constructs a tree panel and adds it to the desktop
3982    * 
3983    * @param type
3984    *          tree type (NJ or AV)
3985    * @param modelName
3986    *          name of score model used to compute the tree
3987    * @param options
3988    *          parameters for the distance or similarity calculation
3989    */
3990   void newTreePanel(String type, String modelName,
3991           SimilarityParamsI options)
3992   {
3993     String frameTitle = "";
3994     TreePanel tp;
3995
3996     boolean onSelection = false;
3997     if (viewport.getSelectionGroup() != null
3998             && viewport.getSelectionGroup().getSize() > 0)
3999     {
4000       SequenceGroup sg = viewport.getSelectionGroup();
4001
4002       /* Decide if the selection is a column region */
4003       for (SequenceI _s : sg.getSequences())
4004       {
4005         if (_s.getLength() < sg.getEndRes())
4006         {
4007           JvOptionPane.showMessageDialog(Desktop.desktop,
4008                   MessageManager.getString(
4009                           "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4010                   MessageManager.getString(
4011                           "label.sequences_selection_not_aligned"),
4012                   JvOptionPane.WARNING_MESSAGE);
4013
4014           return;
4015         }
4016       }
4017       onSelection = true;
4018     }
4019     else
4020     {
4021       if (viewport.getAlignment().getHeight() < 2)
4022       {
4023         return;
4024       }
4025     }
4026
4027     tp = new TreePanel(alignPanel, type, modelName, options);
4028     frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
4029
4030     frameTitle += " from ";
4031
4032     if (viewport.getViewName() != null)
4033     {
4034       frameTitle += viewport.getViewName() + " of ";
4035     }
4036
4037     frameTitle += this.title;
4038
4039     Desktop.addInternalFrame(tp, frameTitle, 600, 500);
4040   }
4041
4042   /**
4043    * DOCUMENT ME!
4044    * 
4045    * @param title
4046    *          DOCUMENT ME!
4047    * @param order
4048    *          DOCUMENT ME!
4049    */
4050   public void addSortByOrderMenuItem(String title,
4051           final AlignmentOrder order)
4052   {
4053     final JMenuItem item = new JMenuItem(MessageManager
4054             .formatMessage("action.by_title_param", new Object[]
4055             { title }));
4056     sort.add(item);
4057     item.addActionListener(new java.awt.event.ActionListener()
4058     {
4059       @Override
4060       public void actionPerformed(ActionEvent e)
4061       {
4062         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4063
4064         // TODO: JBPNote - have to map order entries to curent SequenceI
4065         // pointers
4066         AlignmentSorter.sortBy(viewport.getAlignment(), order);
4067
4068         addHistoryItem(new OrderCommand(order.getName(), oldOrder,
4069                 viewport.getAlignment()));
4070
4071         alignPanel.paintAlignment(true, false);
4072       }
4073     });
4074   }
4075
4076   /**
4077    * Add a new sort by annotation score menu item
4078    * 
4079    * @param sort
4080    *          the menu to add the option to
4081    * @param scoreLabel
4082    *          the label used to retrieve scores for each sequence on the
4083    *          alignment
4084    */
4085   public void addSortByAnnotScoreMenuItem(JMenu sort,
4086           final String scoreLabel)
4087   {
4088     final JMenuItem item = new JMenuItem(scoreLabel);
4089     sort.add(item);
4090     item.addActionListener(new java.awt.event.ActionListener()
4091     {
4092       @Override
4093       public void actionPerformed(ActionEvent e)
4094       {
4095         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4096         AlignmentSorter.sortByAnnotationScore(scoreLabel,
4097                 viewport.getAlignment());// ,viewport.getSelectionGroup());
4098         addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4099                 viewport.getAlignment()));
4100         alignPanel.paintAlignment(true, false);
4101       }
4102     });
4103   }
4104
4105   /**
4106    * last hash for alignment's annotation array - used to minimise cost of
4107    * rebuild.
4108    */
4109   protected int _annotationScoreVectorHash;
4110
4111   /**
4112    * search the alignment and rebuild the sort by annotation score submenu the
4113    * last alignment annotation vector hash is stored to minimize cost of
4114    * rebuilding in subsequence calls.
4115    * 
4116    */
4117   @Override
4118   public void buildSortByAnnotationScoresMenu()
4119   {
4120     if (viewport.getAlignment().getAlignmentAnnotation() == null)
4121     {
4122       return;
4123     }
4124
4125     if (viewport.getAlignment().getAlignmentAnnotation()
4126             .hashCode() == _annotationScoreVectorHash)
4127     {
4128       return;
4129     }
4130
4131     sortByAnnotScore.removeAll();
4132     Set<String> scoreSorts = new HashSet<>();
4133     for (SequenceI sqa : viewport.getAlignment().getSequences())
4134     {
4135       AlignmentAnnotation[] anns = sqa.getAnnotation();
4136       for (int i = 0; anns != null && i < anns.length; i++)
4137       {
4138         AlignmentAnnotation aa = anns[i];
4139         if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4140         {
4141           scoreSorts.add(aa.label);
4142         }
4143       }
4144     }
4145     for (String label : scoreSorts)
4146     {
4147       addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4148     }
4149     sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4150
4151     _annotationScoreVectorHash = viewport.getAlignment()
4152             .getAlignmentAnnotation().hashCode();
4153   }
4154
4155   /**
4156    * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4157    * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4158    * call. Listeners are added to remove the menu item when the treePanel is
4159    * closed, and adjust the tree leaf to sequence mapping when the alignment is
4160    * modified.
4161    */
4162   @Override
4163   public void buildTreeSortMenu()
4164   {
4165     sortByTreeMenu.removeAll();
4166
4167     List<Component> comps = PaintRefresher.components
4168             .get(viewport.getSequenceSetId());
4169     List<TreePanel> treePanels = new ArrayList<>();
4170     for (Component comp : comps)
4171     {
4172       if (comp instanceof TreePanel)
4173       {
4174         treePanels.add((TreePanel) comp);
4175       }
4176     }
4177
4178     if (treePanels.size() < 1)
4179     {
4180       sortByTreeMenu.setVisible(false);
4181       return;
4182     }
4183
4184     sortByTreeMenu.setVisible(true);
4185
4186     for (final TreePanel tp : treePanels)
4187     {
4188       final JMenuItem item = new JMenuItem(tp.getTitle());
4189       item.addActionListener(new java.awt.event.ActionListener()
4190       {
4191         @Override
4192         public void actionPerformed(ActionEvent e)
4193         {
4194           tp.sortByTree_actionPerformed();
4195           addHistoryItem(tp.sortAlignmentIn(alignPanel));
4196
4197         }
4198       });
4199
4200       sortByTreeMenu.add(item);
4201     }
4202   }
4203
4204   public boolean sortBy(AlignmentOrder alorder, String undoname)
4205   {
4206     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4207     AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4208     if (undoname != null)
4209     {
4210       addHistoryItem(new OrderCommand(undoname, oldOrder,
4211               viewport.getAlignment()));
4212     }
4213     alignPanel.paintAlignment(true, false);
4214     return true;
4215   }
4216
4217   /**
4218    * Work out whether the whole set of sequences or just the selected set will
4219    * be submitted for multiple alignment.
4220    * 
4221    */
4222   public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4223   {
4224     // Now, check we have enough sequences
4225     AlignmentView msa = null;
4226
4227     if ((viewport.getSelectionGroup() != null)
4228             && (viewport.getSelectionGroup().getSize() > 1))
4229     {
4230       // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4231       // some common interface!
4232       /*
4233        * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4234        * SequenceI[sz = seqs.getSize(false)];
4235        * 
4236        * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4237        * seqs.getSequenceAt(i); }
4238        */
4239       msa = viewport.getAlignmentView(true);
4240     }
4241     else if (viewport.getSelectionGroup() != null
4242             && viewport.getSelectionGroup().getSize() == 1)
4243     {
4244       int option = JvOptionPane.showConfirmDialog(this,
4245               MessageManager.getString("warn.oneseq_msainput_selection"),
4246               MessageManager.getString("label.invalid_selection"),
4247               JvOptionPane.OK_CANCEL_OPTION);
4248       if (option == JvOptionPane.OK_OPTION)
4249       {
4250         msa = viewport.getAlignmentView(false);
4251       }
4252     }
4253     else
4254     {
4255       msa = viewport.getAlignmentView(false);
4256     }
4257     return msa;
4258   }
4259
4260   /**
4261    * Decides what is submitted to a secondary structure prediction service: the
4262    * first sequence in the alignment, or in the current selection, or, if the
4263    * alignment is 'aligned' (ie padded with gaps), then the currently selected
4264    * region or the whole alignment. (where the first sequence in the set is the
4265    * one that the prediction will be for).
4266    */
4267   public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4268   {
4269     AlignmentView seqs = null;
4270
4271     if ((viewport.getSelectionGroup() != null)
4272             && (viewport.getSelectionGroup().getSize() > 0))
4273     {
4274       seqs = viewport.getAlignmentView(true);
4275     }
4276     else
4277     {
4278       seqs = viewport.getAlignmentView(false);
4279     }
4280     // limit sequences - JBPNote in future - could spawn multiple prediction
4281     // jobs
4282     // TODO: viewport.getAlignment().isAligned is a global state - the local
4283     // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4284     if (!viewport.getAlignment().isAligned(false))
4285     {
4286       seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4287       // TODO: if seqs.getSequences().length>1 then should really have warned
4288       // user!
4289
4290     }
4291     return seqs;
4292   }
4293
4294   /**
4295    * DOCUMENT ME!
4296    * 
4297    * @param e
4298    *          DOCUMENT ME!
4299    */
4300   @Override
4301   protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4302   {
4303     // Pick the tree file
4304     JalviewFileChooser chooser = new JalviewFileChooser(
4305             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4306     chooser.setFileView(new JalviewFileView());
4307     chooser.setDialogTitle(
4308             MessageManager.getString("label.select_newick_like_tree_file"));
4309     chooser.setToolTipText(
4310             MessageManager.getString("label.load_tree_file"));
4311
4312     chooser.setResponseHandler(0,new Runnable()
4313     {
4314       @Override
4315       public void run()
4316       {
4317         String filePath = chooser.getSelectedFile().getPath();
4318         Cache.setProperty("LAST_DIRECTORY", filePath);
4319         NewickFile fin = null;
4320         try
4321         {
4322           fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4323                   DataSourceType.FILE));
4324           viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4325         } catch (Exception ex)
4326         {
4327           JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4328                   MessageManager
4329                           .getString("label.problem_reading_tree_file"),
4330                   JvOptionPane.WARNING_MESSAGE);
4331           ex.printStackTrace();
4332         }
4333         if (fin != null && fin.hasWarningMessage())
4334         {
4335           JvOptionPane.showMessageDialog(Desktop.desktop,
4336                   fin.getWarningMessage(),
4337                   MessageManager.getString(
4338                           "label.possible_problem_with_tree_file"),
4339                   JvOptionPane.WARNING_MESSAGE);
4340         }
4341       }
4342     });
4343     chooser.showOpenDialog(this);
4344   }
4345
4346   public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4347   {
4348     return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4349   }
4350
4351   public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4352           int h, int x, int y)
4353   {
4354     return showNewickTree(nf, treeTitle, null, w, h, x, y);
4355   }
4356
4357   /**
4358    * Add a treeviewer for the tree extracted from a Newick file object to the
4359    * current alignment view
4360    * 
4361    * @param nf
4362    *          the tree
4363    * @param title
4364    *          tree viewer title
4365    * @param input
4366    *          Associated alignment input data (or null)
4367    * @param w
4368    *          width
4369    * @param h
4370    *          height
4371    * @param x
4372    *          position
4373    * @param y
4374    *          position
4375    * @return TreePanel handle
4376    */
4377   public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4378           AlignmentView input, int w, int h, int x, int y)
4379   {
4380     TreePanel tp = null;
4381
4382     try
4383     {
4384       nf.parse();
4385
4386       if (nf.getTree() != null)
4387       {
4388         tp = new TreePanel(alignPanel, nf, treeTitle, input);
4389
4390         tp.setSize(w, h);
4391
4392         if (x > 0 && y > 0)
4393         {
4394           tp.setLocation(x, y);
4395         }
4396
4397         Desktop.addInternalFrame(tp, treeTitle, w, h);
4398       }
4399     } catch (Exception ex)
4400     {
4401       ex.printStackTrace();
4402     }
4403
4404     return tp;
4405   }
4406
4407   private boolean buildingMenu = false;
4408
4409   /**
4410    * Generates menu items and listener event actions for web service clients
4411    * 
4412    */
4413   public void BuildWebServiceMenu()
4414   {
4415     while (buildingMenu)
4416     {
4417       try
4418       {
4419         System.err.println("Waiting for building menu to finish.");
4420         Thread.sleep(10);
4421       } catch (Exception e)
4422       {
4423       }
4424     }
4425     final AlignFrame me = this;
4426     buildingMenu = true;
4427     new Thread(new Runnable()
4428     {
4429       @Override
4430       public void run()
4431       {
4432         final List<JMenuItem> legacyItems = new ArrayList<>();
4433         try
4434         {
4435           // System.err.println("Building ws menu again "
4436           // + Thread.currentThread());
4437           // TODO: add support for context dependent disabling of services based
4438           // on
4439           // alignment and current selection
4440           // TODO: add additional serviceHandle parameter to specify abstract
4441           // handler
4442           // class independently of AbstractName
4443           // TODO: add in rediscovery GUI function to restart discoverer
4444           // TODO: group services by location as well as function and/or
4445           // introduce
4446           // object broker mechanism.
4447           final Vector<JMenu> wsmenu = new Vector<>();
4448           final IProgressIndicator af = me;
4449
4450           /*
4451            * do not i18n these strings - they are hard-coded in class
4452            * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4453            * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4454            */
4455           final JMenu msawsmenu = new JMenu("Alignment");
4456           final JMenu secstrmenu = new JMenu(
4457                   "Secondary Structure Prediction");
4458           final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4459           final JMenu analymenu = new JMenu("Analysis");
4460           final JMenu dismenu = new JMenu("Protein Disorder");
4461           // JAL-940 - only show secondary structure prediction services from
4462           // the legacy server
4463           if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4464               // &&
4465           Discoverer.services != null && (Discoverer.services.size() > 0))
4466           {
4467             // TODO: refactor to allow list of AbstractName/Handler bindings to
4468             // be
4469             // stored or retrieved from elsewhere
4470             // No MSAWS used any more:
4471             // Vector msaws = null; // (Vector)
4472             // Discoverer.services.get("MsaWS");
4473             Vector<ServiceHandle> secstrpr = Discoverer.services
4474                     .get("SecStrPred");
4475             if (secstrpr != null)
4476             {
4477               // Add any secondary structure prediction services
4478               for (int i = 0, j = secstrpr.size(); i < j; i++)
4479               {
4480                 final ext.vamsas.ServiceHandle sh = secstrpr
4481                         .get(i);
4482                 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4483                         .getServiceClient(sh);
4484                 int p = secstrmenu.getItemCount();
4485                 impl.attachWSMenuEntry(secstrmenu, me);
4486                 int q = secstrmenu.getItemCount();
4487                 for (int litm = p; litm < q; litm++)
4488                 {
4489                   legacyItems.add(secstrmenu.getItem(litm));
4490                 }
4491               }
4492             }
4493           }
4494
4495           // Add all submenus in the order they should appear on the web
4496           // services menu
4497           wsmenu.add(msawsmenu);
4498           wsmenu.add(secstrmenu);
4499           wsmenu.add(dismenu);
4500           wsmenu.add(analymenu);
4501           // No search services yet
4502           // wsmenu.add(seqsrchmenu);
4503
4504           javax.swing.SwingUtilities.invokeLater(new Runnable()
4505           {
4506             @Override
4507             public void run()
4508             {
4509               try
4510               {
4511                 webService.removeAll();
4512                 // first, add discovered services onto the webservices menu
4513                 if (wsmenu.size() > 0)
4514                 {
4515                   for (int i = 0, j = wsmenu.size(); i < j; i++)
4516                   {
4517                     webService.add(wsmenu.get(i));
4518                   }
4519                 }
4520                 else
4521                 {
4522                   webService.add(me.webServiceNoServices);
4523                 }
4524                 // TODO: move into separate menu builder class.
4525                 boolean new_sspred = false;
4526
4527                 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4528                 {
4529                   WSDiscovererI jws2servs = Jws2Discoverer.getDiscoverer();
4530                   if (jws2servs != null)
4531                   {
4532                     if (jws2servs.hasServices())
4533                     {
4534                       jws2servs.attachWSMenuEntry(webService, me);
4535                       for (ServiceWithParameters sv : jws2servs.getServices())
4536                       {
4537                         if (sv.getName().toLowerCase().contains("jpred"))
4538                         {
4539                           for (JMenuItem jmi : legacyItems)
4540                           {
4541                             jmi.setVisible(false);
4542                           }
4543                         }
4544                       }
4545
4546                     }
4547                     if (jws2servs.isRunning())
4548                     {
4549                       JMenuItem tm = new JMenuItem(
4550                               "Still discovering JABA Services");
4551                       tm.setEnabled(false);
4552                       webService.add(tm);
4553                     }
4554                   }
4555                 }
4556
4557                 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
4558                 {
4559                   WSDiscovererI discoverer = SlivkaWSDiscoverer
4560                           .getInstance();
4561                   if (discoverer != null)
4562                   {
4563                     if (discoverer.hasServices())
4564                     {
4565                       discoverer.attachWSMenuEntry(webService, me);
4566                     }
4567                     if (discoverer.isRunning())
4568                     {
4569                       JMenuItem tm = new JMenuItem(
4570                               "Still discovering Slivka Services");
4571                       tm.setEnabled(false);
4572                       webService.add(tm);
4573                     }
4574                   }
4575                 }
4576
4577                 build_urlServiceMenu(me.webService);
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 }