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