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