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