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