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