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