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