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