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