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