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