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