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