2ee86f1f86a39bc6034e0c905d4825fd1661c278
[jalview.git] / src / jalview / appletgui / 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.appletgui;
22
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AnnotationSorter.SequenceAnnotationOrder;
25 import jalview.api.AlignViewControllerGuiI;
26 import jalview.api.AlignViewControllerI;
27 import jalview.api.AlignViewportI;
28 import jalview.api.FeatureColourI;
29 import jalview.api.FeatureRenderer;
30 import jalview.api.FeatureSettingsControllerI;
31 import jalview.api.SequenceStructureBinding;
32 import jalview.bin.JalviewLite;
33 import jalview.commands.CommandI;
34 import jalview.commands.EditCommand;
35 import jalview.commands.EditCommand.Action;
36 import jalview.commands.OrderCommand;
37 import jalview.commands.RemoveGapColCommand;
38 import jalview.commands.RemoveGapsCommand;
39 import jalview.commands.SlideSequencesCommand;
40 import jalview.commands.TrimRegionCommand;
41 import jalview.datamodel.Alignment;
42 import jalview.datamodel.AlignmentAnnotation;
43 import jalview.datamodel.AlignmentI;
44 import jalview.datamodel.AlignmentOrder;
45 import jalview.datamodel.ColumnSelection;
46 import jalview.datamodel.PDBEntry;
47 import jalview.datamodel.Sequence;
48 import jalview.datamodel.SequenceGroup;
49 import jalview.datamodel.SequenceI;
50 import jalview.io.AnnotationFile;
51 import jalview.io.AppletFormatAdapter;
52 import jalview.io.DataSourceType;
53 import jalview.io.FeaturesFile;
54 import jalview.io.FileFormat;
55 import jalview.io.TCoffeeScoreFile;
56 import jalview.schemes.Blosum62ColourScheme;
57 import jalview.schemes.BuriedColourScheme;
58 import jalview.schemes.ClustalxColourScheme;
59 import jalview.schemes.ColourSchemeI;
60 import jalview.schemes.HelixColourScheme;
61 import jalview.schemes.HydrophobicColourScheme;
62 import jalview.schemes.NucleotideColourScheme;
63 import jalview.schemes.PIDColourScheme;
64 import jalview.schemes.PurinePyrimidineColourScheme;
65 import jalview.schemes.RNAHelicesColourChooser;
66 import jalview.schemes.StrandColourScheme;
67 import jalview.schemes.TCoffeeColourScheme;
68 import jalview.schemes.TaylorColourScheme;
69 import jalview.schemes.TurnColourScheme;
70 import jalview.schemes.ZappoColourScheme;
71 import jalview.structure.StructureSelectionManager;
72 import jalview.structures.models.AAStructureBindingModel;
73 import jalview.util.MappingUtils;
74 import jalview.util.MessageManager;
75 import jalview.viewmodel.AlignmentViewport;
76
77 import java.awt.BorderLayout;
78 import java.awt.Canvas;
79 import java.awt.CheckboxMenuItem;
80 import java.awt.Color;
81 import java.awt.FlowLayout;
82 import java.awt.Font;
83 import java.awt.FontMetrics;
84 import java.awt.Frame;
85 import java.awt.Graphics;
86 import java.awt.Label;
87 import java.awt.Menu;
88 import java.awt.MenuBar;
89 import java.awt.MenuItem;
90 import java.awt.Panel;
91 import java.awt.event.ActionEvent;
92 import java.awt.event.ActionListener;
93 import java.awt.event.FocusEvent;
94 import java.awt.event.FocusListener;
95 import java.awt.event.ItemEvent;
96 import java.awt.event.ItemListener;
97 import java.awt.event.KeyEvent;
98 import java.awt.event.KeyListener;
99 import java.awt.event.WindowAdapter;
100 import java.awt.event.WindowEvent;
101 import java.io.IOException;
102 import java.net.URL;
103 import java.net.URLEncoder;
104 import java.util.Arrays;
105 import java.util.Deque;
106 import java.util.HashMap;
107 import java.util.Hashtable;
108 import java.util.List;
109 import java.util.Map;
110 import java.util.StringTokenizer;
111 import java.util.Vector;
112
113 import org.jmol.viewer.Viewer;
114
115 public class AlignFrame extends EmbmenuFrame implements ActionListener,
116         ItemListener, KeyListener, AlignViewControllerGuiI
117 {
118   public AlignViewControllerI avc;
119
120   public AlignmentPanel alignPanel;
121
122   public AlignViewport viewport;
123
124   // width and height may be overridden by applet parameters
125   int frameWidth = 700;
126
127   int frameHeight = 500;
128
129   String jalviewServletURL;
130
131   /*
132    * Flag for showing autocalculated consensus above or below other consensus
133    * rows
134    */
135   private boolean showAutoCalculatedAbove;
136
137   private SequenceAnnotationOrder annotationSortOrder;
138
139   /**
140    * Constructor that creates the frame and adds it to the display.
141    * 
142    * @param al
143    * @param applet
144    * @param title
145    * @param embedded
146    */
147   public AlignFrame(AlignmentI al, JalviewLite applet, String title,
148           boolean embedded)
149   {
150     this(al, applet, title, embedded, true);
151   }
152
153   /**
154    * Constructor that optionally allows the frame to be displayed or only
155    * created.
156    * 
157    * @param al
158    * @param applet
159    * @param title
160    * @param embedded
161    * @param addToDisplay
162    */
163   public AlignFrame(AlignmentI al, JalviewLite applet, String title,
164           boolean embedded, boolean addToDisplay)
165   {
166     this(al, null, null, applet, title, embedded, addToDisplay);
167   }
168
169   public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
170           ColumnSelection columnSelection, JalviewLite applet,
171           String title, boolean embedded)
172   {
173     this(al, hiddenSeqs, columnSelection, applet, title, embedded, true);
174   }
175
176   public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
177           ColumnSelection columnSelection, JalviewLite applet,
178           String title, boolean embedded, boolean addToDisplay)
179   {
180     if (applet != null)
181     {
182       jalviewServletURL = applet.getParameter("APPLICATION_URL");
183     }
184
185     try
186     {
187       jbInit();
188     } catch (Exception ex)
189     {
190       ex.printStackTrace();
191     }
192     // need to get window geometry before we calculate alignment layout
193     if (applet != null)
194     {
195       String param;
196       try
197       {
198         param = applet.getParameter("windowWidth");
199         if (param != null)
200         {
201           int width = Integer.parseInt(param);
202           frameWidth = width;
203         }
204         param = applet.getParameter("windowHeight");
205         if (param != null)
206         {
207           int height = Integer.parseInt(param);
208           frameHeight = height;
209         }
210       } catch (Exception ex)
211       {
212       }
213     }
214     viewport = new AlignViewport(al, applet);
215
216     if (hiddenSeqs != null && hiddenSeqs.length > 0)
217     {
218       viewport.hideSequence(hiddenSeqs);
219     }
220     if (columnSelection != null)
221     {
222       viewport.setColumnSelection(columnSelection);
223     }
224     viewport.setScaleAboveWrapped(scaleAbove.getState());
225
226     alignPanel = new AlignmentPanel(this, viewport);
227     avc = new jalview.controller.AlignViewController(this, viewport,
228             alignPanel);
229     viewport.updateConservation(alignPanel);
230     viewport.updateConsensus(alignPanel);
231
232     displayNonconservedMenuItem.setState(viewport.getShowUnconserved());
233     followMouseOverFlag.setState(viewport.isFollowHighlight());
234     showGroupConsensus.setState(viewport.isShowGroupConsensus());
235     showGroupConservation.setState(viewport.isShowGroupConservation());
236     showConsensusHistogram.setState(viewport.isShowConsensusHistogram());
237     showSequenceLogo.setState(viewport.isShowSequenceLogo());
238     normSequenceLogo.setState(viewport.isNormaliseSequenceLogo());
239     applyToAllGroups.setState(viewport.getColourAppliesToAllGroups());
240     annotationPanelMenuItem.setState(viewport.isShowAnnotation());
241     showAlignmentAnnotations.setEnabled(annotationPanelMenuItem.getState());
242     showSequenceAnnotations.setEnabled(annotationPanelMenuItem.getState());
243     showAlignmentAnnotations.setState(true);
244     showSequenceAnnotations.setState(false);
245
246     seqLimits.setState(viewport.getShowJVSuffix());
247
248     if (applet != null)
249     {
250       String param = applet.getParameter("sortBy");
251       if (param != null)
252       {
253         if (param.equalsIgnoreCase("Id"))
254         {
255           sortIDMenuItem_actionPerformed();
256         }
257         else if (param.equalsIgnoreCase("Pairwise Identity"))
258         {
259           sortPairwiseMenuItem_actionPerformed();
260         }
261         else if (param.equalsIgnoreCase("Length"))
262         {
263           sortLengthMenuItem_actionPerformed();
264         }
265       }
266
267       param = applet.getParameter("wrap");
268       if (param != null)
269       {
270         if (param.equalsIgnoreCase("true"))
271         {
272           wrapMenuItem.setState(true);
273           wrapMenuItem_actionPerformed();
274         }
275       }
276       param = applet.getParameter("centrecolumnlabels");
277       if (param != null)
278       {
279         centreColumnLabelFlag.setState(true);
280         centreColumnLabelFlag_stateChanged();
281       }
282
283     }
284     if (viewport.getAlignment().isNucleotide())
285     {
286       viewport.updateStrucConsensus(alignPanel);
287       if (viewport.getAlignment().hasRNAStructure())
288       {
289         RNAHelixColour.setEnabled(true);
290       }
291       else
292       {
293         RNAHelixColour.setEnabled(false);
294       }
295     }
296     else
297     {
298       RNAHelixColour.setEnabled(false);
299       purinePyrimidineColour.setEnabled(false);
300     }
301     // Some JVMS send keyevents to Top frame or lowest panel,
302     // Havent worked out why yet. So add to both this frame and seqCanvas for
303     // now
304     this.addKeyListener(this);
305     alignPanel.seqPanel.seqCanvas.addKeyListener(this);
306     alignPanel.idPanel.idCanvas.addKeyListener(this);
307     alignPanel.scalePanel.addKeyListener(this);
308     alignPanel.annotationPanel.addKeyListener(this);
309     alignPanel.annotationPanelHolder.addKeyListener(this);
310     alignPanel.annotationSpaceFillerHolder.addKeyListener(this);
311     alignPanel.alabels.addKeyListener(this);
312
313     setAnnotationsVisibility();
314
315     if (addToDisplay)
316     {
317       addToDisplay(embedded);
318     }
319   }
320
321   /**
322    * @param embedded
323    */
324   public void addToDisplay(boolean embedded)
325   {
326     createAlignFrameWindow(embedded);
327     validate();
328     alignPanel.adjustAnnotationHeight();
329     alignPanel.paintAlignment(true);
330   }
331
332   public AlignViewport getAlignViewport()
333   {
334     return viewport;
335   }
336
337   public SeqCanvas getSeqcanvas()
338   {
339     return alignPanel.seqPanel.seqCanvas;
340   }
341
342   /**
343    * Load a features file onto the alignment
344    * 
345    * @param file
346    *          file URL, content, or other resolvable path
347    * @param type
348    *          is protocol for accessing data referred to by file
349    */
350
351   public boolean parseFeaturesFile(String file, DataSourceType type)
352   {
353     return parseFeaturesFile(file, type, true);
354   }
355
356   /**
357    * Load a features file onto the alignment
358    * 
359    * @param file
360    *          file URL, content, or other resolvable path
361    * @param paste
362    *          is protocol for accessing data referred to by file
363    * @param autoenabledisplay
364    *          when true, display features flag will be automatically enabled if
365    *          features are loaded
366    * @return true if data parsed as a features file
367    */
368   public boolean parseFeaturesFile(String file, DataSourceType paste,
369           boolean autoenabledisplay)
370   {
371     boolean featuresFile = false;
372     try
373     {
374       Map<String, FeatureColourI> colours = alignPanel.seqPanel.seqCanvas
375               .getFeatureRenderer().getFeatureColours();
376       boolean relaxedIdMatching = viewport.applet.getDefaultParameter(
377               "relaxedidmatch", false);
378       featuresFile = new FeaturesFile(file, paste).parse(
379               viewport.getAlignment(), colours, true, relaxedIdMatching);
380     } catch (Exception ex)
381     {
382       ex.printStackTrace();
383     }
384
385     if (featuresFile)
386     {
387       if (autoenabledisplay)
388       {
389         viewport.setShowSequenceFeatures(true);
390         sequenceFeatures.setState(true);
391       }
392       if (alignPanel.seqPanel.seqCanvas.fr != null)
393       {
394         // update the min/max ranges where necessary
395         alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
396       }
397       if (viewport.featureSettings != null)
398       {
399         viewport.featureSettings.refreshTable();
400       }
401       alignPanel.paintAlignment(true);
402       statusBar.setText(MessageManager
403               .getString("label.successfully_added_features_alignment"));
404     }
405     return featuresFile;
406   }
407
408   @Override
409   public void keyPressed(KeyEvent evt)
410   {
411     if (viewport.cursorMode
412             && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
413                     .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
414                     .getKeyCode() <= KeyEvent.VK_NUMPAD9))
415             && Character.isDigit(evt.getKeyChar()))
416     {
417       alignPanel.seqPanel.numberPressed(evt.getKeyChar());
418     }
419
420     switch (evt.getKeyCode())
421     {
422     case 27: // escape key
423       deselectAllSequenceMenuItem_actionPerformed();
424
425       alignPanel.alabels.cancelDrag();
426       break;
427     case KeyEvent.VK_X:
428       if (evt.isControlDown() || evt.isMetaDown())
429       {
430         cut_actionPerformed();
431       }
432       break;
433     case KeyEvent.VK_C:
434       if (viewport.cursorMode && !evt.isControlDown())
435       {
436         alignPanel.seqPanel.setCursorColumn();
437       }
438       if (evt.isControlDown() || evt.isMetaDown())
439       {
440         copy_actionPerformed();
441       }
442       break;
443     case KeyEvent.VK_V:
444       if (evt.isControlDown())
445       {
446         paste(evt.isShiftDown());
447       }
448       break;
449     case KeyEvent.VK_A:
450       if (evt.isControlDown() || evt.isMetaDown())
451       {
452         selectAllSequenceMenuItem_actionPerformed();
453       }
454       break;
455     case KeyEvent.VK_DOWN:
456       if (viewport.cursorMode)
457       {
458         alignPanel.seqPanel.moveCursor(0, 1);
459       }
460       else
461       {
462         moveSelectedSequences(false);
463       }
464       break;
465
466     case KeyEvent.VK_UP:
467       if (viewport.cursorMode)
468       {
469         alignPanel.seqPanel.moveCursor(0, -1);
470       }
471       else
472       {
473         moveSelectedSequences(true);
474       }
475       break;
476
477     case KeyEvent.VK_LEFT:
478       if (evt.isAltDown() || !viewport.cursorMode)
479       {
480         slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
481       }
482       else
483       {
484         alignPanel.seqPanel.moveCursor(-1, 0);
485       }
486       break;
487
488     case KeyEvent.VK_RIGHT:
489       if (evt.isAltDown() || !viewport.cursorMode)
490       {
491         slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
492       }
493       else
494       {
495         alignPanel.seqPanel.moveCursor(1, 0);
496       }
497       break;
498
499     case KeyEvent.VK_SPACE:
500       if (viewport.cursorMode)
501       {
502         alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
503                 || evt.isShiftDown() || evt.isAltDown());
504       }
505       break;
506
507     case KeyEvent.VK_DELETE:
508     case KeyEvent.VK_BACK_SPACE:
509       if (viewport.cursorMode)
510       {
511         alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
512                 || evt.isShiftDown() || evt.isAltDown());
513       }
514       else
515       {
516         cut_actionPerformed();
517         alignPanel.seqPanel.seqCanvas.repaint();
518       }
519       break;
520
521     case KeyEvent.VK_S:
522       if (viewport.cursorMode)
523       {
524         alignPanel.seqPanel.setCursorRow();
525       }
526       break;
527     case KeyEvent.VK_P:
528       if (viewport.cursorMode)
529       {
530         alignPanel.seqPanel.setCursorPosition();
531       }
532       break;
533
534     case KeyEvent.VK_ENTER:
535     case KeyEvent.VK_COMMA:
536       if (viewport.cursorMode)
537       {
538         alignPanel.seqPanel.setCursorRowAndColumn();
539       }
540       break;
541
542     case KeyEvent.VK_Q:
543       if (viewport.cursorMode)
544       {
545         alignPanel.seqPanel.setSelectionAreaAtCursor(true);
546       }
547       break;
548     case KeyEvent.VK_M:
549       if (viewport.cursorMode)
550       {
551         alignPanel.seqPanel.setSelectionAreaAtCursor(false);
552       }
553       break;
554
555     case KeyEvent.VK_F2:
556       viewport.cursorMode = !viewport.cursorMode;
557       statusBar.setText(MessageManager.formatMessage(
558               "label.keyboard_editing_mode",
559               new String[] { (viewport.cursorMode ? "on" : "off") }));
560       if (viewport.cursorMode)
561       {
562         alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
563         alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
564       }
565       break;
566
567     case KeyEvent.VK_F:
568       if (evt.isControlDown())
569       {
570         findMenuItem_actionPerformed();
571       }
572       break;
573
574     case KeyEvent.VK_H:
575     {
576       boolean toggleSeqs = !evt.isControlDown();
577       boolean toggleCols = !evt.isShiftDown();
578       toggleHiddenRegions(toggleSeqs, toggleCols);
579       break;
580     }
581
582     case KeyEvent.VK_PAGE_UP:
583       if (viewport.getWrapAlignment())
584       {
585         alignPanel.scrollUp(true);
586       }
587       else
588       {
589         alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
590                 - viewport.endSeq + viewport.startSeq);
591       }
592       break;
593
594     case KeyEvent.VK_PAGE_DOWN:
595       if (viewport.getWrapAlignment())
596       {
597         alignPanel.scrollUp(false);
598       }
599       else
600       {
601         alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
602                 + viewport.endSeq - viewport.startSeq);
603       }
604       break;
605
606     case KeyEvent.VK_Z:
607       if (evt.isControlDown())
608       {
609         undoMenuItem_actionPerformed();
610       }
611       break;
612
613     case KeyEvent.VK_Y:
614       if (evt.isControlDown())
615       {
616         redoMenuItem_actionPerformed();
617       }
618       break;
619
620     case KeyEvent.VK_L:
621       if (evt.isControlDown())
622       {
623         trimAlignment(true);
624       }
625       break;
626
627     case KeyEvent.VK_R:
628       if (evt.isControlDown())
629       {
630         trimAlignment(false);
631       }
632       break;
633
634     case KeyEvent.VK_E:
635       if (evt.isControlDown())
636       {
637         if (evt.isShiftDown())
638         {
639           this.removeAllGapsMenuItem_actionPerformed();
640         }
641         else
642         {
643           removeGappedColumnMenuItem_actionPerformed();
644         }
645       }
646       break;
647     case KeyEvent.VK_I:
648       if (evt.isControlDown())
649       {
650         if (evt.isAltDown())
651         {
652           invertColSel_actionPerformed();
653         }
654         else
655         {
656           invertSequenceMenuItem_actionPerformed();
657         }
658       }
659       break;
660
661     case KeyEvent.VK_G:
662       if (evt.isControlDown())
663       {
664         if (evt.isShiftDown())
665         {
666           this.unGroup_actionPerformed();
667         }
668         else
669         {
670           this.createGroup_actionPerformed();
671         }
672       }
673       break;
674
675     case KeyEvent.VK_U:
676       if (evt.isControlDown())
677       {
678         this.deleteGroups_actionPerformed();
679       }
680       break;
681
682     case KeyEvent.VK_T:
683       if (evt.isControlDown())
684       {
685         newView(null);
686       }
687       break;
688
689     }
690     alignPanel.paintAlignment(true);
691   }
692
693   /**
694    * called by key handler and the hide all/show all menu items
695    * 
696    * @param toggleSeqs
697    * @param toggleCols
698    */
699   private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
700   {
701     boolean hide = false;
702     SequenceGroup sg = viewport.getSelectionGroup();
703     if (!toggleSeqs && !toggleCols)
704     {
705       // Hide everything by the current selection - this is a hack - we do the
706       // invert and then hide
707       // first check that there will be visible columns after the invert.
708       if ((viewport.getColumnSelection() != null
709               && viewport.getColumnSelection().getSelected() != null && viewport
710               .getColumnSelection().getSelected().size() > 0)
711               || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
712                       .getEndRes()))
713       {
714         // now invert the sequence set, if required - empty selection implies
715         // that no hiding is required.
716         if (sg != null)
717         {
718           invertSequenceMenuItem_actionPerformed();
719           sg = viewport.getSelectionGroup();
720           toggleSeqs = true;
721
722         }
723         viewport.expandColSelection(sg, true);
724         // finally invert the column selection and get the new sequence
725         // selection and indicate it should be hidden.
726         invertColSel_actionPerformed();
727         toggleCols = true;
728       }
729     }
730
731     if (toggleSeqs)
732     {
733       if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
734       {
735         hide = true;
736         viewport.hideAllSelectedSeqs();
737       }
738       else if (!(toggleCols && viewport.getColumnSelection().getSelected()
739               .size() > 0))
740       {
741         viewport.showAllHiddenSeqs();
742       }
743     }
744
745     if (toggleCols)
746     {
747       if (viewport.getColumnSelection().getSelected().size() > 0)
748       {
749         viewport.hideSelectedColumns();
750         if (!toggleSeqs)
751         {
752           viewport.setSelectionGroup(sg);
753         }
754       }
755       else if (!hide)
756       {
757         viewport.showAllHiddenColumns();
758       }
759       viewport.sendSelection();
760     }
761   }
762
763   @Override
764   public void keyReleased(KeyEvent evt)
765   {
766   }
767
768   @Override
769   public void keyTyped(KeyEvent evt)
770   {
771   }
772
773   @Override
774   public void itemStateChanged(ItemEvent evt)
775   {
776     final Object source = evt.getSource();
777     if (source == displayNonconservedMenuItem)
778     {
779       displayNonconservedMenuItem_actionPerformed();
780     }
781     else if (source == colourTextMenuItem)
782     {
783       colourTextMenuItem_actionPerformed();
784     }
785     else if (source == wrapMenuItem)
786     {
787       wrapMenuItem_actionPerformed();
788     }
789     else if (source == scaleAbove)
790     {
791       viewport.setScaleAboveWrapped(scaleAbove.getState());
792     }
793     else if (source == scaleLeft)
794     {
795       viewport.setScaleLeftWrapped(scaleLeft.getState());
796     }
797     else if (source == scaleRight)
798     {
799       viewport.setScaleRightWrapped(scaleRight.getState());
800     }
801     else if (source == seqLimits)
802     {
803       seqLimits_itemStateChanged();
804     }
805     else if (source == viewBoxesMenuItem)
806     {
807       viewport.setShowBoxes(viewBoxesMenuItem.getState());
808     }
809     else if (source == viewTextMenuItem)
810     {
811       viewport.setShowText(viewTextMenuItem.getState());
812     }
813     else if (source == renderGapsMenuItem)
814     {
815       viewport.setRenderGaps(renderGapsMenuItem.getState());
816     }
817     else if (source == annotationPanelMenuItem)
818     {
819       boolean showAnnotations = annotationPanelMenuItem.getState();
820       showAlignmentAnnotations.setEnabled(showAnnotations);
821       showSequenceAnnotations.setEnabled(showAnnotations);
822       viewport.setShowAnnotation(showAnnotations);
823       alignPanel.setAnnotationVisible(showAnnotations);
824     }
825     else if (source == sequenceFeatures)
826     {
827       viewport.setShowSequenceFeatures(sequenceFeatures.getState());
828       alignPanel.seqPanel.seqCanvas.repaint();
829     }
830     else if (source == showAlignmentAnnotations)
831     {
832       setAnnotationsVisibility();
833     }
834     else if (source == showSequenceAnnotations)
835     {
836       setAnnotationsVisibility();
837     }
838     else if (source == sortAnnBySequence)
839     {
840       boolean newState = sortAnnBySequence.getState();
841       sortAnnByLabel.setState(false);
842       setAnnotationSortOrder(newState ? SequenceAnnotationOrder.SEQUENCE_AND_LABEL
843               : SequenceAnnotationOrder.NONE);
844       setViewportAnnotationOrder();
845     }
846     else if (source == sortAnnByLabel)
847     {
848       boolean newState = sortAnnByLabel.getState();
849       sortAnnBySequence.setState(false);
850       setAnnotationSortOrder(newState ? SequenceAnnotationOrder.LABEL_AND_SEQUENCE
851               : SequenceAnnotationOrder.NONE);
852       setViewportAnnotationOrder();
853     }
854     else if (source == showAutoFirst)
855     {
856       showAutoLast.setState(!showAutoFirst.getState());
857       setShowAutoCalculatedAbove(showAutoFirst.getState());
858       setViewportAnnotationOrder();
859     }
860     else if (source == showAutoLast)
861     {
862       showAutoFirst.setState(!showAutoLast.getState());
863       setShowAutoCalculatedAbove(showAutoFirst.getState());
864       setViewportAnnotationOrder();
865     }
866     else if (source == conservationMenuItem)
867     {
868       conservationMenuItem_actionPerformed();
869     }
870     else if (source == abovePIDThreshold)
871     {
872       abovePIDThreshold_actionPerformed();
873     }
874     else if (source == applyToAllGroups)
875     {
876       viewport.setColourAppliesToAllGroups(applyToAllGroups.getState());
877     }
878     else if (source == autoCalculate)
879     {
880       viewport.autoCalculateConsensus = autoCalculate.getState();
881     }
882     else if (source == sortByTree)
883     {
884       viewport.sortByTree = sortByTree.getState();
885     }
886     else if (source == this.centreColumnLabelFlag)
887     {
888       centreColumnLabelFlag_stateChanged();
889     }
890     else if (source == this.followMouseOverFlag)
891     {
892       mouseOverFlag_stateChanged();
893     }
894     else if (source == showGroupConsensus)
895     {
896       showGroupConsensus_actionPerformed();
897     }
898     else if (source == showGroupConservation)
899     {
900       showGroupConservation_actionPerformed();
901     }
902     else if (source == showSequenceLogo)
903     {
904       showSequenceLogo_actionPerformed();
905     }
906     else if (source == normSequenceLogo)
907     {
908       normSequenceLogo_actionPerformed();
909     }
910     else if (source == showConsensusHistogram)
911     {
912       showConsensusHistogram_actionPerformed();
913     }
914     else if (source == applyAutoAnnotationSettings)
915     {
916       applyAutoAnnotationSettings_actionPerformed();
917     }
918     alignPanel.paintAlignment(true);
919   }
920
921   /**
922    * Set the visibility state of sequence-related and/or alignment-related
923    * annotations depending on checkbox selections, and repaint.
924    * 
925    * @param visible
926    */
927   private void setAnnotationsVisibility()
928   {
929     boolean showForAlignment = showAlignmentAnnotations.getState();
930     boolean showForSequences = showSequenceAnnotations.getState();
931     if (alignPanel.getAlignment().getAlignmentAnnotation() != null)
932     {
933       for (AlignmentAnnotation aa : alignPanel.getAlignment()
934             .getAlignmentAnnotation())
935     {
936       boolean visible = (aa.sequenceRef == null ? showForAlignment
937               : showForSequences);
938       aa.visible = visible;
939       }
940     }
941     alignPanel.validateAnnotationDimensions(true);
942     validate();
943     repaint();
944   }
945
946   private void setAnnotationSortOrder(SequenceAnnotationOrder order)
947   {
948     this.annotationSortOrder = order;
949   }
950
951   /**
952    * Set flags on the viewport that control annotation ordering
953    */
954   private void setViewportAnnotationOrder()
955   {
956     this.alignPanel.av.setSortAnnotationsBy(this.annotationSortOrder);
957     this.alignPanel.av
958             .setShowAutocalculatedAbove(this.showAutoCalculatedAbove);
959   }
960
961   private void setShowAutoCalculatedAbove(boolean showAbove)
962   {
963     this.showAutoCalculatedAbove = showAbove;
964   }
965
966   private void mouseOverFlag_stateChanged()
967   {
968     viewport.setFollowHighlight(followMouseOverFlag.getState());
969     // TODO: could kick the scrollTo mechanism to reset view for current
970     // searchresults.
971   }
972
973   private void centreColumnLabelFlag_stateChanged()
974   {
975     viewport.centreColumnLabels = centreColumnLabelFlag.getState();
976     this.alignPanel.annotationPanel.repaint();
977   }
978
979   @Override
980   public void actionPerformed(ActionEvent evt)
981   {
982     viewport.applet.currentAlignFrame = this;
983
984     Object source = evt.getSource();
985
986     if (source == inputText)
987     {
988       inputText_actionPerformed();
989     }
990     else if (source == loadTree)
991     {
992       loadTree_actionPerformed();
993     }
994     else if (source == loadApplication)
995     {
996       launchFullApplication();
997     }
998     else if (source == loadAnnotations)
999     {
1000       loadAnnotations();
1001     }
1002     else if (source == outputAnnotations)
1003     {
1004       outputAnnotations(true);
1005     }
1006     else if (source == outputFeatures)
1007     {
1008       outputFeatures(true, "Jalview");
1009     }
1010     else if (source == closeMenuItem)
1011     {
1012       closeMenuItem_actionPerformed();
1013     }
1014     else if (source == copy)
1015     {
1016       copy_actionPerformed();
1017     }
1018     else if (source == undoMenuItem)
1019     {
1020       undoMenuItem_actionPerformed();
1021     }
1022     else if (source == redoMenuItem)
1023     {
1024       redoMenuItem_actionPerformed();
1025     }
1026     else if (source == inputText)
1027     {
1028       inputText_actionPerformed();
1029     }
1030     else if (source == closeMenuItem)
1031     {
1032       closeMenuItem_actionPerformed();
1033     }
1034     else if (source == undoMenuItem)
1035     {
1036       undoMenuItem_actionPerformed();
1037     }
1038     else if (source == redoMenuItem)
1039     {
1040       redoMenuItem_actionPerformed();
1041     }
1042     else if (source == copy)
1043     {
1044       copy_actionPerformed();
1045     }
1046     else if (source == pasteNew)
1047     {
1048       pasteNew_actionPerformed();
1049     }
1050     else if (source == pasteThis)
1051     {
1052       pasteThis_actionPerformed();
1053     }
1054     else if (source == cut)
1055     {
1056       cut_actionPerformed();
1057     }
1058     else if (source == delete)
1059     {
1060       delete_actionPerformed();
1061     }
1062     else if (source == grpsFromSelection)
1063     {
1064       makeGrpsFromSelection_actionPerformed();
1065     }
1066     else if (source == deleteGroups)
1067     {
1068       deleteGroups_actionPerformed();
1069     }
1070     else if (source == selectAllSequenceMenuItem)
1071     {
1072       selectAllSequenceMenuItem_actionPerformed();
1073     }
1074     else if (source == deselectAllSequenceMenuItem)
1075     {
1076       deselectAllSequenceMenuItem_actionPerformed();
1077     }
1078     else if (source == invertSequenceMenuItem)
1079     {
1080       invertSequenceMenuItem_actionPerformed();
1081       // uncomment to slave sequence selections in split frame
1082       // viewport.sendSelection();
1083     }
1084     else if (source == invertColSel)
1085     {
1086       viewport.invertColumnSelection();
1087       alignPanel.paintAlignment(true);
1088       viewport.sendSelection();
1089     }
1090     else if (source == remove2LeftMenuItem)
1091     {
1092       trimAlignment(true);
1093     }
1094     else if (source == remove2RightMenuItem)
1095     {
1096       trimAlignment(false);
1097     }
1098     else if (source == removeGappedColumnMenuItem)
1099     {
1100       removeGappedColumnMenuItem_actionPerformed();
1101     }
1102     else if (source == removeAllGapsMenuItem)
1103     {
1104       removeAllGapsMenuItem_actionPerformed();
1105     }
1106     else if (source == findMenuItem)
1107     {
1108       findMenuItem_actionPerformed();
1109     }
1110     else if (source == font)
1111     {
1112       new FontChooser(alignPanel);
1113     }
1114     else if (source == newView)
1115     {
1116       newView(null);
1117     }
1118     else if (source == showColumns)
1119     {
1120       viewport.showAllHiddenColumns();
1121       alignPanel.paintAlignment(true);
1122       viewport.sendSelection();
1123     }
1124     else if (source == showSeqs)
1125     {
1126       viewport.showAllHiddenSeqs();
1127       alignPanel.paintAlignment(true);
1128       // uncomment if we want to slave sequence selections in split frame
1129       // viewport.sendSelection();
1130     }
1131     else if (source == hideColumns)
1132     {
1133       viewport.hideSelectedColumns();
1134       alignPanel.paintAlignment(true);
1135       viewport.sendSelection();
1136     }
1137     else if (source == hideSequences
1138             && viewport.getSelectionGroup() != null)
1139     {
1140       viewport.hideAllSelectedSeqs();
1141       alignPanel.paintAlignment(true);
1142       // uncomment if we want to slave sequence selections in split frame
1143       // viewport.sendSelection();
1144     }
1145     else if (source == hideAllButSelection)
1146     {
1147       toggleHiddenRegions(false, false);
1148       alignPanel.paintAlignment(true);
1149       viewport.sendSelection();
1150     }
1151     else if (source == hideAllSelection)
1152     {
1153       SequenceGroup sg = viewport.getSelectionGroup();
1154       viewport.expandColSelection(sg, false);
1155       viewport.hideAllSelectedSeqs();
1156       viewport.hideSelectedColumns();
1157       alignPanel.paintAlignment(true);
1158       viewport.sendSelection();
1159     }
1160     else if (source == showAllHidden)
1161     {
1162       viewport.showAllHiddenColumns();
1163       viewport.showAllHiddenSeqs();
1164       alignPanel.paintAlignment(true);
1165       viewport.sendSelection();
1166     }
1167     else if (source == showGroupConsensus)
1168     {
1169       showGroupConsensus_actionPerformed();
1170     }
1171     else if (source == showGroupConservation)
1172     {
1173       showGroupConservation_actionPerformed();
1174     }
1175     else if (source == showSequenceLogo)
1176     {
1177       showSequenceLogo_actionPerformed();
1178     }
1179     else if (source == normSequenceLogo)
1180     {
1181       normSequenceLogo_actionPerformed();
1182     }
1183     else if (source == showConsensusHistogram)
1184     {
1185       showConsensusHistogram_actionPerformed();
1186     }
1187     else if (source == applyAutoAnnotationSettings)
1188     {
1189       applyAutoAnnotationSettings_actionPerformed();
1190     }
1191     else if (source == featureSettings)
1192     {
1193       new FeatureSettings(alignPanel);
1194     }
1195     else if (source == alProperties)
1196     {
1197       StringBuffer contents = new jalview.io.AlignmentProperties(
1198               viewport.getAlignment()).formatAsString();
1199       CutAndPasteTransfer cap = new CutAndPasteTransfer(false, this);
1200       cap.setText(contents.toString());
1201       Frame frame = new Frame();
1202       frame.add(cap);
1203       jalview.bin.JalviewLite.addFrame(frame, MessageManager.formatMessage(
1204               "label.alignment_properties", new String[] { getTitle() }),
1205               400, 250);
1206     }
1207     else if (source == overviewMenuItem)
1208     {
1209       overviewMenuItem_actionPerformed();
1210     }
1211     else if (source == noColourmenuItem)
1212     {
1213       changeColour(null);
1214     }
1215     else if (source == clustalColour)
1216     {
1217       abovePIDThreshold.setState(false);
1218       changeColour(new ClustalxColourScheme(viewport.getAlignment(), null));
1219     }
1220     else if (source == zappoColour)
1221     {
1222       changeColour(new ZappoColourScheme());
1223     }
1224     else if (source == taylorColour)
1225     {
1226       changeColour(new TaylorColourScheme());
1227     }
1228     else if (source == hydrophobicityColour)
1229     {
1230       changeColour(new HydrophobicColourScheme());
1231     }
1232     else if (source == helixColour)
1233     {
1234       changeColour(new HelixColourScheme());
1235     }
1236     else if (source == strandColour)
1237     {
1238       changeColour(new StrandColourScheme());
1239     }
1240     else if (source == turnColour)
1241     {
1242       changeColour(new TurnColourScheme());
1243     }
1244     else if (source == buriedColour)
1245     {
1246       changeColour(new BuriedColourScheme());
1247     }
1248     else if (source == nucleotideColour)
1249     {
1250       changeColour(new NucleotideColourScheme());
1251     }
1252     else if (source == purinePyrimidineColour)
1253     {
1254       changeColour(new PurinePyrimidineColourScheme());
1255     }
1256     // else if (source == RNAInteractionColour)
1257     // {
1258     // changeColour(new RNAInteractionColourScheme());
1259     // }
1260     else if (source == RNAHelixColour)
1261     {
1262       new RNAHelicesColourChooser(viewport, alignPanel);
1263     }
1264     else if (source == modifyPID)
1265     {
1266       modifyPID_actionPerformed();
1267     }
1268     else if (source == modifyConservation)
1269     {
1270       modifyConservation_actionPerformed();
1271     }
1272     else if (source == userDefinedColour)
1273     {
1274       new UserDefinedColours(alignPanel, null);
1275     }
1276     else if (source == PIDColour)
1277     {
1278       changeColour(new PIDColourScheme());
1279     }
1280     else if (source == BLOSUM62Colour)
1281     {
1282       changeColour(new Blosum62ColourScheme());
1283     }
1284     else if (source == tcoffeeColour)
1285     {
1286       changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
1287     }
1288     else if (source == annotationColour)
1289     {
1290       new AnnotationColourChooser(viewport, alignPanel);
1291     }
1292     else if (source == annotationColumnSelection)
1293     {
1294       new AnnotationColumnChooser(viewport, alignPanel);
1295     }
1296     else if (source == sortPairwiseMenuItem)
1297     {
1298       sortPairwiseMenuItem_actionPerformed();
1299     }
1300     else if (source == sortIDMenuItem)
1301     {
1302       sortIDMenuItem_actionPerformed();
1303     }
1304     else if (source == sortLengthMenuItem)
1305     {
1306       sortLengthMenuItem_actionPerformed();
1307     }
1308     else if (source == sortGroupMenuItem)
1309     {
1310       sortGroupMenuItem_actionPerformed();
1311     }
1312     else if (source == removeRedundancyMenuItem)
1313     {
1314       removeRedundancyMenuItem_actionPerformed();
1315     }
1316     else if (source == pairwiseAlignmentMenuItem)
1317     {
1318       pairwiseAlignmentMenuItem_actionPerformed();
1319     }
1320     else if (source == PCAMenuItem)
1321     {
1322       PCAMenuItem_actionPerformed();
1323     }
1324     else if (source == averageDistanceTreeMenuItem)
1325     {
1326       averageDistanceTreeMenuItem_actionPerformed();
1327     }
1328     else if (source == neighbourTreeMenuItem)
1329     {
1330       neighbourTreeMenuItem_actionPerformed();
1331     }
1332     else if (source == njTreeBlosumMenuItem)
1333     {
1334       njTreeBlosumMenuItem_actionPerformed();
1335     }
1336     else if (source == avDistanceTreeBlosumMenuItem)
1337     {
1338       avTreeBlosumMenuItem_actionPerformed();
1339     }
1340     else if (source == documentation)
1341     {
1342       documentation_actionPerformed();
1343     }
1344     else if (source == about)
1345     {
1346       about_actionPerformed();
1347     }
1348
1349   }
1350
1351   public void inputText_actionPerformed()
1352   {
1353     CutAndPasteTransfer cap = new CutAndPasteTransfer(true, this);
1354     Frame frame = new Frame();
1355     frame.add(cap);
1356     jalview.bin.JalviewLite.addFrame(frame,
1357             MessageManager.getString("label.input_cut_paste"), 500, 500);
1358   }
1359
1360   protected void outputText_actionPerformed(ActionEvent e)
1361   {
1362     CutAndPasteTransfer cap = new CutAndPasteTransfer(true, this);
1363     Frame frame = new Frame();
1364     frame.add(cap);
1365     JalviewLite.addFrame(frame, MessageManager.formatMessage(
1366             "label.alignment_output_command",
1367             new Object[] { e.getActionCommand() }), 600, 500);
1368
1369     FileFormat fileFormat = FileFormat.valueOf(e.getActionCommand());
1370     cap.setText(new AppletFormatAdapter(alignPanel).formatSequences(
1371             fileFormat, viewport.getAlignment(),
1372             viewport.getShowJVSuffix()));
1373   }
1374
1375   public void loadAnnotations()
1376   {
1377     CutAndPasteTransfer cap = new CutAndPasteTransfer(true, this);
1378     cap.setText(MessageManager
1379             .getString("label.paste_features_annotations_Tcoffee_here"));
1380     cap.setAnnotationImport();
1381     Frame frame = new Frame();
1382     frame.add(cap);
1383     jalview.bin.JalviewLite.addFrame(frame,
1384             MessageManager.getString("action.paste_annotations"), 400, 300);
1385
1386   }
1387
1388   public String outputAnnotations(boolean displayTextbox)
1389   {
1390     String annotation = new AnnotationFile()
1391             .printAnnotationsForView(viewport);
1392
1393     if (displayTextbox)
1394     {
1395       CutAndPasteTransfer cap = new CutAndPasteTransfer(false, this);
1396       Frame frame = new Frame();
1397       frame.add(cap);
1398       jalview.bin.JalviewLite.addFrame(frame,
1399               MessageManager.getString("label.annotations"), 600, 500);
1400       cap.setText(annotation);
1401     }
1402
1403     return annotation;
1404   }
1405
1406   private Map<String, FeatureColourI> getDisplayedFeatureCols()
1407   {
1408     if (alignPanel.getFeatureRenderer() != null
1409             && viewport.getFeaturesDisplayed() != null)
1410     {
1411       return alignPanel.getFeatureRenderer().getDisplayedFeatureCols();
1412
1413     }
1414     return null;
1415   }
1416
1417   public String outputFeatures(boolean displayTextbox, String format)
1418   {
1419     String features;
1420     FeaturesFile formatter = new FeaturesFile();
1421     if (format.equalsIgnoreCase("Jalview"))
1422     {
1423       features = formatter.printJalviewFormat(viewport
1424               .getAlignment().getSequencesArray(),
1425               getDisplayedFeatureCols());
1426     }
1427     else
1428     {
1429       features = formatter.printGffFormat(viewport.getAlignment()
1430               .getSequencesArray(), getDisplayedFeatureCols());
1431     }
1432
1433     if (displayTextbox)
1434     {
1435       boolean frimport = false;
1436       if (features == null || features.equals("No Features Visible"))
1437       {
1438         features = "# No features visible - paste some and import them here.";
1439         frimport = true;
1440       }
1441
1442       CutAndPasteTransfer cap = new CutAndPasteTransfer(frimport, this);
1443       if (frimport)
1444       {
1445         cap.setAnnotationImport();
1446       }
1447       Frame frame = new Frame();
1448       frame.add(cap);
1449       jalview.bin.JalviewLite.addFrame(frame,
1450               MessageManager.getString("label.features"), 600, 500);
1451       cap.setText(features);
1452     }
1453     else
1454     {
1455       if (features == null)
1456       {
1457         features = "";
1458       }
1459     }
1460
1461     return features;
1462   }
1463
1464   void launchFullApplication()
1465   {
1466     StringBuffer url = new StringBuffer(jalviewServletURL);
1467
1468     // allow servlet parameters to be passed in applet parameter
1469     String firstSep = url.lastIndexOf("?") > url.lastIndexOf("/") ? "&"
1470             : "?";
1471     url.append(firstSep);
1472
1473     url.append("open="
1474             + appendProtocol(viewport.applet.getParameter("file")));
1475
1476     if (viewport.applet.getParameter("features") != null)
1477     {
1478       url.append("&features=");
1479       url.append(appendProtocol(viewport.applet.getParameter("features")));
1480     }
1481
1482     if (viewport.applet.getParameter("annotations") != null)
1483     {
1484       url.append("&annotations=");
1485       url.append(appendProtocol(viewport.applet.getParameter("annotations")));
1486     }
1487
1488     if (viewport.applet.getParameter("jnetfile") != null)
1489     {
1490       url.append("&annotations=");
1491       url.append(appendProtocol(viewport.applet.getParameter("jnetfile")));
1492     }
1493
1494     if (viewport.applet.getParameter("defaultColour") != null)
1495     {
1496       url.append("&colour="
1497               + removeWhiteSpace(viewport.applet
1498                       .getParameter("defaultColour")));
1499     }
1500
1501     if (viewport.applet.getParameter("userDefinedColour") != null)
1502     {
1503       url.append("&colour="
1504               + removeWhiteSpace(viewport.applet
1505                       .getParameter("userDefinedColour")));
1506     }
1507     if (viewport.applet.getParameter("tree") != null)
1508     {
1509       url.append("&tree="
1510               + appendProtocol(viewport.applet.getParameter("tree")));
1511     }
1512     if (viewport.applet.getParameter("treeFile") != null)
1513     {
1514       url.append("&tree="
1515               + appendProtocol(viewport.applet.getParameter("treeFile")));
1516     }
1517
1518     showURL(url.toString(), "FULL_APP");
1519   }
1520
1521   String removeWhiteSpace(String colour)
1522   {
1523     StringBuffer sb = new StringBuffer();
1524     for (int i = 0; i < colour.length(); i++)
1525     {
1526       if (Character.isWhitespace(colour.charAt(i)))
1527       {
1528         sb.append("%20");
1529       }
1530       else
1531       {
1532         sb.append(colour.charAt(i));
1533       }
1534     }
1535
1536     return sb.toString();
1537   }
1538
1539   String appendProtocol(String url)
1540   {
1541     try
1542     {
1543       new URL(url);
1544       url = URLEncoder.encode(url);
1545     }
1546     /*
1547      * When we finally deprecate 1.1 compatibility, we can start to use
1548      * URLEncoder.encode(url,"UTF-8") and then we'll need this catch: catch
1549      * (UnsupportedEncodingException ex) { System.err.println("WARNING -
1550      * IMPLEMENTATION ERROR - UNSUPPORTED ENCODING EXCEPTION FOR "+url);
1551      * ex.printStackTrace(); }
1552      */
1553     catch (java.net.MalformedURLException ex)
1554     {
1555       url = viewport.applet.getCodeBase() + url;
1556     }
1557     return url;
1558   }
1559
1560   public void closeMenuItem_actionPerformed()
1561   {
1562     PaintRefresher.RemoveComponent(alignPanel);
1563     if (alignPanel.seqPanel != null
1564             && alignPanel.seqPanel.seqCanvas != null)
1565     {
1566       PaintRefresher.RemoveComponent(alignPanel.seqPanel.seqCanvas);
1567     }
1568     if (alignPanel.idPanel != null && alignPanel.idPanel.idCanvas != null)
1569     {
1570       PaintRefresher.RemoveComponent(alignPanel.idPanel.idCanvas);
1571     }
1572
1573     if (PaintRefresher.components.size() == 0 && viewport.applet == null)
1574     {
1575       System.exit(0);
1576     }
1577     else
1578     {
1579     }
1580     viewport = null;
1581     alignPanel = null;
1582     this.dispose();
1583   }
1584
1585   /**
1586    * TODO: JAL-1104
1587    */
1588   void updateEditMenuBar()
1589   {
1590
1591     if (viewport.getHistoryList().size() > 0)
1592     {
1593       undoMenuItem.setEnabled(true);
1594       CommandI command = viewport.getHistoryList().peek();
1595       undoMenuItem.setLabel(MessageManager.formatMessage(
1596               "label.undo_command",
1597               new Object[] { command.getDescription() }));
1598     }
1599     else
1600     {
1601       undoMenuItem.setEnabled(false);
1602       undoMenuItem.setLabel(MessageManager.getString("action.undo"));
1603     }
1604
1605     if (viewport.getRedoList().size() > 0)
1606     {
1607       redoMenuItem.setEnabled(true);
1608
1609       CommandI command = viewport.getRedoList().peek();
1610       redoMenuItem.setLabel(MessageManager.formatMessage(
1611               "label.redo_command",
1612               new Object[] { command.getDescription() }));
1613     }
1614     else
1615     {
1616       redoMenuItem.setEnabled(false);
1617       redoMenuItem.setLabel(MessageManager.getString("action.redo"));
1618     }
1619   }
1620
1621   /**
1622    * TODO: JAL-1104
1623    */
1624   @Override
1625   public void addHistoryItem(CommandI command)
1626   {
1627     if (command.getSize() > 0)
1628     {
1629       viewport.addToHistoryList(command);
1630       viewport.clearRedoList();
1631       updateEditMenuBar();
1632       viewport.updateHiddenColumns();
1633     }
1634   }
1635
1636   /**
1637    * TODO: JAL-1104 DOCUMENT ME!
1638    * 
1639    * @param e
1640    *          DOCUMENT ME!
1641    */
1642   protected void undoMenuItem_actionPerformed()
1643   {
1644     if (viewport.getHistoryList().isEmpty())
1645     {
1646       return;
1647     }
1648
1649     CommandI command = viewport.getHistoryList().pop();
1650     viewport.addToRedoList(command);
1651     command.undoCommand(null);
1652
1653     AlignmentViewport originalSource = getOriginatingSource(command);
1654     // JBPNote Test
1655     if (originalSource != viewport)
1656     {
1657       System.err
1658               .println("Warning: Viewport object mismatch whilst undoing");
1659     }
1660     originalSource.updateHiddenColumns(); // originalSource.hasHiddenColumns =
1661                                           // viewport.getColumnSelection().getHiddenColumns()
1662                                           // != null;
1663     updateEditMenuBar();
1664     originalSource.firePropertyChange("alignment", null, originalSource
1665             .getAlignment().getSequences());
1666   }
1667
1668   /**
1669    * TODO: JAL-1104 DOCUMENT ME!
1670    * 
1671    * @param e
1672    *          DOCUMENT ME!
1673    */
1674   protected void redoMenuItem_actionPerformed()
1675   {
1676     if (viewport.getRedoList().isEmpty())
1677     {
1678       return;
1679     }
1680
1681     CommandI command = viewport.getRedoList().pop();
1682     viewport.addToHistoryList(command);
1683     command.doCommand(null);
1684
1685     AlignmentViewport originalSource = getOriginatingSource(command);
1686     // JBPNote Test
1687     if (originalSource != viewport)
1688     {
1689       System.err
1690               .println("Warning: Viewport object mismatch whilst re-doing");
1691     }
1692     originalSource.updateHiddenColumns(); // sethasHiddenColumns(); =
1693                                           // viewport.getColumnSelection().getHiddenColumns()
1694                                           // != null;
1695
1696     updateEditMenuBar();
1697     originalSource.firePropertyChange("alignment", null, originalSource
1698             .getAlignment().getSequences());
1699   }
1700
1701   AlignmentViewport getOriginatingSource(CommandI command)
1702   {
1703     AlignmentViewport originalSource = null;
1704     // For sequence removal and addition, we need to fire
1705     // the property change event FROM the viewport where the
1706     // original alignment was altered
1707     AlignmentI al = null;
1708     if (command instanceof EditCommand)
1709     {
1710       EditCommand editCommand = (EditCommand) command;
1711       al = editCommand.getAlignment();
1712       Vector comps = (Vector) PaintRefresher.components.get(viewport
1713               .getSequenceSetId());
1714       for (int i = 0; i < comps.size(); i++)
1715       {
1716         if (comps.elementAt(i) instanceof AlignmentPanel)
1717         {
1718           if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1719           {
1720             originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1721             break;
1722           }
1723         }
1724       }
1725     }
1726
1727     if (originalSource == null)
1728     {
1729       // The original view is closed, we must validate
1730       // the current view against the closed view first
1731       if (al != null)
1732       {
1733         PaintRefresher.validateSequences(al, viewport.getAlignment());
1734       }
1735
1736       originalSource = viewport;
1737     }
1738
1739     return originalSource;
1740   }
1741
1742   /**
1743    * Move the currently selected sequences up or down one position in the
1744    * alignment
1745    * 
1746    * @param up
1747    */
1748   public void moveSelectedSequences(boolean up)
1749   {
1750     SequenceGroup sg = viewport.getSelectionGroup();
1751     if (sg == null)
1752     {
1753       return;
1754     }
1755     viewport.getAlignment().moveSelectedSequencesByOne(sg,
1756             up ? null : viewport.getHiddenRepSequences(), up);
1757     alignPanel.paintAlignment(true);
1758
1759     /*
1760      * Also move cDNA/protein complement sequences
1761      */
1762     AlignViewportI complement = viewport.getCodingComplement();
1763     if (complement != null)
1764     {
1765       SequenceGroup mappedSelection = MappingUtils.mapSequenceGroup(sg,
1766               viewport, complement);
1767       complement.getAlignment().moveSelectedSequencesByOne(mappedSelection,
1768               up ? null : complement.getHiddenRepSequences(), up);
1769       getSplitFrame().getComplement(this).alignPanel.paintAlignment(true);
1770     }
1771   }
1772
1773   synchronized void slideSequences(boolean right, int size)
1774   {
1775     List<SequenceI> sg = new Vector<SequenceI>();
1776     if (viewport.cursorMode)
1777     {
1778       sg.add(viewport.getAlignment().getSequenceAt(
1779               alignPanel.seqPanel.seqCanvas.cursorY));
1780     }
1781     else if (viewport.getSelectionGroup() != null
1782             && viewport.getSelectionGroup().getSize() != viewport
1783                     .getAlignment().getHeight())
1784     {
1785       sg = viewport.getSelectionGroup().getSequences(
1786               viewport.getHiddenRepSequences());
1787     }
1788
1789     if (sg.size() < 1)
1790     {
1791       return;
1792     }
1793
1794     Vector<SequenceI> invertGroup = new Vector();
1795
1796     for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1797     {
1798       if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1799       {
1800         invertGroup.addElement(viewport.getAlignment().getSequenceAt(i));
1801       }
1802     }
1803
1804     SequenceI[] seqs1 = sg.toArray(new SequenceI[sg.size()]);
1805
1806     SequenceI[] seqs2 = invertGroup.toArray(new SequenceI[invertGroup
1807             .size()]);
1808     for (int i = 0; i < invertGroup.size(); i++)
1809     {
1810       seqs2[i] = invertGroup.elementAt(i);
1811     }
1812
1813     SlideSequencesCommand ssc;
1814     if (right)
1815     {
1816       ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1817               size, viewport.getGapCharacter());
1818     }
1819     else
1820     {
1821       ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1822               size, viewport.getGapCharacter());
1823     }
1824
1825     int groupAdjustment = 0;
1826     if (ssc.getGapsInsertedBegin() && right)
1827     {
1828       if (viewport.cursorMode)
1829       {
1830         alignPanel.seqPanel.moveCursor(size, 0);
1831       }
1832       else
1833       {
1834         groupAdjustment = size;
1835       }
1836     }
1837     else if (!ssc.getGapsInsertedBegin() && !right)
1838     {
1839       if (viewport.cursorMode)
1840       {
1841         alignPanel.seqPanel.moveCursor(-size, 0);
1842       }
1843       else
1844       {
1845         groupAdjustment = -size;
1846       }
1847     }
1848
1849     if (groupAdjustment != 0)
1850     {
1851       viewport.getSelectionGroup().setStartRes(
1852               viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1853       viewport.getSelectionGroup().setEndRes(
1854               viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1855     }
1856
1857     boolean appendHistoryItem = false;
1858     Deque<CommandI> historyList = viewport.getHistoryList();
1859     if (historyList != null && historyList.size() > 0
1860             && historyList.peek() instanceof SlideSequencesCommand)
1861     {
1862       appendHistoryItem = ssc
1863               .appendSlideCommand((SlideSequencesCommand) historyList
1864                       .peek());
1865     }
1866
1867     if (!appendHistoryItem)
1868     {
1869       addHistoryItem(ssc);
1870     }
1871
1872     repaint();
1873   }
1874
1875   static StringBuffer copiedSequences;
1876
1877   static Vector copiedHiddenColumns;
1878
1879   protected void copy_actionPerformed()
1880   {
1881     if (viewport.getSelectionGroup() == null)
1882     {
1883       return;
1884     }
1885
1886     SequenceGroup sg = viewport.getSelectionGroup();
1887     copiedSequences = new StringBuffer();
1888     Map<Integer, SequenceI> orderedSeqs = new HashMap<Integer, SequenceI>();
1889     for (int i = 0; i < sg.getSize(); i++)
1890     {
1891       SequenceI seq = sg.getSequenceAt(i);
1892       int index = viewport.getAlignment().findIndex(seq);
1893       orderedSeqs.put(index, seq);
1894     }
1895
1896     int index = 0, startRes, endRes;
1897     char ch;
1898
1899     if (viewport.hasHiddenColumns() && viewport.getSelectionGroup() != null)
1900     {
1901       copiedHiddenColumns = new Vector();
1902       int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1903       for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1904       {
1905         copiedHiddenColumns.addElement(new int[] {
1906             region[0] - hiddenOffset, region[1] - hiddenOffset });
1907       }
1908     }
1909     else
1910     {
1911       copiedHiddenColumns = null;
1912     }
1913
1914     for (int i = 0; i < sg.getSize(); i++)
1915     {
1916       SequenceI seq = null;
1917
1918       while (seq == null)
1919       {
1920         if (orderedSeqs.containsKey(index))
1921         {
1922           seq = orderedSeqs.get(index);
1923           index++;
1924           break;
1925         }
1926         else
1927         {
1928           index++;
1929         }
1930       }
1931
1932       // FIND START RES
1933       // Returns residue following index if gap
1934       startRes = seq.findPosition(sg.getStartRes());
1935
1936       // FIND END RES
1937       // Need to find the residue preceeding index if gap
1938       endRes = 0;
1939
1940       for (int j = 0; j < sg.getEndRes() + 1 && j < seq.getLength(); j++)
1941       {
1942         ch = seq.getCharAt(j);
1943         if (!jalview.util.Comparison.isGap((ch)))
1944         {
1945           endRes++;
1946         }
1947       }
1948
1949       if (endRes > 0)
1950       {
1951         endRes += seq.getStart() - 1;
1952       }
1953
1954       copiedSequences.append(seq.getName()
1955               + "\t"
1956               + startRes
1957               + "\t"
1958               + endRes
1959               + "\t"
1960               + seq.getSequenceAsString(sg.getStartRes(),
1961                       sg.getEndRes() + 1) + "\n");
1962     }
1963
1964   }
1965
1966   protected void pasteNew_actionPerformed()
1967   {
1968     paste(true);
1969   }
1970
1971   protected void pasteThis_actionPerformed()
1972   {
1973     paste(false);
1974   }
1975
1976   void paste(boolean newAlignment)
1977   {
1978     try
1979     {
1980
1981       if (copiedSequences == null)
1982       {
1983         return;
1984       }
1985
1986       StringTokenizer st = new StringTokenizer(copiedSequences.toString());
1987       Vector seqs = new Vector();
1988       while (st.hasMoreElements())
1989       {
1990         String name = st.nextToken();
1991         int start = Integer.parseInt(st.nextToken());
1992         int end = Integer.parseInt(st.nextToken());
1993         seqs.addElement(new Sequence(name, st.nextToken(), start, end));
1994       }
1995       SequenceI[] newSeqs = new SequenceI[seqs.size()];
1996       for (int i = 0; i < seqs.size(); i++)
1997       {
1998         newSeqs[i] = (SequenceI) seqs.elementAt(i);
1999       }
2000
2001       if (newAlignment)
2002       {
2003         String newtitle = MessageManager
2004                 .getString("label.copied_sequences");
2005         if (getTitle().startsWith(
2006                 MessageManager.getString("label.copied_sequences")))
2007         {
2008           newtitle = getTitle();
2009         }
2010         else
2011         {
2012           newtitle = newtitle.concat(MessageManager.formatMessage(
2013                   "label.from_msname", new String[] { getTitle() }));
2014         }
2015         AlignFrame af = new AlignFrame(new Alignment(newSeqs),
2016                 viewport.applet, newtitle, false);
2017         if (copiedHiddenColumns != null)
2018         {
2019           for (int i = 0; i < copiedHiddenColumns.size(); i++)
2020           {
2021             int[] region = (int[]) copiedHiddenColumns.elementAt(i);
2022             af.viewport.hideColumns(region[0], region[1]);
2023           }
2024         }
2025
2026         jalview.bin.JalviewLite.addFrame(af, newtitle, frameWidth,
2027                 frameHeight);
2028       }
2029       else
2030       {
2031         addSequences(newSeqs);
2032       }
2033
2034     } catch (Exception ex)
2035     {
2036     } // could be anything being pasted in here
2037
2038   }
2039
2040   void addSequences(SequenceI[] seqs)
2041   {
2042     for (int i = 0; i < seqs.length; i++)
2043     {
2044       viewport.getAlignment().addSequence(seqs[i]);
2045     }
2046
2047     // !newAlignment
2048     addHistoryItem(new EditCommand(
2049             MessageManager.getString("label.add_sequences"), Action.PASTE,
2050             seqs, 0, viewport.getAlignment().getWidth(),
2051             viewport.getAlignment()));
2052
2053     viewport.setEndSeq(viewport.getAlignment().getHeight());
2054     viewport.getAlignment().getWidth();
2055     viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2056             .getSequences());
2057
2058   }
2059
2060   protected void cut_actionPerformed()
2061   {
2062     copy_actionPerformed();
2063     delete_actionPerformed();
2064   }
2065
2066   protected void delete_actionPerformed()
2067   {
2068
2069     SequenceGroup sg = viewport.getSelectionGroup();
2070     if (sg == null)
2071     {
2072       return;
2073     }
2074
2075     Vector seqs = new Vector();
2076     SequenceI seq;
2077     for (int i = 0; i < sg.getSize(); i++)
2078     {
2079       seq = sg.getSequenceAt(i);
2080       seqs.addElement(seq);
2081     }
2082
2083     /*
2084      * If the cut affects all sequences, warn, remove highlighted columns
2085      */
2086     if (sg.getSize() == viewport.getAlignment().getHeight())
2087     {
2088       boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2089               .getAlignment().getWidth()) ? true : false;
2090       if (isEntireAlignWidth)
2091       {
2092         String title = MessageManager.getString("label.delete_all");
2093         Panel infoPanel = new Panel();
2094         infoPanel.setLayout(new FlowLayout());
2095         infoPanel
2096                 .add(new Label(MessageManager.getString("warn.delete_all")));
2097
2098         final JVDialog dialog = new JVDialog(this, title, true, 400, 200);
2099         dialog.setMainPanel(infoPanel);
2100         dialog.ok.setLabel(MessageManager.getString("action.ok"));
2101         dialog.cancel.setLabel(MessageManager.getString("action.cancel"));
2102         dialog.setVisible(true);
2103
2104         if (!dialog.accept)
2105         {
2106           return;
2107         }
2108       }
2109       viewport.getColumnSelection().removeElements(sg.getStartRes(),
2110               sg.getEndRes() + 1);
2111     }
2112
2113     SequenceI[] cut = new SequenceI[seqs.size()];
2114     for (int i = 0; i < seqs.size(); i++)
2115     {
2116       cut[i] = (SequenceI) seqs.elementAt(i);
2117     }
2118
2119     /*
2120      * //ADD HISTORY ITEM
2121      */
2122     addHistoryItem(new EditCommand(
2123             MessageManager.getString("label.cut_sequences"), Action.CUT,
2124             cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2125             viewport.getAlignment()));
2126
2127     viewport.setSelectionGroup(null);
2128     viewport.getAlignment().deleteGroup(sg);
2129
2130     viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2131             .getSequences());
2132
2133     if (viewport.getAlignment().getHeight() < 1)
2134     {
2135       this.setVisible(false);
2136     }
2137     viewport.sendSelection();
2138   }
2139
2140   /**
2141    * group consensus toggled
2142    * 
2143    */
2144   protected void showGroupConsensus_actionPerformed()
2145   {
2146     viewport.setShowGroupConsensus(showGroupConsensus.getState());
2147     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
2148
2149   }
2150
2151   /**
2152    * group conservation toggled.
2153    */
2154   protected void showGroupConservation_actionPerformed()
2155   {
2156     viewport.setShowGroupConservation(showGroupConservation.getState());
2157     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
2158   }
2159
2160   /*
2161    * (non-Javadoc)
2162    * 
2163    * @see
2164    * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
2165    * .event.ActionEvent)
2166    */
2167   protected void showConsensusHistogram_actionPerformed()
2168   {
2169     viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
2170     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
2171   }
2172
2173   /*
2174    * (non-Javadoc)
2175    * 
2176    * @see
2177    * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
2178    * .event.ActionEvent)
2179    */
2180   protected void showSequenceLogo_actionPerformed()
2181   {
2182     viewport.setShowSequenceLogo(showSequenceLogo.getState());
2183     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
2184   }
2185
2186   protected void normSequenceLogo_actionPerformed()
2187   {
2188     showSequenceLogo.setState(true);
2189     viewport.setShowSequenceLogo(true);
2190     viewport.setNormaliseSequenceLogo(normSequenceLogo.getState());
2191     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
2192   }
2193
2194   protected void applyAutoAnnotationSettings_actionPerformed()
2195   {
2196     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
2197   }
2198
2199   protected void makeGrpsFromSelection_actionPerformed()
2200   {
2201     if (avc.makeGroupsFromSelection())
2202     {
2203       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2204       alignPanel.updateAnnotation();
2205       alignPanel.paintAlignment(true);
2206     }
2207   }
2208
2209   protected void createGroup_actionPerformed()
2210   {
2211     avc.createGroup();
2212   }
2213
2214   protected void unGroup_actionPerformed()
2215   {
2216     if (avc.unGroup())
2217     {
2218       alignPanel.alignmentChanged();
2219     }
2220   }
2221
2222   protected void deleteGroups_actionPerformed()
2223   {
2224     if (avc.deleteGroups())
2225     {
2226       alignPanel.alignmentChanged();
2227     }
2228   }
2229
2230   public void selectAllSequenceMenuItem_actionPerformed()
2231   {
2232     SequenceGroup sg = new SequenceGroup();
2233     for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2234     {
2235       sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2236     }
2237     sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2238     viewport.setSelectionGroup(sg);
2239     // JAL-2034 - should delegate to
2240     // alignPanel to decide if overview needs
2241     // updating.
2242     alignPanel.paintAlignment(false);
2243     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2244     viewport.sendSelection();
2245   }
2246
2247   public void deselectAllSequenceMenuItem_actionPerformed()
2248   {
2249     if (viewport.cursorMode)
2250     {
2251       alignPanel.seqPanel.keyboardNo1 = null;
2252       alignPanel.seqPanel.keyboardNo2 = null;
2253     }
2254     viewport.setSelectionGroup(null);
2255     viewport.getColumnSelection().clear();
2256     viewport.setSelectionGroup(null);
2257     alignPanel.idPanel.idCanvas.searchResults = null;
2258     alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2259     // JAL-2034 - should delegate to
2260     // alignPanel to decide if overview needs
2261     // updating.
2262     alignPanel.paintAlignment(false);
2263     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2264     viewport.sendSelection();
2265   }
2266
2267   public void invertSequenceMenuItem_actionPerformed()
2268   {
2269     SequenceGroup sg = viewport.getSelectionGroup();
2270     for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2271     {
2272       sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2273     }
2274
2275     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2276     viewport.sendSelection();
2277   }
2278
2279   public void invertColSel_actionPerformed()
2280   {
2281     viewport.invertColumnSelection();
2282     alignPanel.paintAlignment(true);
2283     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2284     viewport.sendSelection();
2285   }
2286
2287   void trimAlignment(boolean trimLeft)
2288   {
2289     ColumnSelection colSel = viewport.getColumnSelection();
2290     int column;
2291
2292     if (!colSel.isEmpty())
2293     {
2294       if (trimLeft)
2295       {
2296         column = colSel.getMin();
2297       }
2298       else
2299       {
2300         column = colSel.getMax();
2301       }
2302
2303       SequenceI[] seqs;
2304       if (viewport.getSelectionGroup() != null)
2305       {
2306         seqs = viewport.getSelectionGroup().getSequencesAsArray(
2307                 viewport.getHiddenRepSequences());
2308       }
2309       else
2310       {
2311         seqs = viewport.getAlignment().getSequencesArray();
2312       }
2313
2314       TrimRegionCommand trimRegion;
2315       if (trimLeft)
2316       {
2317         trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2318                 column, viewport.getAlignment());
2319         viewport.setStartRes(0);
2320       }
2321       else
2322       {
2323         trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2324                 column, viewport.getAlignment());
2325       }
2326
2327       statusBar.setText(MessageManager.formatMessage(
2328               "label.removed_columns",
2329               new String[] { Integer.valueOf(trimRegion.getSize())
2330                       .toString() }));
2331       addHistoryItem(trimRegion);
2332
2333       for (SequenceGroup sg : viewport.getAlignment().getGroups())
2334       {
2335         if ((trimLeft && !sg.adjustForRemoveLeft(column))
2336                 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2337         {
2338           viewport.getAlignment().deleteGroup(sg);
2339         }
2340       }
2341
2342       viewport.firePropertyChange("alignment", null, viewport
2343               .getAlignment().getSequences());
2344     }
2345   }
2346
2347   public void removeGappedColumnMenuItem_actionPerformed()
2348   {
2349     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2350
2351     SequenceI[] seqs;
2352     if (viewport.getSelectionGroup() != null)
2353     {
2354       seqs = viewport.getSelectionGroup().getSequencesAsArray(
2355               viewport.getHiddenRepSequences());
2356       start = viewport.getSelectionGroup().getStartRes();
2357       end = viewport.getSelectionGroup().getEndRes();
2358     }
2359     else
2360     {
2361       seqs = viewport.getAlignment().getSequencesArray();
2362     }
2363
2364     RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2365             "Remove Gapped Columns", seqs, start, end,
2366             viewport.getAlignment());
2367
2368     addHistoryItem(removeGapCols);
2369
2370     statusBar.setText(MessageManager.formatMessage(
2371             "label.removed_empty_columns",
2372             new String[] { Integer.valueOf(removeGapCols.getSize())
2373                     .toString() }));
2374
2375     // This is to maintain viewport position on first residue
2376     // of first sequence
2377     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2378     int startRes = seq.findPosition(viewport.startRes);
2379     // ShiftList shifts;
2380     // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2381     // edit.alColumnChanges=shifts.getInverse();
2382     // if (viewport.hasHiddenColumns)
2383     // viewport.getColumnSelection().compensateForEdits(shifts);
2384     viewport.setStartRes(seq.findIndex(startRes) - 1);
2385     viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2386             .getSequences());
2387
2388   }
2389
2390   public void removeAllGapsMenuItem_actionPerformed()
2391   {
2392     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2393
2394     SequenceI[] seqs;
2395     if (viewport.getSelectionGroup() != null)
2396     {
2397       seqs = viewport.getSelectionGroup().getSequencesAsArray(
2398               viewport.getHiddenRepSequences());
2399       start = viewport.getSelectionGroup().getStartRes();
2400       end = viewport.getSelectionGroup().getEndRes();
2401     }
2402     else
2403     {
2404       seqs = viewport.getAlignment().getSequencesArray();
2405     }
2406
2407     // This is to maintain viewport position on first residue
2408     // of first sequence
2409     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2410     int startRes = seq.findPosition(viewport.startRes);
2411
2412     addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2413             viewport.getAlignment()));
2414
2415     viewport.setStartRes(seq.findIndex(startRes) - 1);
2416
2417     viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2418             .getSequences());
2419
2420   }
2421
2422   public void findMenuItem_actionPerformed()
2423   {
2424     new Finder(alignPanel);
2425   }
2426
2427   /**
2428    * create a new view derived from the current view
2429    * 
2430    * @param viewtitle
2431    * @return frame for the new view
2432    */
2433   public AlignFrame newView(String viewtitle)
2434   {
2435     AlignmentI newal;
2436     if (viewport.hasHiddenRows())
2437     {
2438       newal = new Alignment(viewport.getAlignment().getHiddenSequences()
2439               .getFullAlignment().getSequencesArray());
2440     }
2441     else
2442     {
2443       newal = new Alignment(viewport.getAlignment().getSequencesArray());
2444     }
2445
2446     if (viewport.getAlignment().getAlignmentAnnotation() != null)
2447     {
2448       for (int i = 0; i < viewport.getAlignment().getAlignmentAnnotation().length; i++)
2449       {
2450         if (!viewport.getAlignment().getAlignmentAnnotation()[i].autoCalculated)
2451         {
2452           newal.addAnnotation(viewport.getAlignment()
2453                   .getAlignmentAnnotation()[i]);
2454         }
2455       }
2456     }
2457
2458     AlignFrame newaf = new AlignFrame(newal, viewport.applet, "", false);
2459
2460     newaf.viewport.setSequenceSetId(alignPanel.av.getSequenceSetId());
2461     PaintRefresher.Register(alignPanel, alignPanel.av.getSequenceSetId());
2462     PaintRefresher.Register(newaf.alignPanel,
2463             newaf.alignPanel.av.getSequenceSetId());
2464
2465     PaintRefresher.Register(newaf.alignPanel.idPanel.idCanvas,
2466             newaf.alignPanel.av.getSequenceSetId());
2467     PaintRefresher.Register(newaf.alignPanel.seqPanel.seqCanvas,
2468             newaf.alignPanel.av.getSequenceSetId());
2469
2470     Vector comps = (Vector) PaintRefresher.components.get(viewport
2471             .getSequenceSetId());
2472     int viewSize = -1;
2473     for (int i = 0; i < comps.size(); i++)
2474     {
2475       if (comps.elementAt(i) instanceof AlignmentPanel)
2476       {
2477         viewSize++;
2478       }
2479     }
2480
2481     String title = new String(this.getTitle());
2482     if (viewtitle != null)
2483     {
2484       title = viewtitle + " ( " + title + ")";
2485     }
2486     else
2487     {
2488       if (title.indexOf("(View") > -1)
2489       {
2490         title = title.substring(0, title.indexOf("(View"));
2491       }
2492       title += "(View " + viewSize + ")";
2493     }
2494
2495     newaf.setTitle(title.toString());
2496
2497     newaf.viewport.setHistoryList(viewport.getHistoryList());
2498     newaf.viewport.setRedoList(viewport.getRedoList());
2499     return newaf;
2500   }
2501
2502   /**
2503    * 
2504    * @return list of feature groups on the view
2505    */
2506   public String[] getFeatureGroups()
2507   {
2508     FeatureRenderer fr = null;
2509     if (alignPanel != null
2510             && (fr = alignPanel.getFeatureRenderer()) != null)
2511     {
2512       List<String> gps = fr.getFeatureGroups();
2513       String[] _gps = gps.toArray(new String[gps.size()]);
2514       return _gps;
2515     }
2516     return null;
2517   }
2518
2519   /**
2520    * get sequence feature groups that are hidden or shown
2521    * 
2522    * @param visible
2523    *          true is visible
2524    * @return list
2525    */
2526   public String[] getFeatureGroupsOfState(boolean visible)
2527   {
2528     FeatureRenderer fr = null;
2529     if (alignPanel != null
2530             && (fr = alignPanel.getFeatureRenderer()) != null)
2531     {
2532       List<String> gps = fr.getGroups(visible);
2533       String[] _gps = gps.toArray(new String[gps.size()]);
2534       return _gps;
2535     }
2536     return null;
2537   }
2538
2539   /**
2540    * Change the display state for the given feature groups
2541    * 
2542    * @param groups
2543    *          list of group strings
2544    * @param state
2545    *          visible or invisible
2546    */
2547   public void setFeatureGroupState(String[] groups, boolean state)
2548   {
2549     FeatureRenderer fr = null;
2550     this.sequenceFeatures.setState(true);
2551     viewport.setShowSequenceFeatures(true);
2552     if (alignPanel != null
2553             && (fr = alignPanel.getFeatureRenderer()) != null)
2554     {
2555
2556       fr.setGroupVisibility(Arrays.asList(groups), state);
2557       alignPanel.seqPanel.seqCanvas.repaint();
2558       if (alignPanel.overviewPanel != null)
2559       {
2560         alignPanel.overviewPanel.updateOverviewImage();
2561       }
2562     }
2563   }
2564
2565   public void seqLimits_itemStateChanged()
2566   {
2567     viewport.setShowJVSuffix(seqLimits.getState());
2568     alignPanel.fontChanged();
2569     alignPanel.paintAlignment(true);
2570   }
2571
2572   protected void colourTextMenuItem_actionPerformed()
2573   {
2574     viewport.setColourText(colourTextMenuItem.getState());
2575     alignPanel.paintAlignment(true);
2576   }
2577
2578   protected void displayNonconservedMenuItem_actionPerformed()
2579   {
2580     viewport.setShowUnconserved(displayNonconservedMenuItem.getState());
2581     alignPanel.paintAlignment(true);
2582   }
2583
2584   protected void wrapMenuItem_actionPerformed()
2585   {
2586     viewport.setWrapAlignment(wrapMenuItem.getState());
2587     alignPanel.setWrapAlignment(wrapMenuItem.getState());
2588     scaleAbove.setEnabled(wrapMenuItem.getState());
2589     scaleLeft.setEnabled(wrapMenuItem.getState());
2590     scaleRight.setEnabled(wrapMenuItem.getState());
2591     alignPanel.paintAlignment(true);
2592   }
2593
2594   public void overviewMenuItem_actionPerformed()
2595   {
2596     if (alignPanel.overviewPanel != null)
2597     {
2598       return;
2599     }
2600
2601     Frame frame = new Frame();
2602     OverviewPanel overview = new OverviewPanel(alignPanel);
2603     frame.add(overview);
2604     // +50 must allow for applet frame window
2605     jalview.bin.JalviewLite.addFrame(frame, MessageManager.formatMessage(
2606             "label.overview_params", new String[] { this.getTitle() }),
2607             overview.getPreferredSize().width,
2608             overview.getPreferredSize().height + 50);
2609
2610     frame.pack();
2611     final AlignmentPanel ap = alignPanel;
2612     frame.addWindowListener(new WindowAdapter()
2613     {
2614       @Override
2615       public void windowClosing(WindowEvent e)
2616       {
2617         if (ap != null)
2618         {
2619           ap.setOverviewPanel(null);
2620         }
2621       };
2622     });
2623
2624     alignPanel.setOverviewPanel(overview);
2625
2626   }
2627
2628   @Override
2629   public void changeColour(ColourSchemeI cs)
2630   {
2631
2632     if (cs != null)
2633     {
2634       if (viewport.getAbovePIDThreshold())
2635       {
2636         viewport.setThreshold(SliderPanel.setPIDSliderSource(alignPanel,
2637                 cs, "Background"));
2638       }
2639
2640       if (viewport.getConservationSelected())
2641       {
2642         cs.setConservationApplied(true);
2643         viewport.setIncrement(SliderPanel.setConservationSlider(alignPanel,
2644                 cs, "Background"));
2645       }
2646       else
2647       {
2648         cs.setConservationApplied(false);
2649       }
2650     }
2651     viewport.setGlobalColourScheme(cs);
2652
2653     alignPanel.paintAlignment(true);
2654   }
2655
2656   protected void modifyPID_actionPerformed()
2657   {
2658     if (viewport.getAbovePIDThreshold()
2659             && viewport.getGlobalColourScheme() != null)
2660     {
2661       SliderPanel.setPIDSliderSource(alignPanel,
2662               viewport.getGlobalColourScheme(), "Background");
2663       SliderPanel.showPIDSlider();
2664     }
2665   }
2666
2667   protected void modifyConservation_actionPerformed()
2668   {
2669     if (viewport.getConservationSelected()
2670             && viewport.getGlobalColourScheme() != null)
2671     {
2672       SliderPanel.setConservationSlider(alignPanel,
2673               viewport.getGlobalColourScheme(), "Background");
2674       SliderPanel.showConservationSlider();
2675     }
2676   }
2677
2678   protected void conservationMenuItem_actionPerformed()
2679   {
2680     viewport.setConservationSelected(conservationMenuItem.getState());
2681
2682     viewport.setAbovePIDThreshold(false);
2683     abovePIDThreshold.setState(false);
2684
2685     changeColour(viewport.getGlobalColourScheme());
2686
2687     modifyConservation_actionPerformed();
2688   }
2689
2690   public void abovePIDThreshold_actionPerformed()
2691   {
2692     viewport.setAbovePIDThreshold(abovePIDThreshold.getState());
2693
2694     conservationMenuItem.setState(false);
2695     viewport.setConservationSelected(false);
2696
2697     changeColour(viewport.getGlobalColourScheme());
2698
2699     modifyPID_actionPerformed();
2700   }
2701
2702   public void sortPairwiseMenuItem_actionPerformed()
2703   {
2704     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
2705     AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
2706             .getAlignment().getSequenceAt(0), null);
2707
2708     addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
2709             viewport.getAlignment()));
2710     alignPanel.paintAlignment(true);
2711   }
2712
2713   public void sortIDMenuItem_actionPerformed()
2714   {
2715     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
2716     AlignmentSorter.sortByID(viewport.getAlignment());
2717     addHistoryItem(new OrderCommand("ID Sort", oldOrder,
2718             viewport.getAlignment()));
2719     alignPanel.paintAlignment(true);
2720   }
2721
2722   public void sortLengthMenuItem_actionPerformed()
2723   {
2724     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
2725     AlignmentSorter.sortByLength(viewport.getAlignment());
2726     addHistoryItem(new OrderCommand("Length Sort", oldOrder,
2727             viewport.getAlignment()));
2728     alignPanel.paintAlignment(true);
2729   }
2730
2731   public void sortGroupMenuItem_actionPerformed()
2732   {
2733     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
2734     AlignmentSorter.sortByGroup(viewport.getAlignment());
2735     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
2736             viewport.getAlignment()));
2737     alignPanel.paintAlignment(true);
2738
2739   }
2740
2741   public void removeRedundancyMenuItem_actionPerformed()
2742   {
2743     new RedundancyPanel(alignPanel);
2744   }
2745
2746   public void pairwiseAlignmentMenuItem_actionPerformed()
2747   {
2748     if (viewport.getSelectionGroup() != null
2749             && viewport.getSelectionGroup().getSize() > 1)
2750     {
2751       Frame frame = new Frame();
2752       frame.add(new PairwiseAlignPanel(alignPanel));
2753       jalview.bin.JalviewLite.addFrame(frame,
2754               MessageManager.getString("action.pairwise_alignment"), 600,
2755               500);
2756     }
2757   }
2758
2759   public void PCAMenuItem_actionPerformed()
2760   {
2761     // are the sequences aligned?
2762     if (!viewport.getAlignment().isAligned(false))
2763     {
2764       SequenceI current;
2765       int Width = viewport.getAlignment().getWidth();
2766
2767       for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2768       {
2769         current = viewport.getAlignment().getSequenceAt(i);
2770
2771         if (current.getLength() < Width)
2772         {
2773           current.insertCharAt(Width - 1, viewport.getGapCharacter());
2774         }
2775       }
2776       alignPanel.paintAlignment(true);
2777     }
2778
2779     if ((viewport.getSelectionGroup() != null
2780             && viewport.getSelectionGroup().getSize() < 4 && viewport
2781             .getSelectionGroup().getSize() > 0)
2782             || viewport.getAlignment().getHeight() < 4)
2783     {
2784       return;
2785     }
2786
2787     try
2788     {
2789       new PCAPanel(viewport);
2790     } catch (java.lang.OutOfMemoryError ex)
2791     {
2792     }
2793
2794   }
2795
2796   public void averageDistanceTreeMenuItem_actionPerformed()
2797   {
2798     NewTreePanel("AV", "PID", "Average distance tree using PID");
2799   }
2800
2801   public void neighbourTreeMenuItem_actionPerformed()
2802   {
2803     NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
2804   }
2805
2806   protected void njTreeBlosumMenuItem_actionPerformed()
2807   {
2808     NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
2809   }
2810
2811   protected void avTreeBlosumMenuItem_actionPerformed()
2812   {
2813     NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
2814   }
2815
2816   void NewTreePanel(String type, String pwType, String title)
2817   {
2818     // are the sequences aligned?
2819     if (!viewport.getAlignment().isAligned(false))
2820     {
2821       SequenceI current;
2822       int Width = viewport.getAlignment().getWidth();
2823
2824       for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2825       {
2826         current = viewport.getAlignment().getSequenceAt(i);
2827
2828         if (current.getLength() < Width)
2829         {
2830           current.insertCharAt(Width - 1, viewport.getGapCharacter());
2831         }
2832       }
2833       alignPanel.paintAlignment(true);
2834
2835     }
2836
2837     if ((viewport.getSelectionGroup() != null && viewport
2838             .getSelectionGroup().getSize() > 1)
2839             || (viewport.getAlignment().getHeight() > 1))
2840     {
2841       final TreePanel tp = new TreePanel(alignPanel, type, pwType);
2842
2843       addTreeMenuItem(tp, title);
2844
2845       jalview.bin.JalviewLite.addFrame(tp, title, 600, 500);
2846     }
2847   }
2848
2849   void loadTree_actionPerformed()
2850   {
2851     CutAndPasteTransfer cap = new CutAndPasteTransfer(true, this);
2852     cap.setText(MessageManager.getString("label.paste_newick_tree_file"));
2853     cap.setTreeImport();
2854     Frame frame = new Frame();
2855     frame.add(cap);
2856     jalview.bin.JalviewLite.addFrame(frame,
2857             MessageManager.getString("label.paste_newick_file"), 400, 300);
2858   }
2859
2860   public void loadTree(jalview.io.NewickFile tree, String treeFile)
2861   {
2862     TreePanel tp = new TreePanel(alignPanel, treeFile,
2863             MessageManager.getString("label.load_tree_from_file"), tree);
2864     jalview.bin.JalviewLite.addFrame(tp, treeFile, 600, 500);
2865     addTreeMenuItem(tp, treeFile);
2866   }
2867
2868   /**
2869    * sort the alignment using the given treePanel
2870    * 
2871    * @param treePanel
2872    *          tree used to sort view
2873    * @param title
2874    *          string used for undo event name
2875    */
2876   public void sortByTree(TreePanel treePanel, String title)
2877   {
2878     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
2879     AlignmentSorter
2880             .sortByTree(viewport.getAlignment(), treePanel.getTree());
2881     // addHistoryItem(new HistoryItem("Sort", viewport.alignment,
2882     // HistoryItem.SORT));
2883     addHistoryItem(new OrderCommand(MessageManager.formatMessage(
2884             "label.order_by_params", new String[] { title }), oldOrder,
2885             viewport.getAlignment()));
2886     alignPanel.paintAlignment(true);
2887   }
2888
2889   /**
2890    * Do any automatic reordering of the alignment and add the necessary bits to
2891    * the menu structure for the new tree
2892    * 
2893    * @param treePanel
2894    * @param title
2895    */
2896   protected void addTreeMenuItem(final TreePanel treePanel,
2897           final String title)
2898   {
2899     final MenuItem item = new MenuItem(title);
2900     sortByTreeMenu.add(item);
2901     item.addActionListener(new java.awt.event.ActionListener()
2902     {
2903       @Override
2904       public void actionPerformed(ActionEvent evt)
2905       {
2906         sortByTree(treePanel, title); // treePanel.getTitle());
2907       }
2908     });
2909
2910     treePanel.addWindowListener(new WindowAdapter()
2911     {
2912       @Override
2913       public void windowOpened(WindowEvent e)
2914       {
2915         if (viewport.sortByTree)
2916         {
2917           sortByTree(treePanel, title);
2918         }
2919         super.windowOpened(e);
2920       }
2921
2922       @Override
2923       public void windowClosing(WindowEvent e)
2924       {
2925         sortByTreeMenu.remove(item);
2926       };
2927     });
2928   }
2929
2930   public boolean sortBy(AlignmentOrder alorder, String undoname)
2931   {
2932     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
2933     if (viewport.applet.debug)
2934     {
2935       System.err.println("Sorting " + alorder.getOrder().size()
2936               + " in alignment '" + getTitle() + "'");
2937     }
2938     AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
2939     if (undoname != null)
2940     {
2941       addHistoryItem(new OrderCommand(undoname, oldOrder,
2942               viewport.getAlignment()));
2943     }
2944     alignPanel.paintAlignment(true);
2945     return true;
2946   }
2947
2948   protected void documentation_actionPerformed()
2949   {
2950     alignPanel.av.applet.openJalviewHelpUrl();
2951   }
2952
2953   protected void about_actionPerformed()
2954   {
2955
2956     class AboutPanel extends Canvas
2957     {
2958       String version;
2959
2960       String builddate;
2961
2962       public AboutPanel(String version, String builddate)
2963       {
2964         this.version = version;
2965         this.builddate = builddate;
2966       }
2967
2968       @Override
2969       public void paint(Graphics g)
2970       {
2971         g.setColor(Color.white);
2972         g.fillRect(0, 0, getSize().width, getSize().height);
2973         g.setFont(new Font("Helvetica", Font.PLAIN, 12));
2974         FontMetrics fm = g.getFontMetrics();
2975         int fh = fm.getHeight();
2976         int y = 5, x = 7;
2977         g.setColor(Color.black);
2978         // TODO: update this text for each release or centrally store it for
2979         // lite and application
2980         g.setFont(new Font("Helvetica", Font.BOLD, 14));
2981         g.drawString(MessageManager.formatMessage(
2982                 "label.jalviewLite_release", new String[] { version }), x,
2983                 y += fh);
2984         g.setFont(new Font("Helvetica", Font.BOLD, 12));
2985         g.drawString(MessageManager.formatMessage(
2986                 "label.jaview_build_date", new String[] { builddate }), x,
2987                 y += fh);
2988         g.setFont(new Font("Helvetica", Font.PLAIN, 12));
2989         g.drawString(MessageManager.getString("label.jalview_authors_1"),
2990                 x, y += fh * 1.5);
2991         g.drawString(MessageManager.getString("label.jalview_authors_2"),
2992                 x + 50, y += fh + 8);
2993         g.drawString(
2994                 MessageManager.getString("label.jalview_dev_managers"), x,
2995                 y += fh);
2996         g.drawString(MessageManager
2997                 .getString("label.jalview_distribution_lists"), x, y += fh);
2998         g.drawString(MessageManager.getString("label.jalview_please_cite"),
2999                 x, y += fh + 8);
3000         g.drawString(
3001                 MessageManager.getString("label.jalview_cite_1_authors"),
3002                 x, y += fh);
3003         g.drawString(
3004                 MessageManager.getString("label.jalview_cite_1_title"), x,
3005                 y += fh);
3006         g.drawString(MessageManager.getString("label.jalview_cite_1_ref"),
3007                 x, y += fh);
3008       }
3009     }
3010
3011     Frame frame = new Frame();
3012     frame.add(new AboutPanel(JalviewLite.getVersion(), JalviewLite
3013             .getBuildDate()));
3014     jalview.bin.JalviewLite.addFrame(frame,
3015             MessageManager.getString("label.jalview"), 580, 220);
3016
3017   }
3018
3019   public void showURL(String url, String target)
3020   {
3021     if (viewport.applet == null)
3022     {
3023       System.out.println("Not running as applet - no browser available.");
3024     }
3025     else
3026     {
3027       viewport.applet.showURL(url, target);
3028     }
3029   }
3030
3031   // ////////////////////////////////////////////////////////////////////////////////
3032   // JBuilder Graphics here
3033
3034   MenuBar alignFrameMenuBar = new MenuBar();
3035
3036   Menu fileMenu = new Menu(MessageManager.getString("action.file"));
3037
3038   MenuItem loadApplication = new MenuItem(
3039           MessageManager.getString("label.view_full_application"));
3040
3041   MenuItem loadTree = new MenuItem(
3042           MessageManager.getString("label.load_associated_tree"));
3043
3044   MenuItem loadAnnotations = new MenuItem(
3045           MessageManager.getString("label.load_features_annotations"));
3046
3047   MenuItem outputFeatures = new MenuItem(
3048           MessageManager.getString("label.export_features"));
3049
3050   MenuItem outputAnnotations = new MenuItem(
3051           MessageManager.getString("label.export_annotations"));
3052
3053   MenuItem closeMenuItem = new MenuItem(
3054           MessageManager.getString("action.close"));
3055
3056   MenuItem selectAllSequenceMenuItem = new MenuItem(
3057           MessageManager.getString("action.select_all"));
3058
3059   MenuItem deselectAllSequenceMenuItem = new MenuItem(
3060           MessageManager.getString("action.deselect_all"));
3061
3062   MenuItem invertSequenceMenuItem = new MenuItem(
3063           MessageManager.getString("action.invert_selection"));
3064
3065   MenuItem remove2LeftMenuItem = new MenuItem();
3066
3067   MenuItem remove2RightMenuItem = new MenuItem();
3068
3069   MenuItem removeGappedColumnMenuItem = new MenuItem();
3070
3071   MenuItem removeAllGapsMenuItem = new MenuItem();
3072
3073   CheckboxMenuItem viewBoxesMenuItem = new CheckboxMenuItem();
3074
3075   CheckboxMenuItem viewTextMenuItem = new CheckboxMenuItem();
3076
3077   MenuItem sortPairwiseMenuItem = new MenuItem();
3078
3079   MenuItem sortIDMenuItem = new MenuItem();
3080
3081   MenuItem sortLengthMenuItem = new MenuItem();
3082
3083   MenuItem sortGroupMenuItem = new MenuItem();
3084
3085   MenuItem removeRedundancyMenuItem = new MenuItem();
3086
3087   MenuItem pairwiseAlignmentMenuItem = new MenuItem();
3088
3089   MenuItem PCAMenuItem = new MenuItem();
3090
3091   MenuItem averageDistanceTreeMenuItem = new MenuItem();
3092
3093   MenuItem neighbourTreeMenuItem = new MenuItem();
3094
3095   BorderLayout borderLayout1 = new BorderLayout();
3096
3097   public Label statusBar = new Label();
3098
3099   MenuItem clustalColour = new MenuItem();
3100
3101   MenuItem zappoColour = new MenuItem();
3102
3103   MenuItem taylorColour = new MenuItem();
3104
3105   MenuItem hydrophobicityColour = new MenuItem();
3106
3107   MenuItem helixColour = new MenuItem();
3108
3109   MenuItem strandColour = new MenuItem();
3110
3111   MenuItem turnColour = new MenuItem();
3112
3113   MenuItem buriedColour = new MenuItem();
3114
3115   MenuItem purinePyrimidineColour = new MenuItem();
3116
3117   // MenuItem RNAInteractionColour = new MenuItem();
3118
3119   MenuItem RNAHelixColour = new MenuItem();
3120
3121   MenuItem userDefinedColour = new MenuItem();
3122
3123   MenuItem PIDColour = new MenuItem();
3124
3125   MenuItem BLOSUM62Colour = new MenuItem();
3126
3127   MenuItem tcoffeeColour = new MenuItem();
3128
3129   MenuItem njTreeBlosumMenuItem = new MenuItem();
3130
3131   MenuItem avDistanceTreeBlosumMenuItem = new MenuItem();
3132
3133   CheckboxMenuItem annotationPanelMenuItem = new CheckboxMenuItem();
3134
3135   CheckboxMenuItem colourTextMenuItem = new CheckboxMenuItem();
3136
3137   CheckboxMenuItem displayNonconservedMenuItem = new CheckboxMenuItem();
3138
3139   MenuItem alProperties = new MenuItem(
3140           MessageManager.getString("label.alignment_props"));
3141
3142   MenuItem overviewMenuItem = new MenuItem();
3143
3144   MenuItem undoMenuItem = new MenuItem();
3145
3146   MenuItem redoMenuItem = new MenuItem();
3147
3148   CheckboxMenuItem conservationMenuItem = new CheckboxMenuItem();
3149
3150   MenuItem noColourmenuItem = new MenuItem();
3151
3152   CheckboxMenuItem wrapMenuItem = new CheckboxMenuItem();
3153
3154   CheckboxMenuItem renderGapsMenuItem = new CheckboxMenuItem();
3155
3156   MenuItem findMenuItem = new MenuItem();
3157
3158   CheckboxMenuItem abovePIDThreshold = new CheckboxMenuItem();
3159
3160   MenuItem nucleotideColour = new MenuItem();
3161
3162   MenuItem deleteGroups = new MenuItem();
3163
3164   MenuItem grpsFromSelection = new MenuItem();
3165
3166   MenuItem createGroup = new MenuItem();
3167
3168   MenuItem unGroup = new MenuItem();
3169
3170   MenuItem delete = new MenuItem();
3171
3172   MenuItem copy = new MenuItem();
3173
3174   MenuItem cut = new MenuItem();
3175
3176   Menu pasteMenu = new Menu();
3177
3178   MenuItem pasteNew = new MenuItem();
3179
3180   MenuItem pasteThis = new MenuItem();
3181
3182   CheckboxMenuItem applyToAllGroups = new CheckboxMenuItem();
3183
3184   MenuItem font = new MenuItem();
3185
3186   CheckboxMenuItem scaleAbove = new CheckboxMenuItem();
3187
3188   CheckboxMenuItem scaleLeft = new CheckboxMenuItem();
3189
3190   CheckboxMenuItem scaleRight = new CheckboxMenuItem();
3191
3192   MenuItem modifyPID = new MenuItem();
3193
3194   MenuItem modifyConservation = new MenuItem();
3195
3196   CheckboxMenuItem autoCalculate = null;
3197
3198   CheckboxMenuItem sortByTree = new CheckboxMenuItem(
3199           "Sort Alignment With New Tree", true);
3200
3201   Menu sortByTreeMenu = new Menu();
3202
3203   MenuItem inputText = new MenuItem();
3204
3205   MenuItem documentation = new MenuItem();
3206
3207   MenuItem about = new MenuItem();
3208
3209   CheckboxMenuItem seqLimits = new CheckboxMenuItem();
3210
3211   CheckboxMenuItem centreColumnLabelFlag = new CheckboxMenuItem();
3212
3213   CheckboxMenuItem followMouseOverFlag = new CheckboxMenuItem();
3214
3215   CheckboxMenuItem showSequenceLogo = new CheckboxMenuItem();
3216
3217   CheckboxMenuItem applyAutoAnnotationSettings = new CheckboxMenuItem();
3218
3219   CheckboxMenuItem showConsensusHistogram = new CheckboxMenuItem();
3220
3221   CheckboxMenuItem showGroupConsensus = new CheckboxMenuItem();
3222
3223   CheckboxMenuItem showGroupConservation = new CheckboxMenuItem();
3224
3225   CheckboxMenuItem normSequenceLogo = new CheckboxMenuItem();
3226
3227   /**
3228    * Initialise menus and other items
3229    * 
3230    * @throws Exception
3231    */
3232   private void jbInit() throws Exception
3233   {
3234     setMenuBar(alignFrameMenuBar);
3235
3236     /*
3237      * Configure File menu items and actions
3238      */
3239     inputText
3240             .setLabel(MessageManager.getString("label.input_from_textbox"));
3241     inputText.addActionListener(this);
3242     Menu outputTextboxMenu = new Menu(
3243             MessageManager.getString("label.out_to_textbox"));
3244     for (int i = 0; i < jalview.io.AppletFormatAdapter.WRITEABLE_FORMATS.length; i++)
3245     {
3246
3247       MenuItem item = new MenuItem(
3248               jalview.io.AppletFormatAdapter.WRITEABLE_FORMATS[i]);
3249
3250       item.addActionListener(new java.awt.event.ActionListener()
3251       {
3252         @Override
3253         public void actionPerformed(ActionEvent e)
3254         {
3255           outputText_actionPerformed(e);
3256         }
3257       });
3258
3259       outputTextboxMenu.add(item);
3260     }
3261     closeMenuItem.addActionListener(this);
3262     loadApplication.addActionListener(this);
3263     loadTree.addActionListener(this);
3264     loadAnnotations.addActionListener(this);
3265     outputFeatures.addActionListener(this);
3266     outputAnnotations.addActionListener(this);
3267
3268     /*
3269      * Configure Edit menu items and actions
3270      */
3271     undoMenuItem.setEnabled(false);
3272     undoMenuItem.setLabel(MessageManager.getString("action.undo"));
3273     undoMenuItem.addActionListener(this);
3274     redoMenuItem.setEnabled(false);
3275     redoMenuItem.setLabel(MessageManager.getString("action.redo"));
3276     redoMenuItem.addActionListener(this);
3277     copy.setLabel(MessageManager.getString("action.copy"));
3278     copy.addActionListener(this);
3279     cut.setLabel(MessageManager.getString("action.cut"));
3280     cut.addActionListener(this);
3281     delete.setLabel(MessageManager.getString("action.delete"));
3282     delete.addActionListener(this);
3283     pasteMenu.setLabel(MessageManager.getString("action.paste"));
3284     pasteNew.setLabel(MessageManager.getString("label.to_new_alignment"));
3285     pasteNew.addActionListener(this);
3286     pasteThis.setLabel(MessageManager.getString("label.to_this_alignment"));
3287     pasteThis.addActionListener(this);
3288     remove2LeftMenuItem.setLabel(MessageManager
3289             .getString("action.remove_left"));
3290     remove2LeftMenuItem.addActionListener(this);
3291     remove2RightMenuItem.setLabel(MessageManager
3292             .getString("action.remove_right"));
3293     remove2RightMenuItem.addActionListener(this);
3294     removeGappedColumnMenuItem.setLabel(MessageManager
3295             .getString("action.remove_empty_columns"));
3296     removeGappedColumnMenuItem.addActionListener(this);
3297     removeAllGapsMenuItem.setLabel(MessageManager
3298             .getString("action.remove_all_gaps"));
3299     removeAllGapsMenuItem.addActionListener(this);
3300     removeRedundancyMenuItem.setLabel(MessageManager
3301             .getString("action.remove_redundancy"));
3302     removeRedundancyMenuItem.addActionListener(this);
3303
3304     /*
3305      * Configure Select menu items and actions
3306      */
3307     findMenuItem.setLabel(MessageManager.getString("action.find"));
3308     findMenuItem.addActionListener(this);
3309     selectAllSequenceMenuItem.addActionListener(this);
3310     deselectAllSequenceMenuItem.addActionListener(this);
3311     invertSequenceMenuItem.setLabel(MessageManager
3312             .getString("action.invert_sequence_selection"));
3313     invertSequenceMenuItem.addActionListener(this);
3314     invertColSel.setLabel(MessageManager
3315             .getString("action.invert_column_selection"));
3316     invertColSel.addActionListener(this);
3317     deleteGroups.setLabel(MessageManager
3318             .getString("action.undefine_groups"));
3319     deleteGroups.addActionListener(this);
3320     grpsFromSelection.setLabel(MessageManager
3321             .getString("action.make_groups_selection"));
3322     grpsFromSelection.addActionListener(this);
3323     createGroup.setLabel(MessageManager.getString("action.create_group"));
3324     unGroup.setLabel(MessageManager.getString("action.remove_group"));
3325     annotationColumnSelection.setLabel(MessageManager
3326             .getString("action.select_by_annotation"));
3327     annotationColumnSelection.addActionListener(this);
3328
3329     /*
3330      * Configure View menu items and actions
3331      */
3332     newView.setLabel(MessageManager.getString("action.new_view"));
3333     newView.addActionListener(this);
3334     Menu showMenu = new Menu(MessageManager.getString("action.show"));
3335     showColumns.setLabel(MessageManager.getString("label.all_columns"));
3336     showSeqs.setLabel(MessageManager.getString("label.all_sequences"));
3337     Menu hideMenu = new Menu(MessageManager.getString("action.hide"));
3338     hideColumns
3339             .setLabel(MessageManager.getString("label.selected_columns"));
3340     hideSequences.setLabel(MessageManager
3341             .getString("label.selected_sequences"));
3342     hideAllButSelection.setLabel(MessageManager
3343             .getString("label.all_but_selected_region"));
3344     hideAllSelection.setLabel(MessageManager
3345             .getString("label.selected_region"));
3346     showAllHidden.setLabel(MessageManager
3347             .getString("label.all_sequences_columns"));
3348     showColumns.addActionListener(this);
3349     showSeqs.addActionListener(this);
3350     hideColumns.addActionListener(this);
3351     hideSequences.addActionListener(this);
3352     hideAllButSelection.addActionListener(this);
3353     hideAllSelection.addActionListener(this);
3354     showAllHidden.addActionListener(this);
3355     featureSettings.setLabel(MessageManager
3356             .getString("action.feature_settings"));
3357     featureSettings.addActionListener(this);
3358     sequenceFeatures.setLabel(MessageManager
3359             .getString("label.show_sequence_features"));
3360     sequenceFeatures.addItemListener(this);
3361     sequenceFeatures.setState(false);
3362     followMouseOverFlag.setLabel(MessageManager
3363             .getString("label.automatic_scrolling"));
3364     followMouseOverFlag.addItemListener(this);
3365     alProperties.addActionListener(this);
3366     overviewMenuItem.setLabel(MessageManager
3367             .getString("label.overview_window"));
3368     overviewMenuItem.addActionListener(this);
3369
3370     /*
3371      * Configure Annotations menu items and actions
3372      */
3373     annotationPanelMenuItem.setLabel(MessageManager
3374             .getString("label.show_annotations"));
3375     annotationPanelMenuItem.addItemListener(this);
3376     showGroupConsensus.setLabel(MessageManager
3377             .getString("label.group_consensus"));
3378     showGroupConservation.setLabel(MessageManager
3379             .getString("label.group_conservation"));
3380     showConsensusHistogram.setLabel(MessageManager
3381             .getString("label.show_consensus_histogram"));
3382     showSequenceLogo.setLabel(MessageManager
3383             .getString("label.show_consensus_logo"));
3384     normSequenceLogo.setLabel(MessageManager
3385             .getString("label.norm_consensus_logo"));
3386     applyAutoAnnotationSettings.setLabel(MessageManager
3387             .getString("label.apply_all_groups"));
3388     applyAutoAnnotationSettings.setState(true);
3389     Menu autoAnnMenu = new Menu(
3390             MessageManager.getString("label.autocalculated_annotation"));
3391     showGroupConsensus.addItemListener(this);
3392     showGroupConservation.addItemListener(this);
3393     showConsensusHistogram.addItemListener(this);
3394     showSequenceLogo.addItemListener(this);
3395     normSequenceLogo.addItemListener(this);
3396     applyAutoAnnotationSettings.addItemListener(this);
3397     showAlignmentAnnotations = new CheckboxMenuItem(
3398             MessageManager.getString("label.show_all_al_annotations"));
3399     showSequenceAnnotations = new CheckboxMenuItem(
3400             MessageManager.getString("label.show_all_seq_annotations"));
3401     sortAnnBySequence = new CheckboxMenuItem(
3402             MessageManager.getString("label.sort_annotations_by_sequence"));
3403     sortAnnByLabel = new CheckboxMenuItem(
3404             MessageManager.getString("label.sort_annotations_by_label"));
3405     showAutoFirst = new CheckboxMenuItem(
3406             MessageManager.getString("label.show_first"));
3407     showAutoFirst.setState(false); // pending applet parameter
3408     setShowAutoCalculatedAbove(showAutoFirst.getState());
3409     showAutoLast = new CheckboxMenuItem(
3410             MessageManager.getString("label.show_last"));
3411     showAutoLast.setState(!showAutoFirst.getState());
3412     showAlignmentAnnotations.addItemListener(this);
3413     showSequenceAnnotations.addItemListener(this);
3414     sortAnnBySequence.addItemListener(this);
3415     sortAnnByLabel.addItemListener(this);
3416     showAutoFirst.addItemListener(this);
3417     showAutoLast.addItemListener(this);
3418
3419     /*
3420      * Configure Format menu items and actions
3421      */
3422     font.setLabel(MessageManager.getString("action.font"));
3423     font.addActionListener(this);
3424     scaleAbove.setLabel(MessageManager.getString("action.scale_above"));
3425     scaleAbove.setState(true);
3426     scaleAbove.setEnabled(false);
3427     scaleAbove.addItemListener(this);
3428     scaleLeft.setEnabled(false);
3429     scaleLeft.setState(true);
3430     scaleLeft.setLabel(MessageManager.getString("action.scale_left"));
3431     scaleLeft.addItemListener(this);
3432     scaleRight.setEnabled(false);
3433     scaleRight.setState(true);
3434     scaleRight.setLabel(MessageManager.getString("action.scale_right"));
3435     scaleRight.addItemListener(this);
3436     viewBoxesMenuItem.setLabel(MessageManager.getString("action.boxes"));
3437     viewBoxesMenuItem.setState(true);
3438     viewBoxesMenuItem.addItemListener(this);
3439     viewTextMenuItem.setLabel(MessageManager.getString("action.text"));
3440     viewTextMenuItem.setState(true);
3441     viewTextMenuItem.addItemListener(this);
3442     colourTextMenuItem.setLabel(MessageManager
3443             .getString("label.colour_text"));
3444     colourTextMenuItem.addItemListener(this);
3445     displayNonconservedMenuItem.setLabel(MessageManager
3446             .getString("label.show_non_conversed"));
3447     displayNonconservedMenuItem.addItemListener(this);
3448     wrapMenuItem.setLabel(MessageManager.getString("action.wrap"));
3449     wrapMenuItem.addItemListener(this);
3450     renderGapsMenuItem.setLabel(MessageManager
3451             .getString("action.show_gaps"));
3452     renderGapsMenuItem.setState(true);
3453     renderGapsMenuItem.addItemListener(this);
3454     centreColumnLabelFlag.setLabel(MessageManager
3455             .getString("label.centre_column_labels"));
3456     centreColumnLabelFlag.addItemListener(this);
3457     seqLimits.setState(true);
3458     seqLimits.setLabel(MessageManager
3459             .getString("label.show_sequence_limits"));
3460     seqLimits.addItemListener(this);
3461
3462     /*
3463      * Configure Colour menu items and actions
3464      */
3465     applyToAllGroups.setLabel(MessageManager
3466             .getString("label.apply_colour_to_all_groups"));
3467     applyToAllGroups.setState(true);
3468     applyToAllGroups.addItemListener(this);
3469     clustalColour.setLabel(MessageManager.getString("label.clustalx"));
3470     clustalColour.addActionListener(this);
3471     zappoColour.setLabel(MessageManager.getString("label.zappo"));
3472     zappoColour.addActionListener(this);
3473     taylorColour.setLabel(MessageManager.getString("label.taylor"));
3474     taylorColour.addActionListener(this);
3475     hydrophobicityColour.setLabel(MessageManager
3476             .getString("label.hydrophobicity"));
3477     hydrophobicityColour.addActionListener(this);
3478     helixColour
3479             .setLabel(MessageManager.getString("label.helix_propensity"));
3480     helixColour.addActionListener(this);
3481     strandColour.setLabel(MessageManager
3482             .getString("label.strand_propensity"));
3483     strandColour.addActionListener(this);
3484     turnColour.setLabel(MessageManager.getString("label.turn_propensity"));
3485     turnColour.addActionListener(this);
3486     buriedColour.setLabel(MessageManager.getString("label.buried_index"));
3487     buriedColour.addActionListener(this);
3488     purinePyrimidineColour.setLabel(MessageManager
3489             .getString("label.purine_pyrimidine"));
3490     purinePyrimidineColour.addActionListener(this);
3491     // RNAInteractionColour.setLabel(MessageManager
3492     // .getString("label.rna_interaction"));
3493     // RNAInteractionColour.addActionListener(this);
3494     RNAHelixColour.setLabel(MessageManager
3495             .getString("action.by_rna_helixes"));
3496     RNAHelixColour.addActionListener(this);
3497     userDefinedColour.setLabel(MessageManager
3498             .getString("action.user_defined"));
3499     userDefinedColour.addActionListener(this);
3500     PIDColour.setLabel(MessageManager
3501             .getString("label.percentage_identity"));
3502     PIDColour.addActionListener(this);
3503     BLOSUM62Colour.setLabel(MessageManager
3504             .getString("label.blosum62_score"));
3505     BLOSUM62Colour.addActionListener(this);
3506     tcoffeeColour
3507             .setLabel(MessageManager.getString("label.tcoffee_scores"));
3508     // it will be enabled only if a score file is provided
3509     tcoffeeColour.setEnabled(false);
3510     tcoffeeColour.addActionListener(this);
3511     conservationMenuItem.setLabel(MessageManager
3512             .getString("action.by_conservation"));
3513     conservationMenuItem.addItemListener(this);
3514     noColourmenuItem.setLabel(MessageManager.getString("label.none"));
3515     noColourmenuItem.addActionListener(this);
3516     abovePIDThreshold.setLabel(MessageManager
3517             .getString("label.above_identity_threshold"));
3518     abovePIDThreshold.addItemListener(this);
3519     nucleotideColour.setLabel(MessageManager.getString("label.nucleotide"));
3520     nucleotideColour.addActionListener(this);
3521     modifyPID.setLabel(MessageManager
3522             .getString("label.modify_identity_threshold"));
3523     modifyPID.addActionListener(this);
3524     modifyConservation.setLabel(MessageManager
3525             .getString("label.modify_conservation_threshold"));
3526     modifyConservation.addActionListener(this);
3527     annotationColour.setLabel(MessageManager
3528             .getString("action.by_annotation"));
3529     annotationColour.addActionListener(this);
3530
3531     /*
3532      * Configure Calculate menu items and actions
3533      */
3534     sortPairwiseMenuItem.setLabel(MessageManager
3535             .getString("action.by_pairwise_id"));
3536     sortPairwiseMenuItem.addActionListener(this);
3537     sortIDMenuItem.setLabel(MessageManager.getString("action.by_id"));
3538     sortIDMenuItem.addActionListener(this);
3539     sortLengthMenuItem.setLabel(MessageManager
3540             .getString("action.by_length"));
3541     sortLengthMenuItem.addActionListener(this);
3542     sortGroupMenuItem.setLabel(MessageManager.getString("action.by_group"));
3543     sortGroupMenuItem.addActionListener(this);
3544     pairwiseAlignmentMenuItem.setLabel(MessageManager
3545             .getString("action.pairwise_alignment"));
3546     pairwiseAlignmentMenuItem.addActionListener(this);
3547     PCAMenuItem.setLabel(MessageManager
3548             .getString("label.principal_component_analysis"));
3549     PCAMenuItem.addActionListener(this);
3550     autoCalculate = new CheckboxMenuItem(
3551             MessageManager.getString("label.autocalculate_consensus"), true);
3552     averageDistanceTreeMenuItem.setLabel(MessageManager
3553             .getString("label.average_distance_identity"));
3554     averageDistanceTreeMenuItem.addActionListener(this);
3555     neighbourTreeMenuItem.setLabel(MessageManager
3556             .getString("label.neighbour_joining_identity"));
3557     neighbourTreeMenuItem.addActionListener(this);
3558     avDistanceTreeBlosumMenuItem.setLabel(MessageManager
3559             .getString("label.average_distance_bloslum62"));
3560     avDistanceTreeBlosumMenuItem.addActionListener(this);
3561     njTreeBlosumMenuItem.setLabel(MessageManager
3562             .getString("label.neighbour_blosum62"));
3563     njTreeBlosumMenuItem.addActionListener(this);
3564     sortByTreeMenu.setLabel(MessageManager
3565             .getString("action.by_tree_order"));
3566     Menu sortMenu = new Menu(MessageManager.getString("action.sort"));
3567     Menu calculateTreeMenu = new Menu(
3568             MessageManager.getString("action.calculate_tree"));
3569     autoCalculate.addItemListener(this);
3570     sortByTree.addItemListener(this);
3571
3572     /*
3573      * Configure Help menu items and actions
3574      */
3575     Menu helpMenu = new Menu(MessageManager.getString("action.help"));
3576     documentation.setLabel(MessageManager.getString("label.documentation"));
3577     documentation.addActionListener(this);
3578     about.setLabel(MessageManager.getString("label.about"));
3579     about.addActionListener(this);
3580
3581     /*
3582      * Add top level menus to frame
3583      */
3584     alignFrameMenuBar.add(fileMenu);
3585     Menu editMenu = new Menu(MessageManager.getString("action.edit"));
3586     alignFrameMenuBar.add(editMenu);
3587     Menu selectMenu = new Menu(MessageManager.getString("action.select"));
3588     alignFrameMenuBar.add(selectMenu);
3589     Menu viewMenu = new Menu(MessageManager.getString("action.view"));
3590     alignFrameMenuBar.add(viewMenu);
3591     Menu annotationsMenu = new Menu(
3592             MessageManager.getString("action.annotations"));
3593     alignFrameMenuBar.add(annotationsMenu);
3594     Menu formatMenu = new Menu(MessageManager.getString("action.format"));
3595     alignFrameMenuBar.add(formatMenu);
3596     Menu colourMenu = new Menu(MessageManager.getString("action.colour"));
3597     alignFrameMenuBar.add(colourMenu);
3598     Menu calculateMenu = new Menu(
3599             MessageManager.getString("action.calculate"));
3600     alignFrameMenuBar.add(calculateMenu);
3601     alignFrameMenuBar.add(helpMenu);
3602
3603     /*
3604      * File menu
3605      */
3606     fileMenu.add(inputText);
3607     fileMenu.add(loadTree);
3608     fileMenu.add(loadAnnotations);
3609     fileMenu.addSeparator();
3610     fileMenu.add(outputTextboxMenu);
3611     fileMenu.add(outputFeatures);
3612     fileMenu.add(outputAnnotations);
3613     if (jalviewServletURL != null)
3614     {
3615       fileMenu.add(loadApplication);
3616     }
3617     fileMenu.addSeparator();
3618     fileMenu.add(closeMenuItem);
3619
3620     /*
3621      * Edit menu
3622      */
3623     editMenu.add(undoMenuItem);
3624     editMenu.add(redoMenuItem);
3625     editMenu.add(cut);
3626     editMenu.add(copy);
3627     pasteMenu.add(pasteNew);
3628     pasteMenu.add(pasteThis);
3629     editMenu.add(pasteMenu);
3630     editMenu.add(delete);
3631     editMenu.addSeparator();
3632     editMenu.add(remove2LeftMenuItem);
3633     editMenu.add(remove2RightMenuItem);
3634     editMenu.add(removeGappedColumnMenuItem);
3635     editMenu.add(removeAllGapsMenuItem);
3636     editMenu.add(removeRedundancyMenuItem);
3637
3638     /*
3639      * Select menu
3640      */
3641     selectMenu.add(findMenuItem);
3642     selectMenu.addSeparator();
3643     selectMenu.add(selectAllSequenceMenuItem);
3644     selectMenu.add(deselectAllSequenceMenuItem);
3645     selectMenu.add(invertSequenceMenuItem);
3646     selectMenu.add(invertColSel);
3647     selectMenu.add(createGroup);
3648     selectMenu.add(unGroup);
3649     selectMenu.add(grpsFromSelection);
3650     selectMenu.add(deleteGroups);
3651     selectMenu.add(annotationColumnSelection);
3652
3653     /*
3654      * View menu
3655      */
3656     viewMenu.add(newView);
3657     viewMenu.addSeparator();
3658     showMenu.add(showColumns);
3659     showMenu.add(showSeqs);
3660     showMenu.add(showAllHidden);
3661     viewMenu.add(showMenu);
3662     hideMenu.add(hideColumns);
3663     hideMenu.add(hideSequences);
3664     hideMenu.add(hideAllSelection);
3665     hideMenu.add(hideAllButSelection);
3666     viewMenu.add(hideMenu);
3667     viewMenu.addSeparator();
3668     viewMenu.add(followMouseOverFlag);
3669     viewMenu.addSeparator();
3670     viewMenu.add(sequenceFeatures);
3671     viewMenu.add(featureSettings);
3672     viewMenu.addSeparator();
3673     viewMenu.add(alProperties);
3674     viewMenu.addSeparator();
3675     viewMenu.add(overviewMenuItem);
3676
3677     /*
3678      * Annotations menu
3679      */
3680     annotationsMenu.add(annotationPanelMenuItem);
3681     annotationsMenu.addSeparator();
3682     annotationsMenu.add(showAlignmentAnnotations);
3683     annotationsMenu.add(showSequenceAnnotations);
3684     annotationsMenu.add(sortAnnBySequence);
3685     annotationsMenu.add(sortAnnByLabel);
3686     annotationsMenu.addSeparator();
3687     autoAnnMenu.add(showAutoFirst);
3688     autoAnnMenu.add(showAutoLast);
3689     autoAnnMenu.addSeparator();
3690     autoAnnMenu.add(applyAutoAnnotationSettings);
3691     autoAnnMenu.add(showConsensusHistogram);
3692     autoAnnMenu.add(showSequenceLogo);
3693     autoAnnMenu.add(normSequenceLogo);
3694     autoAnnMenu.addSeparator();
3695     autoAnnMenu.add(showGroupConservation);
3696     autoAnnMenu.add(showGroupConsensus);
3697     annotationsMenu.add(autoAnnMenu);
3698
3699     /*
3700      * Format menu
3701      */
3702     formatMenu.add(font);
3703     formatMenu.add(seqLimits);
3704     formatMenu.add(wrapMenuItem);
3705     formatMenu.add(scaleAbove);
3706     formatMenu.add(scaleLeft);
3707     formatMenu.add(scaleRight);
3708     formatMenu.add(viewBoxesMenuItem);
3709     formatMenu.add(viewTextMenuItem);
3710     formatMenu.add(colourTextMenuItem);
3711     formatMenu.add(displayNonconservedMenuItem);
3712     formatMenu.add(renderGapsMenuItem);
3713     formatMenu.add(centreColumnLabelFlag);
3714
3715     /*
3716      * Colour menu
3717      */
3718     colourMenu.add(applyToAllGroups);
3719     colourMenu.addSeparator();
3720     colourMenu.add(noColourmenuItem);
3721     colourMenu.add(clustalColour);
3722     colourMenu.add(BLOSUM62Colour);
3723     colourMenu.add(PIDColour);
3724     colourMenu.add(zappoColour);
3725     colourMenu.add(taylorColour);
3726     colourMenu.add(hydrophobicityColour);
3727     colourMenu.add(helixColour);
3728     colourMenu.add(strandColour);
3729     colourMenu.add(turnColour);
3730     colourMenu.add(buriedColour);
3731     colourMenu.add(nucleotideColour);
3732     colourMenu.add(purinePyrimidineColour);
3733     // colourMenu.add(RNAInteractionColour);
3734     colourMenu.add(tcoffeeColour);
3735     colourMenu.add(userDefinedColour);
3736     colourMenu.addSeparator();
3737     colourMenu.add(conservationMenuItem);
3738     colourMenu.add(modifyConservation);
3739     colourMenu.add(abovePIDThreshold);
3740     colourMenu.add(modifyPID);
3741     colourMenu.add(annotationColour);
3742     colourMenu.add(RNAHelixColour);
3743
3744     /*
3745      * Calculate menu
3746      */
3747     sortMenu.add(sortIDMenuItem);
3748     sortMenu.add(sortLengthMenuItem);
3749     sortMenu.add(sortByTreeMenu);
3750     sortMenu.add(sortGroupMenuItem);
3751     sortMenu.add(sortPairwiseMenuItem);
3752     calculateMenu.add(sortMenu);
3753     calculateTreeMenu.add(averageDistanceTreeMenuItem);
3754     calculateTreeMenu.add(neighbourTreeMenuItem);
3755     calculateTreeMenu.add(avDistanceTreeBlosumMenuItem);
3756     calculateTreeMenu.add(njTreeBlosumMenuItem);
3757     calculateMenu.add(calculateTreeMenu);
3758     calculateMenu.addSeparator();
3759     calculateMenu.add(pairwiseAlignmentMenuItem);
3760     calculateMenu.add(PCAMenuItem);
3761     calculateMenu.add(autoCalculate);
3762     calculateMenu.add(sortByTree);
3763
3764     /*
3765      * Help menu
3766      */
3767     helpMenu.add(documentation);
3768     helpMenu.add(about);
3769
3770     /*
3771      * Status bar
3772      */
3773     statusBar.setBackground(Color.white);
3774     statusBar.setFont(new java.awt.Font("Verdana", 0, 11));
3775     statusBar.setText(MessageManager.getString("label.status_bar"));
3776     this.add(statusBar, BorderLayout.SOUTH);
3777   }
3778
3779   @Override
3780   public void setStatus(String string)
3781   {
3782     statusBar.setText(string);
3783   };
3784
3785   MenuItem featureSettings = new MenuItem();
3786
3787   CheckboxMenuItem sequenceFeatures = new CheckboxMenuItem();
3788
3789   MenuItem annotationColour = new MenuItem();
3790
3791   MenuItem annotationColumnSelection = new MenuItem();
3792
3793   MenuItem invertColSel = new MenuItem();
3794
3795   MenuItem showColumns = new MenuItem();
3796
3797   MenuItem showSeqs = new MenuItem();
3798
3799   MenuItem hideColumns = new MenuItem();
3800
3801   MenuItem hideSequences = new MenuItem();
3802
3803   MenuItem hideAllButSelection = new MenuItem();
3804
3805   MenuItem hideAllSelection = new MenuItem();
3806
3807   MenuItem showAllHidden = new MenuItem();
3808
3809   MenuItem newView = new MenuItem();
3810
3811   private CheckboxMenuItem showAlignmentAnnotations;
3812
3813   private CheckboxMenuItem showSequenceAnnotations;
3814
3815   private CheckboxMenuItem sortAnnBySequence;
3816
3817   private CheckboxMenuItem sortAnnByLabel;
3818
3819   private CheckboxMenuItem showAutoFirst;
3820
3821   private CheckboxMenuItem showAutoLast;
3822
3823   private SplitFrame splitFrame;
3824
3825   /**
3826    * Attach the alignFrame panels after embedding menus, if necessary. This used
3827    * to be called setEmbedded, but is now creates the dropdown menus in a
3828    * platform independent manner to avoid OSX/Mac menu appendage daftness.
3829    * 
3830    * @param reallyEmbedded
3831    *          true to attach the view to the applet area on the page rather than
3832    *          in a new window
3833    */
3834   public void createAlignFrameWindow(boolean reallyEmbedded)
3835   {
3836     if (reallyEmbedded)
3837     {
3838       embedAlignFrameInApplet(viewport.applet);
3839     }
3840     else
3841     {
3842       // //////
3843       // test and embed menu bar if necessary.
3844       //
3845       if (embedMenuIfNeeded(alignPanel))
3846       {
3847         /*
3848          * adjust for status bar height too. ? pointless as overridden by layout
3849          * manager
3850          */
3851         alignPanel.setSize(getSize().width,
3852                 getSize().height - statusBar.getHeight());
3853       }
3854       add(statusBar, BorderLayout.SOUTH);
3855       add(alignPanel, BorderLayout.CENTER);
3856       // and register with the applet so it can pass external API calls to us
3857       jalview.bin.JalviewLite.addFrame(this, this.getTitle(), frameWidth,
3858               frameHeight);
3859     }
3860   }
3861
3862   /**
3863    * Add the components of this AlignFrame to the applet container.
3864    * 
3865    * @param theApplet
3866    */
3867   public void embedAlignFrameInApplet(final JalviewLite theApplet)
3868   {
3869     // ////
3870     // Explicitly build the embedded menu panel for the on-page applet
3871     //
3872     // view cannot be closed if its actually on the page
3873     fileMenu.remove(closeMenuItem);
3874     fileMenu.remove(3); // Remove Separator
3875     // construct embedded menu, using default font
3876     embeddedMenu = makeEmbeddedPopupMenu(alignFrameMenuBar, false, false);
3877     // and actually add the components to the applet area
3878     theApplet.setLayout(new BorderLayout());
3879     theApplet.add(embeddedMenu, BorderLayout.NORTH);
3880     theApplet.add(statusBar, BorderLayout.SOUTH);
3881     // TODO should size be left to the layout manager?
3882     alignPanel.setSize(theApplet.getSize().width,
3883             theApplet.getSize().height - embeddedMenu.getHeight()
3884                     - statusBar.getHeight());
3885     theApplet.add(alignPanel, BorderLayout.CENTER);
3886     final AlignFrame me = this;
3887     theApplet.addFocusListener(new FocusListener()
3888     {
3889
3890       @Override
3891       public void focusLost(FocusEvent e)
3892       {
3893         if (theApplet.currentAlignFrame == me)
3894         {
3895           theApplet.currentAlignFrame = null;
3896         }
3897       }
3898
3899       @Override
3900       public void focusGained(FocusEvent e)
3901       {
3902         theApplet.currentAlignFrame = me;
3903       }
3904     });
3905     theApplet.validate();
3906   }
3907
3908   /**
3909    * create a new binding between structures in an existing jmol viewer instance
3910    * and an alignpanel with sequences that have existing PDBFile entries. Note,
3911    * this does not open a new Jmol window, or modify the display of the
3912    * structures in the original jmol window. Note This method doesn't work
3913    * without an additional javascript library to exchange messages between the
3914    * distinct applets. See http://issues.jalview.org/browse/JAL-621
3915    * 
3916    * @param viewer
3917    *          JmolViewer instance
3918    * @param sequenceIds
3919    *          - sequence Ids to search for associations
3920    */
3921   public SequenceStructureBinding addStructureViewInstance(
3922           Object jmolviewer, String[] sequenceIds)
3923   {
3924     Viewer viewer = null;
3925     try
3926     {
3927       viewer = (Viewer) jmolviewer;
3928     } catch (ClassCastException ex)
3929     {
3930       System.err.println("Unsupported viewer object :"
3931               + jmolviewer.getClass());
3932     }
3933     if (viewer == null)
3934     {
3935       System.err.println("Can't use this object as a structure viewer:"
3936               + jmolviewer.getClass());
3937       return null;
3938     }
3939     SequenceI[] seqs = null;
3940     if (sequenceIds == null || sequenceIds.length == 0)
3941     {
3942       seqs = viewport.getAlignment().getSequencesArray();
3943     }
3944     else
3945     {
3946       Vector sqi = new Vector();
3947       AlignmentI al = viewport.getAlignment();
3948       for (int sid = 0; sid < sequenceIds.length; sid++)
3949       {
3950         SequenceI sq = al.findName(sequenceIds[sid]);
3951         if (sq != null)
3952         {
3953           sqi.addElement(sq);
3954         }
3955       }
3956       if (sqi.size() > 0)
3957       {
3958         seqs = new SequenceI[sqi.size()];
3959         for (int sid = 0, sSize = sqi.size(); sid < sSize; sid++)
3960         {
3961           seqs[sid] = (SequenceI) sqi.elementAt(sid);
3962         }
3963       }
3964       else
3965       {
3966         return null;
3967       }
3968     }
3969     AAStructureBindingModel jmv = null;
3970     // TODO: search for a jmv that involves viewer
3971     if (jmv == null)
3972     { // create a new viewer/jalview binding.
3973       jmv = new ExtJmol(viewer, alignPanel, new SequenceI[][] { seqs });
3974     }
3975     return jmv;
3976
3977   }
3978
3979   /**
3980    * bind a pdb file to a sequence in the current view
3981    * 
3982    * @param sequenceId
3983    *          - sequenceId within the dataset.
3984    * @param pdbEntryString
3985    *          - the short name for the PDB file
3986    * @param pdbFile
3987    *          - pdb file - either a URL or a valid PDB file.
3988    * @return true if binding was as success TODO: consider making an exception
3989    *         structure for indicating when PDB parsing or sequenceId location
3990    *         fails.
3991    */
3992   public boolean addPdbFile(String sequenceId, String pdbEntryString,
3993           String pdbFile)
3994   {
3995     SequenceI toaddpdb = viewport.getAlignment().findName(sequenceId);
3996     boolean needtoadd = false;
3997     if (toaddpdb != null)
3998     {
3999       Vector pdbe = toaddpdb.getAllPDBEntries();
4000       PDBEntry pdbentry = null;
4001       if (pdbe != null && pdbe.size() > 0)
4002       {
4003         for (int pe = 0, peSize = pdbe.size(); pe < peSize; pe++)
4004         {
4005           pdbentry = (PDBEntry) pdbe.elementAt(pe);
4006           if (!pdbentry.getId().equals(pdbEntryString)
4007                   && !pdbentry.getFile().equals(pdbFile))
4008           {
4009             pdbentry = null;
4010           }
4011           else
4012           {
4013             continue;
4014           }
4015         }
4016       }
4017       if (pdbentry == null)
4018       {
4019         pdbentry = new PDBEntry();
4020         pdbentry.setId(pdbEntryString);
4021         pdbentry.setFile(pdbFile);
4022         needtoadd = true; // add this new entry to sequence.
4023       }
4024       // resolve data source
4025       // TODO: this code should be a refactored to an io package
4026       DataSourceType protocol = AppletFormatAdapter.resolveProtocol(
4027               pdbFile, FileFormat.PDB);
4028       if (protocol == null)
4029       {
4030         return false;
4031       }
4032       if (needtoadd)
4033       {
4034         // make a note of the access mode and add
4035         if (pdbentry.getProperty() == null)
4036         {
4037           pdbentry.setProperty(new Hashtable<String, String>());
4038         }
4039         pdbentry.getProperty().put("protocol", protocol.toString());
4040         toaddpdb.addPDBId(pdbentry);
4041         alignPanel.getStructureSelectionManager()
4042                 .registerPDBEntry(pdbentry);
4043       }
4044     }
4045     return true;
4046   }
4047
4048   private Object[] cleanSeqChainArrays(SequenceI[] seqs, String[] chains)
4049   {
4050     if (seqs != null)
4051     {
4052       Vector sequences = new Vector();
4053       for (int i = 0; i < seqs.length; i++)
4054       {
4055         if (seqs[i] != null)
4056         {
4057           sequences.addElement(new Object[] { seqs[i],
4058               (chains != null) ? chains[i] : null });
4059         }
4060       }
4061       seqs = new SequenceI[sequences.size()];
4062       chains = new String[sequences.size()];
4063       for (int i = 0, isize = sequences.size(); i < isize; i++)
4064       {
4065         Object[] oj = (Object[]) sequences.elementAt(i);
4066
4067         seqs[i] = (SequenceI) oj[0];
4068         chains[i] = (String) oj[1];
4069       }
4070     }
4071     return new Object[] { seqs, chains };
4072
4073   }
4074
4075   public void newStructureView(JalviewLite applet, PDBEntry pdb,
4076           SequenceI[] seqs, String[] chains, DataSourceType protocol)
4077   {
4078     // Scrub any null sequences from the array
4079     Object[] sqch = cleanSeqChainArrays(seqs, chains);
4080     seqs = (SequenceI[]) sqch[0];
4081     chains = (String[]) sqch[1];
4082     if (seqs == null || seqs.length == 0)
4083     {
4084       System.err
4085               .println("JalviewLite.AlignFrame:newStructureView: No sequence to bind structure to.");
4086     }
4087     if (protocol == null)
4088     {
4089       String sourceType = pdb.getProperty().get("protocol");
4090       try
4091       {
4092         protocol = DataSourceType.valueOf(sourceType);
4093       } catch (IllegalArgumentException e)
4094       {
4095         // ignore
4096       }
4097       if (protocol == null)
4098       {
4099         System.err.println("Couldn't work out protocol to open structure: "
4100                 + pdb.getId());
4101         return;
4102       }
4103     }
4104     if (applet.useXtrnalSviewer)
4105     {
4106       // register the association(s) and quit, don't create any windows.
4107       if (StructureSelectionManager.getStructureSelectionManager(applet)
4108               .setMapping(seqs, chains, pdb.getFile(), protocol) == null)
4109       {
4110         System.err.println("Failed to map " + pdb.getFile() + " ("
4111                 + protocol + ") to any sequences");
4112       }
4113       return;
4114     }
4115     if (applet.isAlignPdbStructures() && applet.jmolAvailable)
4116     {
4117       // can only do alignments with Jmol
4118       // find the last jmol window assigned to this alignment
4119       AppletJmol ajm = null, tajm;
4120       Vector jmols = applet.getAppletWindow(AppletJmol.class);
4121       for (int i = 0, iSize = jmols.size(); i < iSize; i++)
4122       {
4123         tajm = (AppletJmol) jmols.elementAt(i);
4124         if (tajm.ap.alignFrame == this)
4125         {
4126           ajm = tajm;
4127           break;
4128         }
4129       }
4130       if (ajm != null)
4131       {
4132         System.err
4133                 .println("Incremental adding and aligning structure to existing Jmol view not yet implemented.");
4134         // try and add the pdb structure
4135         // ajm.addS
4136         ajm = null;
4137       }
4138     }
4139     // otherwise, create a new window
4140     if (applet.jmolAvailable)
4141     {
4142       new AppletJmol(pdb, seqs, chains, alignPanel,
4143               protocol);
4144       applet.lastFrameX += 40;
4145       applet.lastFrameY += 40;
4146     }
4147     else
4148     {
4149       new MCview.AppletPDBViewer(pdb, seqs, chains, alignPanel, protocol);
4150     }
4151
4152   }
4153
4154   public void alignedStructureView(JalviewLite applet, PDBEntry[] pdb,
4155           SequenceI[][] seqs, String[][] chains, String[] protocols)
4156   {
4157     // TODO Auto-generated method stub
4158     System.err.println("Aligned Structure View: Not yet implemented.");
4159   }
4160
4161   /**
4162    * modify the current selection, providing the user has not made a selection
4163    * already.
4164    * 
4165    * @param sel
4166    *          - sequences from this alignment
4167    * @param csel
4168    *          - columns to be selected on the alignment
4169    */
4170   public void select(SequenceGroup sel, ColumnSelection csel)
4171   {
4172     alignPanel.seqPanel.selection(sel, csel, null);
4173   }
4174
4175   public void scrollTo(int row, int column)
4176   {
4177     alignPanel.seqPanel.scrollTo(row, column);
4178   }
4179
4180   public void scrollToRow(int row)
4181   {
4182     alignPanel.seqPanel.scrollToRow(row);
4183   }
4184
4185   public void scrollToColumn(int column)
4186   {
4187     alignPanel.seqPanel.scrollToColumn(column);
4188   }
4189
4190   /**
4191    * @return the alignments unique ID.
4192    */
4193   public String getSequenceSetId()
4194   {
4195     return viewport.getSequenceSetId();
4196   }
4197
4198   /**
4199    * Load the (T-Coffee) score file from the specified url
4200    * 
4201    * @param source
4202    *          File/URL/T-COFFEE score file contents
4203    * @throws IOException
4204    * @return true if alignment was annotated with data from source
4205    */
4206   public boolean loadScoreFile(String source) throws IOException
4207   {
4208
4209     TCoffeeScoreFile file = new TCoffeeScoreFile(source,
4210             AppletFormatAdapter.checkProtocol(source));
4211     if (!file.isValid())
4212     {
4213       // TODO: raise dialog for gui
4214       System.err.println("Problems parsing T-Coffee scores: "
4215               + file.getWarningMessage());
4216       System.err.println("Origin was:\n" + source);
4217       return false;
4218     }
4219
4220     /*
4221      * check that the score matrix matches the alignment dimensions
4222      */
4223     AlignmentI aln;
4224     if ((aln = viewport.getAlignment()) != null
4225             && (aln.getHeight() != file.getHeight() || aln.getWidth() != file
4226                     .getWidth()))
4227     {
4228       // TODO: raise a dialog box here rather than bomb out.
4229       System.err
4230               .println("The scores matrix does not match the alignment dimensions");
4231
4232     }
4233
4234     // TODO add parameter to indicate if matching should be done
4235     if (file.annotateAlignment(alignPanel.getAlignment(), false))
4236     {
4237       alignPanel.fontChanged();
4238       tcoffeeColour.setEnabled(true);
4239       // switch to this color
4240       changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4241       return true;
4242     }
4243     else
4244     {
4245       System.err.println("Problems resolving T-Coffee scores:");
4246       if (file.getWarningMessage() != null)
4247       {
4248         System.err.println(file.getWarningMessage());
4249       }
4250     }
4251     return false;
4252   }
4253
4254   public SplitFrame getSplitFrame()
4255   {
4256     return this.splitFrame;
4257   }
4258
4259   public void setSplitFrame(SplitFrame sf)
4260   {
4261     this.splitFrame = sf;
4262   }
4263
4264   // may not need this
4265   @Override
4266   public void setShowSeqFeatures(boolean b)
4267   {
4268     // showSeqFeatures.setSelected(b);
4269     viewport.setShowSequenceFeatures(b);
4270
4271   }
4272
4273   @Override
4274   public void setMenusForViewport()
4275   {
4276     // setMenusFromViewport(viewport);
4277
4278   }
4279
4280   @Override
4281   public void refreshFeatureUI(boolean enableIfNecessary)
4282   {
4283     if (enableIfNecessary)
4284     {
4285       sequenceFeatures.setState(true);
4286       alignPanel.av.setShowSequenceFeatures(true);
4287     }
4288   }
4289
4290   @Override
4291   public FeatureSettingsControllerI getFeatureSettingsUI()
4292   {
4293     return alignPanel.av.featureSettings;
4294   }
4295
4296 }