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