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