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