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