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