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