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