997647116aec7b48c31271e18883281acb36c049
[jalview.git] / src / jalview / gui / PopupMenu.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
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
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.analysis.AAFrequency;
24 import jalview.analysis.AlignmentAnnotationUtils;
25 import jalview.analysis.Conservation;
26 import jalview.commands.ChangeCaseCommand;
27 import jalview.commands.EditCommand;
28 import jalview.commands.EditCommand.Action;
29 import jalview.datamodel.AlignmentAnnotation;
30 import jalview.datamodel.Annotation;
31 import jalview.datamodel.DBRefEntry;
32 import jalview.datamodel.PDBEntry;
33 import jalview.datamodel.Sequence;
34 import jalview.datamodel.SequenceFeature;
35 import jalview.datamodel.SequenceGroup;
36 import jalview.datamodel.SequenceI;
37 import jalview.io.FormatAdapter;
38 import jalview.io.SequenceAnnotationReport;
39 import jalview.schemes.AnnotationColourGradient;
40 import jalview.schemes.Blosum62ColourScheme;
41 import jalview.schemes.BuriedColourScheme;
42 import jalview.schemes.ClustalxColourScheme;
43 import jalview.schemes.HelixColourScheme;
44 import jalview.schemes.HydrophobicColourScheme;
45 import jalview.schemes.NucleotideColourScheme;
46 import jalview.schemes.PIDColourScheme;
47 import jalview.schemes.PurinePyrimidineColourScheme;
48 import jalview.schemes.ResidueProperties;
49 import jalview.schemes.StrandColourScheme;
50 import jalview.schemes.TaylorColourScheme;
51 import jalview.schemes.TurnColourScheme;
52 import jalview.schemes.UserColourScheme;
53 import jalview.schemes.ZappoColourScheme;
54 import jalview.util.GroupUrlLink;
55 import jalview.util.GroupUrlLink.UrlStringTooLongException;
56 import jalview.util.MessageManager;
57 import jalview.util.UrlLink;
58
59 import java.awt.Color;
60 import java.awt.event.ActionEvent;
61 import java.awt.event.ActionListener;
62 import java.util.ArrayList;
63 import java.util.Arrays;
64 import java.util.Collection;
65 import java.util.Collections;
66 import java.util.Hashtable;
67 import java.util.LinkedHashMap;
68 import java.util.List;
69 import java.util.Map;
70 import java.util.TreeMap;
71 import java.util.Vector;
72
73 import javax.swing.ButtonGroup;
74 import javax.swing.JCheckBoxMenuItem;
75 import javax.swing.JColorChooser;
76 import javax.swing.JMenu;
77 import javax.swing.JMenuItem;
78 import javax.swing.JOptionPane;
79 import javax.swing.JPopupMenu;
80 import javax.swing.JRadioButtonMenuItem;
81
82 /**
83  * DOCUMENT ME!
84  * 
85  * @author $author$
86  * @version $Revision: 1.118 $
87  */
88 public class PopupMenu extends JPopupMenu
89 {
90   private static final String ALL_ANNOTATIONS = "All";
91
92   private static final String COMMA = ",";
93
94   JMenu groupMenu = new JMenu();
95
96   JMenuItem groupName = new JMenuItem();
97
98   protected JRadioButtonMenuItem clustalColour = new JRadioButtonMenuItem();
99
100   protected JRadioButtonMenuItem zappoColour = new JRadioButtonMenuItem();
101
102   protected JRadioButtonMenuItem taylorColour = new JRadioButtonMenuItem();
103
104   protected JRadioButtonMenuItem hydrophobicityColour = new JRadioButtonMenuItem();
105
106   protected JRadioButtonMenuItem helixColour = new JRadioButtonMenuItem();
107
108   protected JRadioButtonMenuItem strandColour = new JRadioButtonMenuItem();
109
110   protected JRadioButtonMenuItem turnColour = new JRadioButtonMenuItem();
111
112   protected JRadioButtonMenuItem buriedColour = new JRadioButtonMenuItem();
113
114   protected JCheckBoxMenuItem abovePIDColour = new JCheckBoxMenuItem();
115
116   protected JRadioButtonMenuItem userDefinedColour = new JRadioButtonMenuItem();
117
118   protected JRadioButtonMenuItem PIDColour = new JRadioButtonMenuItem();
119
120   protected JRadioButtonMenuItem BLOSUM62Colour = new JRadioButtonMenuItem();
121
122   protected JRadioButtonMenuItem purinePyrimidineColour = new JRadioButtonMenuItem();
123
124   protected JRadioButtonMenuItem RNAInteractionColour = new JRadioButtonMenuItem();
125
126   // protected JRadioButtonMenuItem covariationColour = new
127   // JRadioButtonMenuItem();
128
129   JRadioButtonMenuItem noColourmenuItem = new JRadioButtonMenuItem();
130
131   protected JCheckBoxMenuItem conservationMenuItem = new JCheckBoxMenuItem();
132
133   AlignmentPanel ap;
134
135   JMenu sequenceMenu = new JMenu();
136
137   JMenuItem sequenceName = new JMenuItem();
138
139   JMenuItem sequenceDetails = new JMenuItem();
140
141   JMenuItem sequenceSelDetails = new JMenuItem();
142
143   JMenuItem chooseAnnotations = new JMenuItem();
144
145   SequenceI sequence;
146
147   JMenuItem createGroupMenuItem = new JMenuItem();
148
149   JMenuItem unGroupMenuItem = new JMenuItem();
150
151   JMenuItem outline = new JMenuItem();
152
153   JRadioButtonMenuItem nucleotideMenuItem = new JRadioButtonMenuItem();
154
155   JMenu colourMenu = new JMenu();
156
157   JCheckBoxMenuItem showBoxes = new JCheckBoxMenuItem();
158
159   JCheckBoxMenuItem showText = new JCheckBoxMenuItem();
160
161   JCheckBoxMenuItem showColourText = new JCheckBoxMenuItem();
162
163   JCheckBoxMenuItem displayNonconserved = new JCheckBoxMenuItem();
164
165   JMenu editMenu = new JMenu();
166
167   JMenuItem cut = new JMenuItem();
168
169   JMenuItem copy = new JMenuItem();
170
171   JMenuItem upperCase = new JMenuItem();
172
173   JMenuItem lowerCase = new JMenuItem();
174
175   JMenuItem toggle = new JMenuItem();
176
177   JMenu pdbMenu = new JMenu();
178
179   JMenuItem pdbFromFile = new JMenuItem();
180
181   // JBPNote: Commented these out - Should add these services via the web
182   // services menu system.
183   // JMenuItem ContraFold = new JMenuItem();
184
185   // JMenuItem RNAFold = new JMenuItem();
186
187   JMenuItem enterPDB = new JMenuItem();
188
189   JMenuItem discoverPDB = new JMenuItem();
190
191   JMenu outputMenu = new JMenu();
192
193   JMenu seqShowAnnotationsMenu = new JMenu();
194
195   JMenu seqHideAnnotationsMenu = new JMenu();
196
197   JMenuItem seqAddReferenceAnnotations = new JMenuItem();
198
199   JMenu groupShowAnnotationsMenu = new JMenu();
200
201   JMenu groupHideAnnotationsMenu = new JMenu();
202
203   JMenuItem groupAddReferenceAnnotations = new JMenuItem();
204
205   JMenuItem sequenceFeature = new JMenuItem();
206
207   JMenuItem textColour = new JMenuItem();
208
209   JMenu jMenu1 = new JMenu();
210
211   JMenu structureMenu = new JMenu();
212
213   JMenu viewStructureMenu = new JMenu();
214
215   // JMenu colStructureMenu = new JMenu();
216   JMenuItem editSequence = new JMenuItem();
217
218   // JMenuItem annotationMenuItem = new JMenuItem();
219
220   JMenu groupLinksMenu;
221
222   /**
223    * Creates a new PopupMenu object.
224    * 
225    * @param ap
226    *          DOCUMENT ME!
227    * @param seq
228    *          DOCUMENT ME!
229    */
230   public PopupMenu(final AlignmentPanel ap, Sequence seq, Vector links)
231   {
232     this(ap, seq, links, null);
233   }
234
235   /**
236    * 
237    * @param ap
238    * @param seq
239    * @param links
240    * @param groupLinks
241    */
242   public PopupMenu(final AlignmentPanel ap, final SequenceI seq,
243           Vector links, Vector groupLinks)
244   {
245     // /////////////////////////////////////////////////////////
246     // If this is activated from the sequence panel, the user may want to
247     // edit or annotate a particular residue. Therefore display the residue menu
248     //
249     // If from the IDPanel, we must display the sequence menu
250     // ////////////////////////////////////////////////////////
251     this.ap = ap;
252     sequence = seq;
253
254     ButtonGroup colours = new ButtonGroup();
255     colours.add(noColourmenuItem);
256     colours.add(clustalColour);
257     colours.add(zappoColour);
258     colours.add(taylorColour);
259     colours.add(hydrophobicityColour);
260     colours.add(helixColour);
261     colours.add(strandColour);
262     colours.add(turnColour);
263     colours.add(buriedColour);
264     colours.add(abovePIDColour);
265     colours.add(userDefinedColour);
266     colours.add(PIDColour);
267     colours.add(BLOSUM62Colour);
268     colours.add(purinePyrimidineColour);
269     colours.add(RNAInteractionColour);
270     // colours.add(covariationColour);
271
272     for (int i = 0; i < jalview.io.FormatAdapter.WRITEABLE_FORMATS.length; i++)
273     {
274       JMenuItem item = new JMenuItem(
275               jalview.io.FormatAdapter.WRITEABLE_FORMATS[i]);
276
277       item.addActionListener(new java.awt.event.ActionListener()
278       {
279         @Override
280         public void actionPerformed(ActionEvent e)
281         {
282           outputText_actionPerformed(e);
283         }
284       });
285
286       outputMenu.add(item);
287     }
288
289     /*
290      * Build menus for annotation types that may be shown or hidden, and for
291      * 'reference annotations' that may be added to the alignment. First for the
292      * currently selected sequence (if there is one):
293      */
294     final List<SequenceI> selectedSequence = (seq == null ? Collections
295             .<SequenceI> emptyList() : Arrays.asList(seq));
296     buildAnnotationTypesMenus(seqShowAnnotationsMenu,
297             seqHideAnnotationsMenu, selectedSequence);
298     configureReferenceAnnotationsMenu(seqAddReferenceAnnotations,
299             selectedSequence);
300
301     /*
302      * And repeat for the current selection group (if there is one):
303      */
304     final List<SequenceI> selectedGroup = (ap.av.getSelectionGroup() == null ? Collections
305             .<SequenceI> emptyList() : ap.av.getSelectionGroup()
306             .getSequences());
307     buildAnnotationTypesMenus(groupShowAnnotationsMenu,
308             groupHideAnnotationsMenu, selectedGroup);
309     configureReferenceAnnotationsMenu(groupAddReferenceAnnotations,
310             selectedGroup);
311
312     try
313     {
314       jbInit();
315     } catch (Exception e)
316     {
317       e.printStackTrace();
318     }
319
320     JMenuItem menuItem;
321     if (seq != null)
322     {
323       sequenceMenu.setText(sequence.getName());
324
325       if (seq.getDatasetSequence().getPDBId() != null
326               && seq.getDatasetSequence().getPDBId().size() > 0)
327       {
328         java.util.Enumeration e = seq.getDatasetSequence().getPDBId()
329                 .elements();
330
331         while (e.hasMoreElements())
332         {
333           final PDBEntry pdb = (PDBEntry) e.nextElement();
334
335           menuItem = new JMenuItem();
336           menuItem.setText(pdb.getId());
337           menuItem.addActionListener(new ActionListener()
338           {
339             @Override
340             public void actionPerformed(ActionEvent e)
341             {
342               // TODO re JAL-860: optionally open dialog or provide a menu entry
343               // allowing user to open just one structure per sequence
344               // new AppJmol(pdb, ap.av.collateForPDB(new PDBEntry[]
345               // { pdb })[0], null, ap);
346               new StructureViewer(ap.getStructureSelectionManager())
347                       .viewStructures(pdb,
348                               ap.av.collateForPDB(new PDBEntry[]
349                               { pdb })[0], null, ap);
350             }
351           });
352           viewStructureMenu.add(menuItem);
353
354           /*
355            * menuItem = new JMenuItem(); menuItem.setText(pdb.getId());
356            * menuItem.addActionListener(new java.awt.event.ActionListener() {
357            * public void actionPerformed(ActionEvent e) {
358            * colourByStructure(pdb.getId()); } });
359            * colStructureMenu.add(menuItem);
360            */
361         }
362       }
363       else
364       {
365         if (ap.av.getAlignment().isNucleotide() == false)
366         {
367           structureMenu.remove(viewStructureMenu);
368         }
369         // structureMenu.remove(colStructureMenu);
370       }
371
372       if (ap.av.getAlignment().isNucleotide() == true)
373       {
374         AlignmentAnnotation[] aa = ap.av.getAlignment()
375                 .getAlignmentAnnotation();
376         for (int i = 0; aa != null && i < aa.length; i++)
377         {
378           if (aa[i].isValidStruc() && aa[i].sequenceRef == null)
379           {
380             final String rnastruc = aa[i].getRNAStruc();
381             final String structureLine = aa[i].label + " (alignment)";
382             menuItem = new JMenuItem();
383             menuItem.setText(MessageManager.formatMessage(
384                     "label.2d_rna_structure_line", new String[]
385                     { structureLine }));
386             menuItem.addActionListener(new java.awt.event.ActionListener()
387             {
388               @Override
389               public void actionPerformed(ActionEvent e)
390               {
391                 // // System.out.println("1:"+structureLine);
392                 // System.out.println("1:sname" + seq.getName());
393                 // System.out.println("2:seq" + seq);
394                 //
395                 // // System.out.println("3:"+seq.getSequenceAsString());
396                 // System.out.println("3:strucseq" + rnastruc);
397                 // // System.out.println("4:struc"+seq.getRNA());
398                 // System.out.println("5:name" + seq.getName());
399                 // System.out.println("6:ap" + ap);
400                 new AppVarna(structureLine, seq, seq.getSequenceAsString(),
401                         rnastruc, seq.getName(), ap);
402                 // new AppVarna(seq.getName(),seq,rnastruc,seq.getRNA(),
403                 // seq.getName(), ap);
404                 System.out.println("end");
405               }
406             });
407             viewStructureMenu.add(menuItem);
408           }
409         }
410
411         // SequenceFeatures[] test = seq.getSequenceFeatures();
412
413         if (seq.getAnnotation() != null)
414         {
415           AlignmentAnnotation seqAnno[] = seq.getAnnotation();
416           for (int i = 0; i < seqAnno.length; i++)
417           {
418             if (seqAnno[i].isValidStruc())
419             {
420               final String rnastruc = seqAnno[i].getRNAStruc();
421
422               // TODO: make rnastrucF a bit more nice
423               menuItem = new JMenuItem();
424               menuItem.setText(MessageManager.formatMessage(
425                       "label.2d_rna_sequence_name", new String[]
426                       { seq.getName() }));
427               menuItem.addActionListener(new java.awt.event.ActionListener()
428               {
429                 @Override
430                 public void actionPerformed(ActionEvent e)
431                 {
432                   // TODO: VARNA does'nt print gaps in the sequence
433
434                   new AppVarna(seq.getName() + " structure", seq, seq
435                           .getSequenceAsString(), rnastruc, seq.getName(),
436                           ap);
437                 }
438               });
439               viewStructureMenu.add(menuItem);
440             }
441           }
442         }
443
444       }
445
446       menuItem = new JMenuItem(
447               MessageManager.getString("action.hide_sequences"));
448       menuItem.addActionListener(new java.awt.event.ActionListener()
449       {
450         @Override
451         public void actionPerformed(ActionEvent e)
452         {
453           hideSequences(false);
454         }
455       });
456       add(menuItem);
457
458       if (ap.av.getSelectionGroup() != null
459               && ap.av.getSelectionGroup().getSize() > 1)
460       {
461         menuItem = new JMenuItem(MessageManager.formatMessage(
462                 "label.represent_group_with", new String[]
463                 { seq.getName() }));
464         menuItem.addActionListener(new java.awt.event.ActionListener()
465         {
466           @Override
467           public void actionPerformed(ActionEvent e)
468           {
469             hideSequences(true);
470           }
471         });
472         sequenceMenu.add(menuItem);
473       }
474
475       if (ap.av.hasHiddenRows())
476       {
477         final int index = ap.av.getAlignment().findIndex(seq);
478
479         if (ap.av.adjustForHiddenSeqs(index)
480                 - ap.av.adjustForHiddenSeqs(index - 1) > 1)
481         {
482           menuItem = new JMenuItem(
483                   MessageManager.getString("action.reveal_sequences"));
484           menuItem.addActionListener(new ActionListener()
485           {
486             @Override
487             public void actionPerformed(ActionEvent e)
488             {
489               ap.av.showSequence(index);
490               if (ap.overviewPanel != null)
491               {
492                 ap.overviewPanel.updateOverviewImage();
493               }
494             }
495           });
496           add(menuItem);
497         }
498       }
499     }
500     // for the case when no sequences are even visible
501     if (ap.av.hasHiddenRows())
502     {
503       {
504         menuItem = new JMenuItem(
505                 MessageManager.getString("action.reveal_all"));
506         menuItem.addActionListener(new ActionListener()
507         {
508           @Override
509           public void actionPerformed(ActionEvent e)
510           {
511             ap.av.showAllHiddenSeqs();
512             if (ap.overviewPanel != null)
513             {
514               ap.overviewPanel.updateOverviewImage();
515             }
516           }
517         });
518
519         add(menuItem);
520       }
521
522     }
523
524     SequenceGroup sg = ap.av.getSelectionGroup();
525     boolean isDefinedGroup = (sg != null) ? ap.av.getAlignment()
526             .getGroups().contains(sg) : false;
527
528     if (sg != null && sg.getSize() > 0)
529     {
530       groupName.setText(MessageManager.formatMessage("label.name_param",
531               new String[]
532               { sg.getName() }));
533       groupName.setText(MessageManager
534               .getString("label.edit_name_and_description_current_group"));
535
536       if (sg.cs instanceof ZappoColourScheme)
537       {
538         zappoColour.setSelected(true);
539       }
540       else if (sg.cs instanceof TaylorColourScheme)
541       {
542         taylorColour.setSelected(true);
543       }
544       else if (sg.cs instanceof PIDColourScheme)
545       {
546         PIDColour.setSelected(true);
547       }
548       else if (sg.cs instanceof Blosum62ColourScheme)
549       {
550         BLOSUM62Colour.setSelected(true);
551       }
552       else if (sg.cs instanceof UserColourScheme)
553       {
554         userDefinedColour.setSelected(true);
555       }
556       else if (sg.cs instanceof HydrophobicColourScheme)
557       {
558         hydrophobicityColour.setSelected(true);
559       }
560       else if (sg.cs instanceof HelixColourScheme)
561       {
562         helixColour.setSelected(true);
563       }
564       else if (sg.cs instanceof StrandColourScheme)
565       {
566         strandColour.setSelected(true);
567       }
568       else if (sg.cs instanceof TurnColourScheme)
569       {
570         turnColour.setSelected(true);
571       }
572       else if (sg.cs instanceof BuriedColourScheme)
573       {
574         buriedColour.setSelected(true);
575       }
576       else if (sg.cs instanceof ClustalxColourScheme)
577       {
578         clustalColour.setSelected(true);
579       }
580       else if (sg.cs instanceof PurinePyrimidineColourScheme)
581       {
582         purinePyrimidineColour.setSelected(true);
583       }
584
585       /*
586        * else if (sg.cs instanceof CovariationColourScheme) {
587        * covariationColour.setSelected(true); }
588        */
589       else
590       {
591         noColourmenuItem.setSelected(true);
592       }
593
594       if (sg.cs != null && sg.cs.conservationApplied())
595       {
596         conservationMenuItem.setSelected(true);
597       }
598       displayNonconserved.setSelected(sg.getShowNonconserved());
599       showText.setSelected(sg.getDisplayText());
600       showColourText.setSelected(sg.getColourText());
601       showBoxes.setSelected(sg.getDisplayBoxes());
602       // add any groupURLs to the groupURL submenu and make it visible
603       if (groupLinks != null && groupLinks.size() > 0)
604       {
605         buildGroupURLMenu(sg, groupLinks);
606       }
607       // Add a 'show all structures' for the current selection
608       Hashtable<String, PDBEntry> pdbe = new Hashtable<String, PDBEntry>(), reppdb = new Hashtable<String, PDBEntry>();
609       SequenceI sqass = null;
610       for (SequenceI sq : ap.av.getSequenceSelection())
611       {
612         Vector<PDBEntry> pes = sq.getDatasetSequence().getPDBId();
613         if (pes != null && pes.size() > 0)
614         {
615           reppdb.put(pes.get(0).getId(), pes.get(0));
616           for (PDBEntry pe : pes)
617           {
618             pdbe.put(pe.getId(), pe);
619             if (sqass == null)
620             {
621               sqass = sq;
622             }
623           }
624         }
625       }
626       if (pdbe.size() > 0)
627       {
628         final PDBEntry[] pe = pdbe.values().toArray(
629                 new PDBEntry[pdbe.size()]), pr = reppdb.values().toArray(
630                 new PDBEntry[reppdb.size()]);
631         final JMenuItem gpdbview, rpdbview;
632         if (pdbe.size() == 1)
633         {
634           structureMenu.add(gpdbview = new JMenuItem(MessageManager
635                   .formatMessage("label.view_structure_for", new String[]
636                   { sqass.getDisplayId(false) })));
637         }
638         else
639         {
640           structureMenu.add(gpdbview = new JMenuItem(MessageManager
641                   .formatMessage("label.view_all_structures", new String[]
642                   { new Integer(pdbe.size()).toString() })));
643         }
644         gpdbview.setToolTipText(MessageManager
645                 .getString("label.open_new_jmol_view_with_all_structures_associated_current_selection_superimpose_using_alignment"));
646         gpdbview.addActionListener(new ActionListener()
647         {
648
649           @Override
650           public void actionPerformed(ActionEvent e)
651           {
652             new StructureViewer(ap.getStructureSelectionManager())
653                     .viewStructures(ap, pe, ap.av.collateForPDB(pe));
654           }
655         });
656         if (reppdb.size() > 1 && reppdb.size() < pdbe.size())
657         {
658           structureMenu.add(rpdbview = new JMenuItem(MessageManager
659                   .formatMessage(
660                           "label.view_all_representative_structures",
661                           new String[]
662                           { new Integer(reppdb.size()).toString() })));
663           rpdbview.setToolTipText(MessageManager
664                   .getString("label.open_new_jmol_view_with_all_representative_structures_associated_current_selection_superimpose_using_alignment"));
665           rpdbview.addActionListener(new ActionListener()
666           {
667
668             @Override
669             public void actionPerformed(ActionEvent e)
670             {
671               new StructureViewer(ap.getStructureSelectionManager())
672                       .viewStructures(ap, pr, ap.av.collateForPDB(pr));
673             }
674           });
675         }
676       }
677     }
678     else
679     {
680       groupMenu.setVisible(false);
681       editMenu.setVisible(false);
682     }
683
684     if (!isDefinedGroup)
685     {
686       createGroupMenuItem.setVisible(true);
687       unGroupMenuItem.setVisible(false);
688       jMenu1.setText(MessageManager.getString("action.edit_new_group"));
689     }
690     else
691     {
692       createGroupMenuItem.setVisible(false);
693       unGroupMenuItem.setVisible(true);
694       jMenu1.setText(MessageManager.getString("action.edit_group"));
695     }
696
697     if (seq == null)
698     {
699       sequenceMenu.setVisible(false);
700       structureMenu.setVisible(false);
701     }
702
703     if (links != null && links.size() > 0)
704     {
705
706       JMenu linkMenu = new JMenu(MessageManager.getString("action.link"));
707       Vector linkset = new Vector();
708       for (int i = 0; i < links.size(); i++)
709       {
710         String link = links.elementAt(i).toString();
711         UrlLink urlLink = null;
712         try
713         {
714           urlLink = new UrlLink(link);
715         } catch (Exception foo)
716         {
717           jalview.bin.Cache.log.error("Exception for URLLink '" + link
718                   + "'", foo);
719           continue;
720         }
721         ;
722         if (!urlLink.isValid())
723         {
724           jalview.bin.Cache.log.error(urlLink.getInvalidMessage());
725           continue;
726         }
727         final String label = urlLink.getLabel();
728         if (seq != null && urlLink.isDynamic())
729         {
730
731           // collect matching db-refs
732           DBRefEntry[] dbr = jalview.util.DBRefUtils.selectRefs(
733                   seq.getDBRef(), new String[]
734                   { urlLink.getTarget() });
735           // collect id string too
736           String id = seq.getName();
737           String descr = seq.getDescription();
738           if (descr != null && descr.length() < 1)
739           {
740             descr = null;
741           }
742
743           if (dbr != null)
744           {
745             for (int r = 0; r < dbr.length; r++)
746             {
747               if (id != null && dbr[r].getAccessionId().equals(id))
748               {
749                 // suppress duplicate link creation for the bare sequence ID
750                 // string with this link
751                 id = null;
752               }
753               // create Bare ID link for this RUL
754               String[] urls = urlLink.makeUrls(dbr[r].getAccessionId(),
755                       true);
756               if (urls != null)
757               {
758                 for (int u = 0; u < urls.length; u += 2)
759                 {
760                   if (!linkset.contains(urls[u] + "|" + urls[u + 1]))
761                   {
762                     linkset.addElement(urls[u] + "|" + urls[u + 1]);
763                     addshowLink(linkMenu, label + "|" + urls[u],
764                             urls[u + 1]);
765                   }
766                 }
767               }
768             }
769           }
770           if (id != null)
771           {
772             // create Bare ID link for this RUL
773             String[] urls = urlLink.makeUrls(id, true);
774             if (urls != null)
775             {
776               for (int u = 0; u < urls.length; u += 2)
777               {
778                 if (!linkset.contains(urls[u] + "|" + urls[u + 1]))
779                 {
780                   linkset.addElement(urls[u] + "|" + urls[u + 1]);
781                   addshowLink(linkMenu, label, urls[u + 1]);
782                 }
783               }
784             }
785           }
786           // Create urls from description but only for URL links which are regex
787           // links
788           if (descr != null && urlLink.getRegexReplace() != null)
789           {
790             // create link for this URL from description where regex matches
791             String[] urls = urlLink.makeUrls(descr, true);
792             if (urls != null)
793             {
794               for (int u = 0; u < urls.length; u += 2)
795               {
796                 if (!linkset.contains(urls[u] + "|" + urls[u + 1]))
797                 {
798                   linkset.addElement(urls[u] + "|" + urls[u + 1]);
799                   addshowLink(linkMenu, label, urls[u + 1]);
800                 }
801               }
802             }
803           }
804         }
805         else
806         {
807           if (!linkset.contains(label + "|" + urlLink.getUrl_prefix()))
808           {
809             linkset.addElement(label + "|" + urlLink.getUrl_prefix());
810             // Add a non-dynamic link
811             addshowLink(linkMenu, label, urlLink.getUrl_prefix());
812           }
813         }
814       }
815       if (sequence != null)
816       {
817         sequenceMenu.add(linkMenu);
818       }
819       else
820       {
821         add(linkMenu);
822       }
823     }
824   }
825
826   /**
827    * Add annotation types to 'Show annotations' and/or 'Hide annotations' menus.
828    * "All" is added first, followed by a separator. Then add any annotation
829    * types associated with the current selection. Separate menus are built for
830    * the selected sequence group (if any), and the selected sequence.
831    * <p>
832    * Some annotation rows are always rendered together - these can be identified
833    * by a common graphGroup property > -1. Only one of each group will be marked
834    * as visible (to avoid duplication of the display). For such groups we add a
835    * composite type name, e.g.
836    * <p>
837    * IUPredWS (Long), IUPredWS (Short)
838    * 
839    * @param seq
840    */
841   protected void buildAnnotationTypesMenus(JMenu showMenu, JMenu hideMenu,
842           List<SequenceI> forSequences)
843   {
844     showMenu.removeAll();
845     hideMenu.removeAll();
846
847     final List<String> all = Arrays.asList(ALL_ANNOTATIONS);
848     addAnnotationTypeToShowHide(showMenu, forSequences, "", all, true, true);
849     addAnnotationTypeToShowHide(hideMenu, forSequences, "", all, true,
850             false);
851     showMenu.addSeparator();
852     hideMenu.addSeparator();
853
854     final AlignmentAnnotation[] annotations = ap.getAlignment()
855             .getAlignmentAnnotation();
856
857     /*
858      * Find shown/hidden annotations types, distinguished by source (calcId),
859      * and grouped by graphGroup. Using LinkedHashMap means we will retrieve in
860      * the insertion order, which is the order of the annotations on the
861      * alignment.
862      */
863     Map<String, List<List<String>>> shownTypes = new LinkedHashMap<String, List<List<String>>>();
864     Map<String, List<List<String>>> hiddenTypes = new LinkedHashMap<String, List<List<String>>>();
865     AlignmentAnnotationUtils.getShownHiddenTypes(shownTypes,
866             hiddenTypes,
867             AlignmentAnnotationUtils.asList(annotations),
868             forSequences);
869
870     for (String calcId : hiddenTypes.keySet())
871     {
872       for (List<String> type : hiddenTypes.get(calcId))
873       {
874         addAnnotationTypeToShowHide(showMenu, forSequences,
875                 calcId, type, false, true);
876       }
877     }
878     // grey out 'show annotations' if none are hidden
879     showMenu.setEnabled(!hiddenTypes.isEmpty());
880
881     for (String calcId : shownTypes.keySet())
882     {
883       for (List<String> type : shownTypes.get(calcId))
884       {
885         addAnnotationTypeToShowHide(hideMenu, forSequences,
886                 calcId, type, false, false);
887       }
888     }
889     // grey out 'hide annotations' if none are shown
890     hideMenu.setEnabled(!shownTypes.isEmpty());
891   }
892
893   /**
894    * Returns a list of sequences - either the current selection group (if there
895    * is one), else the specified single sequence.
896    * 
897    * @param seq
898    * @return
899    */
900   protected List<SequenceI> getSequenceScope(SequenceI seq)
901   {
902     List<SequenceI> forSequences = null;
903     final SequenceGroup selectionGroup = ap.av.getSelectionGroup();
904     if (selectionGroup != null && selectionGroup.getSize() > 0)
905     {
906       forSequences = selectionGroup.getSequences();
907     }
908     else
909     {
910       forSequences = seq == null ? Collections.<SequenceI> emptyList()
911               : Arrays.asList(seq);
912     }
913     return forSequences;
914   }
915
916   /**
917    * Add one annotation type to the 'Show Annotations' or 'Hide Annotations'
918    * menus.
919    * 
920    * @param showOrHideMenu
921    *          the menu to add to
922    * @param forSequences
923    *          the sequences whose annotations may be shown or hidden
924    * @param calcId
925    * @param types
926    *          the label to add
927    * @param allTypes
928    *          if true this is a special label meaning 'All'
929    * @param actionIsShow
930    *          if true, the select menu item action is to show the annotation
931    *          type, else hide
932    */
933   protected void addAnnotationTypeToShowHide(JMenu showOrHideMenu,
934           final List<SequenceI> forSequences, String calcId,
935           final List<String> types, final boolean allTypes,
936           final boolean actionIsShow)
937   {
938     String label = types.toString(); // [a, b, c]
939     label = label.substring(1, label.length() - 1);
940     final JMenuItem item = new JMenuItem(label);
941     item.setToolTipText(calcId);
942     item.addActionListener(new java.awt.event.ActionListener()
943     {
944       @Override
945       public void actionPerformed(ActionEvent e)
946       {
947         showHideAnnotation_actionPerformed(types, forSequences, allTypes,
948                 actionIsShow);
949       }
950     });
951     showOrHideMenu.add(item);
952   }
953
954   /**
955    * Action on selecting a list of annotation type (or the 'all types' values)
956    * to show or hide for the specified sequences.
957    * 
958    * @param types
959    * @param forSequences
960    * @param anyType
961    * @param doShow
962    */
963   protected void showHideAnnotation_actionPerformed(
964           Collection<String> types, List<SequenceI> forSequences,
965           boolean anyType, boolean doShow)
966   {
967     for (AlignmentAnnotation aa : ap.getAlignment()
968             .getAlignmentAnnotation())
969     {
970       if (anyType || types.contains(aa.label))
971       {
972         if ((aa.sequenceRef != null)
973                 && forSequences.contains(aa.sequenceRef))
974         {
975           aa.visible = doShow;
976         }
977       }
978     }
979     refresh();
980   }
981
982   private void buildGroupURLMenu(SequenceGroup sg, Vector groupLinks)
983   {
984
985     // TODO: usability: thread off the generation of group url content so root
986     // menu appears asap
987     // sequence only URLs
988     // ID/regex match URLs
989     groupLinksMenu = new JMenu(
990             MessageManager.getString("action.group_link"));
991     JMenu[] linkMenus = new JMenu[]
992     { null, new JMenu(MessageManager.getString("action.ids")),
993         new JMenu(MessageManager.getString("action.sequences")),
994         new JMenu(MessageManager.getString("action.ids_sequences")) }; // three
995                                                                        // types
996                                                                        // of url
997                                                                        // that
998                                                                        // might
999                                                                        // be
1000     // created.
1001     SequenceI[] seqs = ap.av.getSelectionAsNewSequence();
1002     String[][] idandseqs = GroupUrlLink.formStrings(seqs);
1003     Hashtable commonDbrefs = new Hashtable();
1004     for (int sq = 0; sq < seqs.length; sq++)
1005     {
1006
1007       int start = seqs[sq].findPosition(sg.getStartRes()), end = seqs[sq]
1008               .findPosition(sg.getEndRes());
1009       // just collect ids from dataset sequence
1010       // TODO: check if IDs collected from selecton group intersects with the
1011       // current selection, too
1012       SequenceI sqi = seqs[sq];
1013       while (sqi.getDatasetSequence() != null)
1014       {
1015         sqi = sqi.getDatasetSequence();
1016       }
1017       DBRefEntry[] dbr = sqi.getDBRef();
1018       if (dbr != null && dbr.length > 0)
1019       {
1020         for (int d = 0; d < dbr.length; d++)
1021         {
1022           String src = dbr[d].getSource(); // jalview.util.DBRefUtils.getCanonicalName(dbr[d].getSource()).toUpperCase();
1023           Object[] sarray = (Object[]) commonDbrefs.get(src);
1024           if (sarray == null)
1025           {
1026             sarray = new Object[2];
1027             sarray[0] = new int[]
1028             { 0 };
1029             sarray[1] = new String[seqs.length];
1030
1031             commonDbrefs.put(src, sarray);
1032           }
1033
1034           if (((String[]) sarray[1])[sq] == null)
1035           {
1036             if (!dbr[d].hasMap()
1037                     || (dbr[d].getMap().locateMappedRange(start, end) != null))
1038             {
1039               ((String[]) sarray[1])[sq] = dbr[d].getAccessionId();
1040               ((int[]) sarray[0])[0]++;
1041             }
1042           }
1043         }
1044       }
1045     }
1046     // now create group links for all distinct ID/sequence sets.
1047     boolean addMenu = false; // indicates if there are any group links to give
1048                              // to user
1049     for (int i = 0; i < groupLinks.size(); i++)
1050     {
1051       String link = groupLinks.elementAt(i).toString();
1052       GroupUrlLink urlLink = null;
1053       try
1054       {
1055         urlLink = new GroupUrlLink(link);
1056       } catch (Exception foo)
1057       {
1058         jalview.bin.Cache.log.error("Exception for GroupURLLink '" + link
1059                 + "'", foo);
1060         continue;
1061       }
1062       ;
1063       if (!urlLink.isValid())
1064       {
1065         jalview.bin.Cache.log.error(urlLink.getInvalidMessage());
1066         continue;
1067       }
1068       final String label = urlLink.getLabel();
1069       boolean usingNames = false;
1070       // Now see which parts of the group apply for this URL
1071       String ltarget = urlLink.getTarget(); // jalview.util.DBRefUtils.getCanonicalName(urlLink.getTarget());
1072       Object[] idset = (Object[]) commonDbrefs.get(ltarget.toUpperCase());
1073       String[] seqstr, ids; // input to makeUrl
1074       if (idset != null)
1075       {
1076         int numinput = ((int[]) idset[0])[0];
1077         String[] allids = ((String[]) idset[1]);
1078         seqstr = new String[numinput];
1079         ids = new String[numinput];
1080         for (int sq = 0, idcount = 0; sq < seqs.length; sq++)
1081         {
1082           if (allids[sq] != null)
1083           {
1084             ids[idcount] = allids[sq];
1085             seqstr[idcount++] = idandseqs[1][sq];
1086           }
1087         }
1088       }
1089       else
1090       {
1091         // just use the id/seq set
1092         seqstr = idandseqs[1];
1093         ids = idandseqs[0];
1094         usingNames = true;
1095       }
1096       // and try and make the groupURL!
1097
1098       Object[] urlset = null;
1099       try
1100       {
1101         urlset = urlLink.makeUrlStubs(ids, seqstr,
1102                 "FromJalview" + System.currentTimeMillis(), false);
1103       } catch (UrlStringTooLongException e)
1104       {
1105       }
1106       if (urlset != null)
1107       {
1108         int type = urlLink.getGroupURLType() & 3;
1109         // System.out.println(urlLink.getGroupURLType()
1110         // +" "+((String[])urlset[3])[0]);
1111         // first two bits ofurlLink type bitfield are sequenceids and sequences
1112         // TODO: FUTURE: ensure the groupURL menu structure can be generalised
1113         addshowLink(linkMenus[type], label
1114                 + (((type & 1) == 1) ? ("("
1115                         + (usingNames ? "Names" : ltarget) + ")") : ""),
1116                 urlLink, urlset);
1117         addMenu = true;
1118       }
1119     }
1120     if (addMenu)
1121     {
1122       groupLinksMenu = new JMenu(
1123               MessageManager.getString("action.group_link"));
1124       for (int m = 0; m < linkMenus.length; m++)
1125       {
1126         if (linkMenus[m] != null
1127                 && linkMenus[m].getMenuComponentCount() > 0)
1128         {
1129           groupLinksMenu.add(linkMenus[m]);
1130         }
1131       }
1132
1133       groupMenu.add(groupLinksMenu);
1134     }
1135   }
1136
1137   /**
1138    * add a show URL menu item to the given linkMenu
1139    * 
1140    * @param linkMenu
1141    * @param label
1142    *          - menu label string
1143    * @param url
1144    *          - url to open
1145    */
1146   private void addshowLink(JMenu linkMenu, String label, final String url)
1147   {
1148     JMenuItem item = new JMenuItem(label);
1149     item.setToolTipText(MessageManager.formatMessage(
1150             "label.open_url_param", new String[]
1151             { url }));
1152     item.addActionListener(new java.awt.event.ActionListener()
1153     {
1154       @Override
1155       public void actionPerformed(ActionEvent e)
1156       {
1157         new Thread(new Runnable()
1158         {
1159
1160           @Override
1161           public void run()
1162           {
1163             showLink(url);
1164           }
1165
1166         }).start();
1167       }
1168     });
1169
1170     linkMenu.add(item);
1171   }
1172
1173   /**
1174    * add a late bound groupURL item to the given linkMenu
1175    * 
1176    * @param linkMenu
1177    * @param label
1178    *          - menu label string
1179    * @param urlgenerator
1180    *          GroupURLLink used to generate URL
1181    * @param urlstub
1182    *          Object array returned from the makeUrlStubs function.
1183    */
1184   private void addshowLink(JMenu linkMenu, String label,
1185           final GroupUrlLink urlgenerator, final Object[] urlstub)
1186   {
1187     JMenuItem item = new JMenuItem(label);
1188     item.setToolTipText(MessageManager.formatMessage(
1189             "label.open_url_seqs_param",
1190             new Object[]
1191             { urlgenerator.getUrl_prefix(),
1192                 urlgenerator.getNumberInvolved(urlstub) }));
1193     // TODO: put in info about what is being sent.
1194     item.addActionListener(new java.awt.event.ActionListener()
1195     {
1196       @Override
1197       public void actionPerformed(ActionEvent e)
1198       {
1199         new Thread(new Runnable()
1200         {
1201
1202           @Override
1203           public void run()
1204           {
1205             try
1206             {
1207               showLink(urlgenerator.constructFrom(urlstub));
1208             } catch (UrlStringTooLongException e)
1209             {
1210             }
1211           }
1212
1213         }).start();
1214       }
1215     });
1216
1217     linkMenu.add(item);
1218   }
1219
1220   /**
1221    * DOCUMENT ME!
1222    * 
1223    * @throws Exception
1224    *           DOCUMENT ME!
1225    */
1226   private void jbInit() throws Exception
1227   {
1228     groupMenu.setText(MessageManager.getString("label.group"));
1229     groupMenu.setText(MessageManager.getString("label.selection"));
1230     groupName.setText(MessageManager.getString("label.name"));
1231     groupName.addActionListener(new java.awt.event.ActionListener()
1232     {
1233       @Override
1234       public void actionPerformed(ActionEvent e)
1235       {
1236         groupName_actionPerformed();
1237       }
1238     });
1239     sequenceMenu.setText(MessageManager.getString("label.sequence"));
1240     sequenceName.setText(MessageManager
1241             .getString("label.edit_name_description"));
1242     sequenceName.addActionListener(new java.awt.event.ActionListener()
1243     {
1244       @Override
1245       public void actionPerformed(ActionEvent e)
1246       {
1247         sequenceName_actionPerformed();
1248       }
1249     });
1250     chooseAnnotations.setText(MessageManager
1251             .getString("label.choose_annotations") + "...");
1252     chooseAnnotations.addActionListener(new java.awt.event.ActionListener()
1253     {
1254       @Override
1255       public void actionPerformed(ActionEvent e)
1256       {
1257         chooseAnnotations_actionPerformed(e);
1258       }
1259     });
1260     sequenceDetails.setText(MessageManager
1261             .getString("label.sequence_details") + "...");
1262     sequenceDetails.addActionListener(new java.awt.event.ActionListener()
1263     {
1264       @Override
1265       public void actionPerformed(ActionEvent e)
1266       {
1267         sequenceDetails_actionPerformed();
1268       }
1269     });
1270     sequenceSelDetails.setText(MessageManager
1271             .getString("label.sequence_details") + "...");
1272     sequenceSelDetails
1273             .addActionListener(new java.awt.event.ActionListener()
1274             {
1275               @Override
1276               public void actionPerformed(ActionEvent e)
1277               {
1278                 sequenceSelectionDetails_actionPerformed();
1279               }
1280             });
1281     PIDColour.setFocusPainted(false);
1282     unGroupMenuItem
1283             .setText(MessageManager.getString("action.remove_group"));
1284     unGroupMenuItem.addActionListener(new java.awt.event.ActionListener()
1285     {
1286       @Override
1287       public void actionPerformed(ActionEvent e)
1288       {
1289         unGroupMenuItem_actionPerformed();
1290       }
1291     });
1292     createGroupMenuItem.setText(MessageManager
1293             .getString("action.create_group"));
1294     createGroupMenuItem
1295             .addActionListener(new java.awt.event.ActionListener()
1296             {
1297               @Override
1298               public void actionPerformed(ActionEvent e)
1299               {
1300                 createGroupMenuItem_actionPerformed();
1301               }
1302             });
1303
1304     outline.setText(MessageManager.getString("action.border_colour"));
1305     outline.addActionListener(new java.awt.event.ActionListener()
1306     {
1307       @Override
1308       public void actionPerformed(ActionEvent e)
1309       {
1310         outline_actionPerformed();
1311       }
1312     });
1313     nucleotideMenuItem
1314             .setText(MessageManager.getString("label.nucleotide"));
1315     nucleotideMenuItem.addActionListener(new ActionListener()
1316     {
1317       @Override
1318       public void actionPerformed(ActionEvent e)
1319       {
1320         nucleotideMenuItem_actionPerformed();
1321       }
1322     });
1323     colourMenu.setText(MessageManager.getString("label.group_colour"));
1324     showBoxes.setText(MessageManager.getString("action.boxes"));
1325     showBoxes.setState(true);
1326     showBoxes.addActionListener(new ActionListener()
1327     {
1328       @Override
1329       public void actionPerformed(ActionEvent e)
1330       {
1331         showBoxes_actionPerformed();
1332       }
1333     });
1334     showText.setText(MessageManager.getString("action.text"));
1335     showText.setState(true);
1336     showText.addActionListener(new ActionListener()
1337     {
1338       @Override
1339       public void actionPerformed(ActionEvent e)
1340       {
1341         showText_actionPerformed();
1342       }
1343     });
1344     showColourText.setText(MessageManager.getString("label.colour_text"));
1345     showColourText.addActionListener(new ActionListener()
1346     {
1347       @Override
1348       public void actionPerformed(ActionEvent e)
1349       {
1350         showColourText_actionPerformed();
1351       }
1352     });
1353     displayNonconserved.setText(MessageManager
1354             .getString("label.show_non_conversed"));
1355     displayNonconserved.setState(true);
1356     displayNonconserved.addActionListener(new ActionListener()
1357     {
1358       @Override
1359       public void actionPerformed(ActionEvent e)
1360       {
1361         showNonconserved_actionPerformed();
1362       }
1363     });
1364     editMenu.setText(MessageManager.getString("action.edit"));
1365     cut.setText(MessageManager.getString("action.cut"));
1366     cut.addActionListener(new ActionListener()
1367     {
1368       @Override
1369       public void actionPerformed(ActionEvent e)
1370       {
1371         cut_actionPerformed();
1372       }
1373     });
1374     upperCase.setText(MessageManager.getString("label.to_upper_case"));
1375     upperCase.addActionListener(new ActionListener()
1376     {
1377       @Override
1378       public void actionPerformed(ActionEvent e)
1379       {
1380         changeCase(e);
1381       }
1382     });
1383     copy.setText(MessageManager.getString("action.copy"));
1384     copy.addActionListener(new ActionListener()
1385     {
1386       @Override
1387       public void actionPerformed(ActionEvent e)
1388       {
1389         copy_actionPerformed();
1390       }
1391     });
1392     lowerCase.setText(MessageManager.getString("label.to_lower_case"));
1393     lowerCase.addActionListener(new ActionListener()
1394     {
1395       @Override
1396       public void actionPerformed(ActionEvent e)
1397       {
1398         changeCase(e);
1399       }
1400     });
1401     toggle.setText(MessageManager.getString("label.toggle_case"));
1402     toggle.addActionListener(new ActionListener()
1403     {
1404       @Override
1405       public void actionPerformed(ActionEvent e)
1406       {
1407         changeCase(e);
1408       }
1409     });
1410     pdbMenu.setText(MessageManager
1411             .getString("label.associate_structure_with_sequence"));
1412     pdbFromFile.setText(MessageManager.getString("label.from_file"));
1413     pdbFromFile.addActionListener(new ActionListener()
1414     {
1415       @Override
1416       public void actionPerformed(ActionEvent e)
1417       {
1418         pdbFromFile_actionPerformed();
1419       }
1420     });
1421     // RNAFold.setText("From RNA Fold with predict2D");
1422     // RNAFold.addActionListener(new ActionListener()
1423     // {
1424     // public void actionPerformed(ActionEvent e)
1425     // {
1426     // try {
1427     // RNAFold_actionPerformed();
1428     // } catch (Exception e1) {
1429     // // TODO Auto-generated catch block
1430     // e1.printStackTrace();
1431     // }
1432     // }
1433     // });
1434     // ContraFold.setText("From Contra Fold with predict2D");
1435     // ContraFold.addActionListener(new ActionListener()
1436     // {
1437     // public void actionPerformed(ActionEvent e)
1438     // {
1439     // try {
1440     // ContraFold_actionPerformed();
1441     // } catch (Exception e1) {
1442     // // TODO Auto-generated catch block
1443     // e1.printStackTrace();
1444     // }
1445     // }
1446     // });
1447     enterPDB.setText(MessageManager.getString("label.enter_pdb_id"));
1448     enterPDB.addActionListener(new ActionListener()
1449     {
1450       @Override
1451       public void actionPerformed(ActionEvent e)
1452       {
1453         enterPDB_actionPerformed();
1454       }
1455     });
1456     discoverPDB.setText(MessageManager.getString("label.discover_pdb_ids"));
1457     discoverPDB.addActionListener(new ActionListener()
1458     {
1459       @Override
1460       public void actionPerformed(ActionEvent e)
1461       {
1462         discoverPDB_actionPerformed();
1463       }
1464     });
1465     outputMenu.setText(MessageManager.getString("label.out_to_textbox")
1466             + "...");
1467     seqShowAnnotationsMenu.setText(MessageManager
1468             .getString("label.show_annotations"));
1469     seqHideAnnotationsMenu.setText(MessageManager
1470             .getString("label.hide_annotations"));
1471     groupShowAnnotationsMenu.setText(MessageManager
1472             .getString("label.show_annotations"));
1473     groupHideAnnotationsMenu.setText(MessageManager
1474             .getString("label.hide_annotations"));
1475     sequenceFeature.setText(MessageManager
1476             .getString("label.create_sequence_feature"));
1477     sequenceFeature.addActionListener(new ActionListener()
1478     {
1479       @Override
1480       public void actionPerformed(ActionEvent e)
1481       {
1482         sequenceFeature_actionPerformed();
1483       }
1484     });
1485     textColour.setText(MessageManager.getString("label.text_colour"));
1486     textColour.addActionListener(new ActionListener()
1487     {
1488       @Override
1489       public void actionPerformed(ActionEvent e)
1490       {
1491         textColour_actionPerformed();
1492       }
1493     });
1494     jMenu1.setText(MessageManager.getString("label.group"));
1495     structureMenu.setText(MessageManager.getString("label.structure"));
1496     viewStructureMenu.setText(MessageManager
1497             .getString("label.view_structure"));
1498     // colStructureMenu.setText("Colour By Structure");
1499     editSequence.setText(MessageManager.getString("label.edit_sequence")
1500             + "...");
1501     editSequence.addActionListener(new ActionListener()
1502     {
1503       @Override
1504       public void actionPerformed(ActionEvent actionEvent)
1505       {
1506         editSequence_actionPerformed(actionEvent);
1507       }
1508     });
1509
1510     /*
1511      * annotationMenuItem.setText("By Annotation");
1512      * annotationMenuItem.addActionListener(new ActionListener() { public void
1513      * actionPerformed(ActionEvent actionEvent) {
1514      * annotationMenuItem_actionPerformed(actionEvent); } });
1515      */
1516     groupMenu.add(sequenceSelDetails);
1517     add(groupMenu);
1518     add(sequenceMenu);
1519     this.add(structureMenu);
1520     // annotations configuration panel suppressed for now
1521     // groupMenu.add(chooseAnnotations);
1522
1523     /*
1524      * Add show/hide annotations to the Sequence menu, and to the Selection menu
1525      * (if a selection group is in force).
1526      */
1527     sequenceMenu.add(seqShowAnnotationsMenu);
1528     sequenceMenu.add(seqHideAnnotationsMenu);
1529     sequenceMenu.add(seqAddReferenceAnnotations);
1530     groupMenu.add(groupShowAnnotationsMenu);
1531     groupMenu.add(groupHideAnnotationsMenu);
1532     groupMenu.add(groupAddReferenceAnnotations);
1533     groupMenu.add(editMenu);
1534     groupMenu.add(outputMenu);
1535     groupMenu.add(sequenceFeature);
1536     groupMenu.add(createGroupMenuItem);
1537     groupMenu.add(unGroupMenuItem);
1538     groupMenu.add(jMenu1);
1539     sequenceMenu.add(sequenceName);
1540     sequenceMenu.add(sequenceDetails);
1541     colourMenu.add(textColour);
1542     colourMenu.add(noColourmenuItem);
1543     colourMenu.add(clustalColour);
1544     colourMenu.add(BLOSUM62Colour);
1545     colourMenu.add(PIDColour);
1546     colourMenu.add(zappoColour);
1547     colourMenu.add(taylorColour);
1548     colourMenu.add(hydrophobicityColour);
1549     colourMenu.add(helixColour);
1550     colourMenu.add(strandColour);
1551     colourMenu.add(turnColour);
1552     colourMenu.add(buriedColour);
1553     colourMenu.add(nucleotideMenuItem);
1554     if (ap.getAlignment().isNucleotide())
1555     {
1556       // JBPNote - commented since the colourscheme isn't functional
1557       // colourMenu.add(RNAInteractionColour);
1558       colourMenu.add(purinePyrimidineColour);
1559     }
1560     // colourMenu.add(covariationColour);
1561     colourMenu.add(userDefinedColour);
1562
1563     if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
1564     {
1565       java.util.Enumeration userColours = jalview.gui.UserDefinedColours
1566               .getUserColourSchemes().keys();
1567
1568       while (userColours.hasMoreElements())
1569       {
1570         JMenuItem item = new JMenuItem(userColours.nextElement().toString());
1571         item.addActionListener(new ActionListener()
1572         {
1573           @Override
1574           public void actionPerformed(ActionEvent evt)
1575           {
1576             userDefinedColour_actionPerformed(evt);
1577           }
1578         });
1579         colourMenu.add(item);
1580       }
1581     }
1582
1583     colourMenu.addSeparator();
1584     colourMenu.add(abovePIDColour);
1585     colourMenu.add(conservationMenuItem);
1586     // colourMenu.add(annotationMenuItem);
1587     editMenu.add(copy);
1588     editMenu.add(cut);
1589     editMenu.add(editSequence);
1590     editMenu.add(upperCase);
1591     editMenu.add(lowerCase);
1592     editMenu.add(toggle);
1593     pdbMenu.add(pdbFromFile);
1594     // JBPNote: These shouldn't be added here - should appear in a generic
1595     // 'apply web service to this sequence menu'
1596     // pdbMenu.add(RNAFold);
1597     // pdbMenu.add(ContraFold);
1598     pdbMenu.add(enterPDB);
1599     pdbMenu.add(discoverPDB);
1600     jMenu1.add(groupName);
1601     jMenu1.add(colourMenu);
1602     jMenu1.add(showBoxes);
1603     jMenu1.add(showText);
1604     jMenu1.add(showColourText);
1605     jMenu1.add(outline);
1606     jMenu1.add(displayNonconserved);
1607     structureMenu.add(pdbMenu);
1608     structureMenu.add(viewStructureMenu);
1609     // structureMenu.add(colStructureMenu);
1610     noColourmenuItem.setText(MessageManager.getString("label.none"));
1611     noColourmenuItem.addActionListener(new java.awt.event.ActionListener()
1612     {
1613       @Override
1614       public void actionPerformed(ActionEvent e)
1615       {
1616         noColourmenuItem_actionPerformed();
1617       }
1618     });
1619
1620     clustalColour.setText(MessageManager
1621             .getString("label.clustalx_colours"));
1622     clustalColour.addActionListener(new java.awt.event.ActionListener()
1623     {
1624       @Override
1625       public void actionPerformed(ActionEvent e)
1626       {
1627         clustalColour_actionPerformed();
1628       }
1629     });
1630     zappoColour.setText(MessageManager.getString("label.zappo"));
1631     zappoColour.addActionListener(new java.awt.event.ActionListener()
1632     {
1633       @Override
1634       public void actionPerformed(ActionEvent e)
1635       {
1636         zappoColour_actionPerformed();
1637       }
1638     });
1639     taylorColour.setText(MessageManager.getString("label.taylor"));
1640     taylorColour.addActionListener(new java.awt.event.ActionListener()
1641     {
1642       @Override
1643       public void actionPerformed(ActionEvent e)
1644       {
1645         taylorColour_actionPerformed();
1646       }
1647     });
1648     hydrophobicityColour.setText(MessageManager
1649             .getString("label.hydrophobicity"));
1650     hydrophobicityColour
1651             .addActionListener(new java.awt.event.ActionListener()
1652             {
1653               @Override
1654               public void actionPerformed(ActionEvent e)
1655               {
1656                 hydrophobicityColour_actionPerformed();
1657               }
1658             });
1659     helixColour.setText(MessageManager.getString("label.helix_propensity"));
1660     helixColour.addActionListener(new java.awt.event.ActionListener()
1661     {
1662       @Override
1663       public void actionPerformed(ActionEvent e)
1664       {
1665         helixColour_actionPerformed();
1666       }
1667     });
1668     strandColour.setText(MessageManager
1669             .getString("label.strand_propensity"));
1670     strandColour.addActionListener(new java.awt.event.ActionListener()
1671     {
1672       @Override
1673       public void actionPerformed(ActionEvent e)
1674       {
1675         strandColour_actionPerformed();
1676       }
1677     });
1678     turnColour.setText(MessageManager.getString("label.turn_propensity"));
1679     turnColour.addActionListener(new java.awt.event.ActionListener()
1680     {
1681       @Override
1682       public void actionPerformed(ActionEvent e)
1683       {
1684         turnColour_actionPerformed();
1685       }
1686     });
1687     buriedColour.setText(MessageManager.getString("label.buried_index"));
1688     buriedColour.addActionListener(new java.awt.event.ActionListener()
1689     {
1690       @Override
1691       public void actionPerformed(ActionEvent e)
1692       {
1693         buriedColour_actionPerformed();
1694       }
1695     });
1696     abovePIDColour.setText(MessageManager
1697             .getString("label.above_identity_percentage"));
1698     abovePIDColour.addActionListener(new java.awt.event.ActionListener()
1699     {
1700       @Override
1701       public void actionPerformed(ActionEvent e)
1702       {
1703         abovePIDColour_actionPerformed();
1704       }
1705     });
1706     userDefinedColour.setText(MessageManager
1707             .getString("action.user_defined"));
1708     userDefinedColour.addActionListener(new java.awt.event.ActionListener()
1709     {
1710       @Override
1711       public void actionPerformed(ActionEvent e)
1712       {
1713         userDefinedColour_actionPerformed(e);
1714       }
1715     });
1716     PIDColour
1717             .setText(MessageManager.getString("label.percentage_identity"));
1718     PIDColour.addActionListener(new java.awt.event.ActionListener()
1719     {
1720       @Override
1721       public void actionPerformed(ActionEvent e)
1722       {
1723         PIDColour_actionPerformed();
1724       }
1725     });
1726     BLOSUM62Colour.setText(MessageManager.getString("label.blosum62"));
1727     BLOSUM62Colour.addActionListener(new java.awt.event.ActionListener()
1728     {
1729       @Override
1730       public void actionPerformed(ActionEvent e)
1731       {
1732         BLOSUM62Colour_actionPerformed();
1733       }
1734     });
1735     purinePyrimidineColour.setText(MessageManager
1736             .getString("label.purine_pyrimidine"));
1737     purinePyrimidineColour
1738             .addActionListener(new java.awt.event.ActionListener()
1739             {
1740               @Override
1741               public void actionPerformed(ActionEvent e)
1742               {
1743                 purinePyrimidineColour_actionPerformed();
1744               }
1745             });
1746
1747     /*
1748      * covariationColour.addActionListener(new java.awt.event.ActionListener() {
1749      * public void actionPerformed(ActionEvent e) {
1750      * covariationColour_actionPerformed(); } });
1751      */
1752
1753     conservationMenuItem.setText(MessageManager
1754             .getString("label.conservation"));
1755     conservationMenuItem
1756             .addActionListener(new java.awt.event.ActionListener()
1757             {
1758               @Override
1759               public void actionPerformed(ActionEvent e)
1760               {
1761                 conservationMenuItem_actionPerformed();
1762               }
1763             });
1764   }
1765
1766   /**
1767    * Check for any annotations on the underlying dataset sequences (for the
1768    * current selection group) which are not on the alignment annotations for the
1769    * sequence. If any are found, enable the option to add them to the alignment.
1770    * The criteria for 'on the alignment' is finding an alignment annotation on
1771    * the sequence, that matches on calcId and label. A tooltip is also
1772    * constructed that displays the source (calcId) and type (label) of the
1773    * annotations that can be added.
1774    * 
1775    * @param menuItem
1776    * @param forSequences
1777    */
1778   protected void configureReferenceAnnotationsMenu(
1779           JMenuItem menuItem, List<SequenceI> forSequences)
1780   {
1781     menuItem.setText(MessageManager
1782             .getString("label.add_reference_annotations"));
1783     menuItem.setEnabled(false);
1784     if (forSequences == null)
1785     {
1786       return;
1787     }
1788
1789     /*
1790      * Temporary store to hold distinct calcId / type pairs for the tooltip.
1791      * Using TreeMap means calcIds are shown in alphabetical order.
1792      */
1793     Map<String, String> tipEntries = new TreeMap<String, String>();
1794     StringBuilder tooltip = new StringBuilder(64);
1795     tooltip.append(MessageManager.getString("label.add_annotations_for"));
1796
1797     /*
1798      * For each sequence selected in the alignment, make a list of any
1799      * annotations on the underlying dataset sequence which are not already on
1800      * the sequence in the alignment.
1801      * 
1802      * Build a map of { alignmentSequence, <List of annotations to add> }
1803      */
1804     final Map<SequenceI, List<AlignmentAnnotation>> candidates = new LinkedHashMap<SequenceI, List<AlignmentAnnotation>>();
1805     for (SequenceI seq : forSequences)
1806     {
1807       SequenceI dataset = seq.getDatasetSequence();
1808       if (dataset == null)
1809       {
1810         continue;
1811       }
1812       AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1813       if (datasetAnnotations == null)
1814       {
1815         continue;
1816       }
1817       final List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1818       for (AlignmentAnnotation dsann : datasetAnnotations)
1819       {
1820         /*
1821          * If the sequence has no annotation that matches this one, then add
1822          * this one to the results list.
1823          */
1824         if (seq.getAlignmentAnnotations(dsann.getCalcId(), dsann.label)
1825                 .isEmpty())
1826         {
1827           result.add(dsann);
1828           tipEntries.put(dsann.getCalcId(), dsann.label);
1829         }
1830       }
1831       /*
1832        * Save any addable annotations for this sequence
1833        */
1834       if (!result.isEmpty())
1835       {
1836         candidates.put(seq, result);
1837       }
1838     }
1839     if (!candidates.isEmpty())
1840     {
1841       /*
1842        * Found annotations that could be added. Enable the menu item, and
1843        * configure its tooltip and action.
1844        */
1845       menuItem.setEnabled(true);
1846       for (String calcId : tipEntries.keySet())
1847       {
1848         tooltip.append("<br/>" + calcId + "/" + tipEntries.get(calcId));
1849       }
1850       String tooltipText = JvSwingUtils.wrapTooltip(true,
1851               tooltip.toString());
1852       menuItem.setToolTipText(tooltipText);
1853
1854       menuItem.addActionListener(new ActionListener()
1855       {
1856         @Override
1857         public void actionPerformed(ActionEvent e)
1858         {
1859           addReferenceAnnotations_actionPerformed(candidates);
1860         }
1861       });
1862     }
1863   }
1864
1865   /**
1866    * Add annotations to the sequences and to the alignment.
1867    * 
1868    * @param candidates
1869    *          a map whose keys are sequences on the alignment, and values a list
1870    *          of annotations to add to each sequence
1871    */
1872   protected void addReferenceAnnotations_actionPerformed(
1873           Map<SequenceI, List<AlignmentAnnotation>> candidates)
1874   {
1875     /*
1876      * Add annotations at the top of the annotation, in the same order as their
1877      * related sequences.
1878      */
1879     for (SequenceI seq : candidates.keySet())
1880     {
1881       for (AlignmentAnnotation ann : candidates.get(seq))
1882       {
1883         AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1884         int startRes = 0;
1885         int endRes = ann.annotations.length;
1886         final SequenceGroup selectionGroup = this.ap.av.getSelectionGroup();
1887         if (selectionGroup != null)
1888         {
1889           startRes = selectionGroup.getStartRes();
1890           endRes = selectionGroup.getEndRes();
1891         }
1892         copyAnn.restrict(startRes, endRes);
1893
1894         // add to the sequence (sets copyAnn.datasetSequence)
1895         seq.addAlignmentAnnotation(copyAnn);
1896         // adjust for gaps
1897         copyAnn.adjustForAlignment();
1898         // add to the alignment and set visible
1899         this.ap.getAlignment().addAnnotation(copyAnn);
1900         copyAnn.visible = true;
1901       }
1902     }
1903     refresh();
1904   }
1905
1906   protected void sequenceSelectionDetails_actionPerformed()
1907   {
1908     createSequenceDetailsReport(ap.av.getSequenceSelection());
1909   }
1910
1911   protected void sequenceDetails_actionPerformed()
1912   {
1913     createSequenceDetailsReport(new SequenceI[]
1914     { sequence });
1915   }
1916
1917   public void createSequenceDetailsReport(SequenceI[] sequences)
1918   {
1919     CutAndPasteHtmlTransfer cap = new CutAndPasteHtmlTransfer();
1920     StringBuffer contents = new StringBuffer();
1921     for (SequenceI seq : sequences)
1922     {
1923       contents.append("<p><h2>"
1924               + MessageManager
1925                       .formatMessage(
1926                               "label.create_sequence_details_report_annotation_for",
1927                               new String[]
1928                               { seq.getDisplayId(true) }) + "</h2></p><p>");
1929       new SequenceAnnotationReport(null)
1930               .createSequenceAnnotationReport(
1931                       contents,
1932                       seq,
1933                       true,
1934                       true,
1935                       false,
1936                       (ap.seqPanel.seqCanvas.fr != null) ? ap.seqPanel.seqCanvas.fr.minmax
1937                               : null);
1938       contents.append("</p>");
1939     }
1940     cap.setText("<html>" + contents.toString() + "</html>");
1941
1942     Desktop.instance.addInternalFrame(cap, MessageManager.formatMessage(
1943             "label.sequece_details_for",
1944             (sequences.length == 1 ? new String[]
1945             { sequences[0].getDisplayId(true) } : new String[]
1946             { MessageManager.getString("label.selection") })), 500, 400);
1947
1948   }
1949
1950   protected void showNonconserved_actionPerformed()
1951   {
1952     getGroup().setShowNonconserved(displayNonconserved.isSelected());
1953     refresh();
1954   }
1955
1956   /**
1957    * call to refresh view after settings change
1958    */
1959   void refresh()
1960   {
1961     ap.updateAnnotation();
1962     ap.paintAlignment(true);
1963
1964     PaintRefresher.Refresh(this, ap.av.getSequenceSetId());
1965   }
1966
1967   /**
1968    * DOCUMENT ME!
1969    * 
1970    * @param e
1971    *          DOCUMENT ME!
1972    */
1973   protected void clustalColour_actionPerformed()
1974   {
1975     SequenceGroup sg = getGroup();
1976     sg.cs = new ClustalxColourScheme(sg, ap.av.getHiddenRepSequences());
1977     refresh();
1978   }
1979
1980   /**
1981    * DOCUMENT ME!
1982    * 
1983    * @param e
1984    *          DOCUMENT ME!
1985    */
1986   protected void zappoColour_actionPerformed()
1987   {
1988     getGroup().cs = new ZappoColourScheme();
1989     refresh();
1990   }
1991
1992   /**
1993    * DOCUMENT ME!
1994    * 
1995    * @param e
1996    *          DOCUMENT ME!
1997    */
1998   protected void taylorColour_actionPerformed()
1999   {
2000     getGroup().cs = new TaylorColourScheme();
2001     refresh();
2002   }
2003
2004   /**
2005    * DOCUMENT ME!
2006    * 
2007    * @param e
2008    *          DOCUMENT ME!
2009    */
2010   protected void hydrophobicityColour_actionPerformed()
2011   {
2012     getGroup().cs = new HydrophobicColourScheme();
2013     refresh();
2014   }
2015
2016   /**
2017    * DOCUMENT ME!
2018    * 
2019    * @param e
2020    *          DOCUMENT ME!
2021    */
2022   protected void helixColour_actionPerformed()
2023   {
2024     getGroup().cs = new HelixColourScheme();
2025     refresh();
2026   }
2027
2028   /**
2029    * DOCUMENT ME!
2030    * 
2031    * @param e
2032    *          DOCUMENT ME!
2033    */
2034   protected void strandColour_actionPerformed()
2035   {
2036     getGroup().cs = new StrandColourScheme();
2037     refresh();
2038   }
2039
2040   /**
2041    * DOCUMENT ME!
2042    * 
2043    * @param e
2044    *          DOCUMENT ME!
2045    */
2046   protected void turnColour_actionPerformed()
2047   {
2048     getGroup().cs = new TurnColourScheme();
2049     refresh();
2050   }
2051
2052   /**
2053    * DOCUMENT ME!
2054    * 
2055    * @param e
2056    *          DOCUMENT ME!
2057    */
2058   protected void buriedColour_actionPerformed()
2059   {
2060     getGroup().cs = new BuriedColourScheme();
2061     refresh();
2062   }
2063
2064   /**
2065    * DOCUMENT ME!
2066    * 
2067    * @param e
2068    *          DOCUMENT ME!
2069    */
2070   public void nucleotideMenuItem_actionPerformed()
2071   {
2072     getGroup().cs = new NucleotideColourScheme();
2073     refresh();
2074   }
2075
2076   protected void purinePyrimidineColour_actionPerformed()
2077   {
2078     getGroup().cs = new PurinePyrimidineColourScheme();
2079     refresh();
2080   }
2081
2082   /*
2083    * protected void covariationColour_actionPerformed() { getGroup().cs = new
2084    * CovariationColourScheme(sequence.getAnnotation()[0]); refresh(); }
2085    */
2086   /**
2087    * DOCUMENT ME!
2088    * 
2089    * @param e
2090    *          DOCUMENT ME!
2091    */
2092   protected void abovePIDColour_actionPerformed()
2093   {
2094     SequenceGroup sg = getGroup();
2095     if (sg.cs == null)
2096     {
2097       return;
2098     }
2099
2100     if (abovePIDColour.isSelected())
2101     {
2102       sg.cs.setConsensus(AAFrequency.calculate(
2103               sg.getSequences(ap.av.getHiddenRepSequences()),
2104               sg.getStartRes(), sg.getEndRes() + 1));
2105
2106       int threshold = SliderPanel.setPIDSliderSource(ap, sg.cs, getGroup()
2107               .getName());
2108
2109       sg.cs.setThreshold(threshold, ap.av.getIgnoreGapsConsensus());
2110
2111       SliderPanel.showPIDSlider();
2112     }
2113     else
2114     // remove PIDColouring
2115     {
2116       sg.cs.setThreshold(0, ap.av.getIgnoreGapsConsensus());
2117     }
2118
2119     refresh();
2120   }
2121
2122   /**
2123    * DOCUMENT ME!
2124    * 
2125    * @param e
2126    *          DOCUMENT ME!
2127    */
2128   protected void userDefinedColour_actionPerformed(ActionEvent e)
2129   {
2130     SequenceGroup sg = getGroup();
2131
2132     if (e.getSource().equals(userDefinedColour))
2133     {
2134       new UserDefinedColours(ap, sg);
2135     }
2136     else
2137     {
2138       UserColourScheme udc = (UserColourScheme) UserDefinedColours
2139               .getUserColourSchemes().get(e.getActionCommand());
2140
2141       sg.cs = udc;
2142     }
2143     refresh();
2144   }
2145
2146   /**
2147    * Open a panel where the user can choose which types of sequence annotation
2148    * to show or hide.
2149    * 
2150    * @param e
2151    */
2152   protected void chooseAnnotations_actionPerformed(ActionEvent e)
2153   {
2154     // todo correct way to guard against opening a duplicate panel?
2155     new AnnotationChooser(ap);
2156   }
2157
2158   /**
2159    * DOCUMENT ME!
2160    * 
2161    * @param e
2162    *          DOCUMENT ME!
2163    */
2164   protected void PIDColour_actionPerformed()
2165   {
2166     SequenceGroup sg = getGroup();
2167     sg.cs = new PIDColourScheme();
2168     sg.cs.setConsensus(AAFrequency.calculate(
2169             sg.getSequences(ap.av.getHiddenRepSequences()),
2170             sg.getStartRes(), sg.getEndRes() + 1));
2171     refresh();
2172   }
2173
2174   /**
2175    * DOCUMENT ME!
2176    * 
2177    * @param e
2178    *          DOCUMENT ME!
2179    */
2180   protected void BLOSUM62Colour_actionPerformed()
2181   {
2182     SequenceGroup sg = getGroup();
2183
2184     sg.cs = new Blosum62ColourScheme();
2185
2186     sg.cs.setConsensus(AAFrequency.calculate(
2187             sg.getSequences(ap.av.getHiddenRepSequences()),
2188             sg.getStartRes(), sg.getEndRes() + 1));
2189
2190     refresh();
2191   }
2192
2193   /**
2194    * DOCUMENT ME!
2195    * 
2196    * @param e
2197    *          DOCUMENT ME!
2198    */
2199   protected void noColourmenuItem_actionPerformed()
2200   {
2201     getGroup().cs = null;
2202     refresh();
2203   }
2204
2205   /**
2206    * DOCUMENT ME!
2207    * 
2208    * @param e
2209    *          DOCUMENT ME!
2210    */
2211   protected void conservationMenuItem_actionPerformed()
2212   {
2213     SequenceGroup sg = getGroup();
2214     if (sg.cs == null)
2215     {
2216       return;
2217     }
2218
2219     if (conservationMenuItem.isSelected())
2220     {
2221       // JBPNote: Conservation name shouldn't be i18n translated
2222       Conservation c = new Conservation("Group",
2223               ResidueProperties.propHash, 3, sg.getSequences(ap.av
2224                       .getHiddenRepSequences()), sg.getStartRes(),
2225               sg.getEndRes() + 1);
2226
2227       c.calculate();
2228       c.verdict(false, ap.av.getConsPercGaps());
2229
2230       sg.cs.setConservation(c);
2231
2232       SliderPanel.setConservationSlider(ap, sg.cs, sg.getName());
2233       SliderPanel.showConservationSlider();
2234     }
2235     else
2236     // remove ConservationColouring
2237     {
2238       sg.cs.setConservation(null);
2239     }
2240
2241     refresh();
2242   }
2243
2244   public void annotationMenuItem_actionPerformed(ActionEvent actionEvent)
2245   {
2246     SequenceGroup sg = getGroup();
2247     if (sg == null)
2248     {
2249       return;
2250     }
2251
2252     AnnotationColourGradient acg = new AnnotationColourGradient(
2253             sequence.getAnnotation()[0], null,
2254             AnnotationColourGradient.NO_THRESHOLD);
2255
2256     acg.setPredefinedColours(true);
2257     sg.cs = acg;
2258
2259     refresh();
2260   }
2261
2262   /**
2263    * DOCUMENT ME!
2264    * 
2265    * @param e
2266    *          DOCUMENT ME!
2267    */
2268   protected void groupName_actionPerformed()
2269   {
2270
2271     SequenceGroup sg = getGroup();
2272     EditNameDialog dialog = new EditNameDialog(sg.getName(),
2273             sg.getDescription(), "       "
2274                     + MessageManager.getString("label.group_name") + " ",
2275             MessageManager.getString("label.group_description") + " ",
2276             MessageManager.getString("label.edit_group_name_description"),
2277             ap.alignFrame);
2278
2279     if (!dialog.accept)
2280     {
2281       return;
2282     }
2283
2284     sg.setName(dialog.getName());
2285     sg.setDescription(dialog.getDescription());
2286     refresh();
2287   }
2288
2289   /**
2290    * Get selection group - adding it to the alignment if necessary.
2291    * 
2292    * @return sequence group to operate on
2293    */
2294   SequenceGroup getGroup()
2295   {
2296     SequenceGroup sg = ap.av.getSelectionGroup();
2297     // this method won't add a new group if it already exists
2298     if (sg != null)
2299     {
2300       ap.av.getAlignment().addGroup(sg);
2301     }
2302
2303     return sg;
2304   }
2305
2306   /**
2307    * DOCUMENT ME!
2308    * 
2309    * @param e
2310    *          DOCUMENT ME!
2311    */
2312   void sequenceName_actionPerformed()
2313   {
2314     EditNameDialog dialog = new EditNameDialog(sequence.getName(),
2315             sequence.getDescription(),
2316             "       " + MessageManager.getString("label.sequence_name")
2317                     + " ",
2318             MessageManager.getString("label.sequence_description") + " ",
2319             MessageManager
2320                     .getString("label.edit_sequence_name_description"),
2321             ap.alignFrame);
2322
2323     if (!dialog.accept)
2324     {
2325       return;
2326     }
2327
2328     if (dialog.getName() != null)
2329     {
2330       if (dialog.getName().indexOf(" ") > -1)
2331       {
2332         JOptionPane
2333                 .showMessageDialog(
2334                         ap,
2335                         MessageManager
2336                                 .getString("label.spaces_converted_to_backslashes"),
2337                         MessageManager
2338                                 .getString("label.no_spaces_allowed_sequence_name"),
2339                         JOptionPane.WARNING_MESSAGE);
2340       }
2341
2342       sequence.setName(dialog.getName().replace(' ', '_'));
2343       ap.paintAlignment(false);
2344     }
2345
2346     sequence.setDescription(dialog.getDescription());
2347
2348     ap.av.firePropertyChange("alignment", null, ap.av.getAlignment()
2349             .getSequences());
2350
2351   }
2352
2353   /**
2354    * DOCUMENT ME!
2355    * 
2356    * @param e
2357    *          DOCUMENT ME!
2358    */
2359   void unGroupMenuItem_actionPerformed()
2360   {
2361     SequenceGroup sg = ap.av.getSelectionGroup();
2362     ap.av.getAlignment().deleteGroup(sg);
2363     ap.av.setSelectionGroup(null);
2364     refresh();
2365   }
2366
2367   void createGroupMenuItem_actionPerformed()
2368   {
2369     getGroup(); // implicitly creates group - note - should apply defaults / use
2370                 // standard alignment window logic for this
2371     refresh();
2372   }
2373
2374   /**
2375    * DOCUMENT ME!
2376    * 
2377    * @param e
2378    *          DOCUMENT ME!
2379    */
2380   protected void outline_actionPerformed()
2381   {
2382     SequenceGroup sg = getGroup();
2383     Color col = JColorChooser.showDialog(this,
2384             MessageManager.getString("label.select_outline_colour"),
2385             Color.BLUE);
2386
2387     if (col != null)
2388     {
2389       sg.setOutlineColour(col);
2390     }
2391
2392     refresh();
2393   }
2394
2395   /**
2396    * DOCUMENT ME!
2397    * 
2398    * @param e
2399    *          DOCUMENT ME!
2400    */
2401   public void showBoxes_actionPerformed()
2402   {
2403     getGroup().setDisplayBoxes(showBoxes.isSelected());
2404     refresh();
2405   }
2406
2407   /**
2408    * DOCUMENT ME!
2409    * 
2410    * @param e
2411    *          DOCUMENT ME!
2412    */
2413   public void showText_actionPerformed()
2414   {
2415     getGroup().setDisplayText(showText.isSelected());
2416     refresh();
2417   }
2418
2419   /**
2420    * DOCUMENT ME!
2421    * 
2422    * @param e
2423    *          DOCUMENT ME!
2424    */
2425   public void showColourText_actionPerformed()
2426   {
2427     getGroup().setColourText(showColourText.isSelected());
2428     refresh();
2429   }
2430
2431   public void showLink(String url)
2432   {
2433     try
2434     {
2435       jalview.util.BrowserLauncher.openURL(url);
2436     } catch (Exception ex)
2437     {
2438       JOptionPane.showInternalMessageDialog(Desktop.desktop,
2439               MessageManager.getString("label.web_browser_not_found_unix"),
2440               MessageManager.getString("label.web_browser_not_found"),
2441               JOptionPane.WARNING_MESSAGE);
2442
2443       ex.printStackTrace();
2444     }
2445   }
2446
2447   void hideSequences(boolean representGroup)
2448   {
2449     SequenceGroup sg = ap.av.getSelectionGroup();
2450     if (sg == null || sg.getSize() < 1)
2451     {
2452       ap.av.hideSequence(new SequenceI[]
2453       { sequence });
2454       return;
2455     }
2456
2457     ap.av.setSelectionGroup(null);
2458
2459     if (representGroup)
2460     {
2461       ap.av.hideRepSequences(sequence, sg);
2462
2463       return;
2464     }
2465
2466     int gsize = sg.getSize();
2467     SequenceI[] hseqs;
2468
2469     hseqs = new SequenceI[gsize];
2470
2471     int index = 0;
2472     for (int i = 0; i < gsize; i++)
2473     {
2474       hseqs[index++] = sg.getSequenceAt(i);
2475     }
2476
2477     ap.av.hideSequence(hseqs);
2478     // refresh(); TODO: ? needed ?
2479     ap.av.sendSelection();
2480   }
2481
2482   public void copy_actionPerformed()
2483   {
2484     ap.alignFrame.copy_actionPerformed(null);
2485   }
2486
2487   public void cut_actionPerformed()
2488   {
2489     ap.alignFrame.cut_actionPerformed(null);
2490   }
2491
2492   void changeCase(ActionEvent e)
2493   {
2494     Object source = e.getSource();
2495     SequenceGroup sg = ap.av.getSelectionGroup();
2496
2497     if (sg != null)
2498     {
2499       int[][] startEnd = ap.av.getVisibleRegionBoundaries(sg.getStartRes(),
2500               sg.getEndRes() + 1);
2501
2502       String description;
2503       int caseChange;
2504
2505       if (source == toggle)
2506       {
2507         description = MessageManager.getString("label.toggle_case");
2508         caseChange = ChangeCaseCommand.TOGGLE_CASE;
2509       }
2510       else if (source == upperCase)
2511       {
2512         description = MessageManager.getString("label.to_upper_case");
2513         caseChange = ChangeCaseCommand.TO_UPPER;
2514       }
2515       else
2516       {
2517         description = MessageManager.getString("label.to_lower_case");
2518         caseChange = ChangeCaseCommand.TO_LOWER;
2519       }
2520
2521       ChangeCaseCommand caseCommand = new ChangeCaseCommand(description,
2522               sg.getSequencesAsArray(ap.av.getHiddenRepSequences()),
2523               startEnd, caseChange);
2524
2525       ap.alignFrame.addHistoryItem(caseCommand);
2526
2527       ap.av.firePropertyChange("alignment", null, ap.av.getAlignment()
2528               .getSequences());
2529
2530     }
2531   }
2532
2533   public void outputText_actionPerformed(ActionEvent e)
2534   {
2535     CutAndPasteTransfer cap = new CutAndPasteTransfer();
2536     cap.setForInput(null);
2537     Desktop.addInternalFrame(cap, MessageManager.formatMessage(
2538             "label.alignment_output_command", new String[]
2539             { e.getActionCommand() }), 600, 500);
2540
2541     String[] omitHidden = null;
2542
2543     System.out.println("PROMPT USER HERE"); // TODO: decide if a prompt happens
2544     // or we simply trust the user wants
2545     // wysiwig behaviour
2546
2547     cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
2548             ap.av, true));
2549   }
2550
2551   public void pdbFromFile_actionPerformed()
2552   {
2553     jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
2554             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
2555     chooser.setFileView(new jalview.io.JalviewFileView());
2556     chooser.setDialogTitle(MessageManager.formatMessage(
2557             "label.select_pdb_file_for", new String[]
2558             { sequence.getDisplayId(false) }));
2559     chooser.setToolTipText(MessageManager.formatMessage(
2560             "label.load_pdb_file_associate_with_sequence", new String[]
2561             { sequence.getDisplayId(false) }));
2562
2563     int value = chooser.showOpenDialog(null);
2564
2565     if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
2566     {
2567       String choice = chooser.getSelectedFile().getPath();
2568       jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
2569       new AssociatePdbFileWithSeq().associatePdbWithSeq(choice,
2570               jalview.io.AppletFormatAdapter.FILE, sequence, true,
2571               Desktop.instance);
2572     }
2573
2574   }
2575
2576   // JBNote: commented out - these won't be instantiated here...!
2577   // public void RNAFold_actionPerformed() throws Exception
2578   // {
2579   // Predict2D P2D = new Predict2D();
2580   // P2D.getStructure2DFromRNAFold("toto");
2581   // }
2582   //
2583   // public void ContraFold_actionPerformed() throws Exception
2584   // {
2585   // Predict2D P2D = new Predict2D();
2586   // P2D.getStructure2DFromContraFold("toto");
2587   // }
2588   public void enterPDB_actionPerformed()
2589   {
2590     String id = JOptionPane.showInternalInputDialog(Desktop.desktop,
2591             MessageManager.getString("label.enter_pdb_id"),
2592             MessageManager.getString("label.enter_pdb_id"),
2593             JOptionPane.QUESTION_MESSAGE);
2594
2595     if (id != null && id.length() > 0)
2596     {
2597       PDBEntry entry = new PDBEntry();
2598       entry.setId(id.toUpperCase());
2599       sequence.getDatasetSequence().addPDBId(entry);
2600     }
2601   }
2602
2603   public void discoverPDB_actionPerformed()
2604   {
2605
2606     final SequenceI[] sequences = ((ap.av.getSelectionGroup() == null) ? new SequenceI[]
2607     { sequence }
2608             : ap.av.getSequenceSelection());
2609     Thread discpdb = new Thread(new Runnable()
2610     {
2611       @Override
2612       public void run()
2613       {
2614
2615         new jalview.ws.DBRefFetcher(sequences, ap.alignFrame)
2616                 .fetchDBRefs(false);
2617       }
2618
2619     });
2620     discpdb.start();
2621   }
2622
2623   public void sequenceFeature_actionPerformed()
2624   {
2625     SequenceGroup sg = ap.av.getSelectionGroup();
2626     if (sg == null)
2627     {
2628       return;
2629     }
2630
2631     int rsize = 0, gSize = sg.getSize();
2632     SequenceI[] rseqs, seqs = new SequenceI[gSize];
2633     SequenceFeature[] tfeatures, features = new SequenceFeature[gSize];
2634
2635     for (int i = 0; i < gSize; i++)
2636     {
2637       int start = sg.getSequenceAt(i).findPosition(sg.getStartRes());
2638       int end = sg.findEndRes(sg.getSequenceAt(i));
2639       if (start <= end)
2640       {
2641         seqs[rsize] = sg.getSequenceAt(i).getDatasetSequence();
2642         features[rsize] = new SequenceFeature(null, null, null, start, end,
2643                 "Jalview");
2644         rsize++;
2645       }
2646     }
2647     rseqs = new SequenceI[rsize];
2648     tfeatures = new SequenceFeature[rsize];
2649     System.arraycopy(seqs, 0, rseqs, 0, rsize);
2650     System.arraycopy(features, 0, tfeatures, 0, rsize);
2651     features = tfeatures;
2652     seqs = rseqs;
2653     if (ap.seqPanel.seqCanvas.getFeatureRenderer().amendFeatures(seqs,
2654             features, true, ap))
2655     {
2656       ap.alignFrame.setShowSeqFeatures(true);
2657       ap.highlightSearchResults(null);
2658     }
2659   }
2660
2661   public void textColour_actionPerformed()
2662   {
2663     SequenceGroup sg = getGroup();
2664     if (sg != null)
2665     {
2666       new TextColourChooser().chooseColour(ap, sg);
2667     }
2668   }
2669
2670   public void colourByStructure(String pdbid)
2671   {
2672     Annotation[] anots = ap.av.getStructureSelectionManager()
2673             .colourSequenceFromStructure(sequence, pdbid);
2674
2675     AlignmentAnnotation an = new AlignmentAnnotation("Structure",
2676             "Coloured by " + pdbid, anots);
2677
2678     ap.av.getAlignment().addAnnotation(an);
2679     an.createSequenceMapping(sequence, 0, true);
2680     // an.adjustForAlignment();
2681     ap.av.getAlignment().setAnnotationIndex(an, 0);
2682
2683     ap.adjustAnnotationHeight();
2684
2685     sequence.addAlignmentAnnotation(an);
2686
2687   }
2688
2689   public void editSequence_actionPerformed(ActionEvent actionEvent)
2690   {
2691     SequenceGroup sg = ap.av.getSelectionGroup();
2692
2693     if (sg != null)
2694     {
2695       if (sequence == null)
2696       {
2697         sequence = sg.getSequenceAt(0);
2698       }
2699
2700       EditNameDialog dialog = new EditNameDialog(
2701               sequence.getSequenceAsString(sg.getStartRes(),
2702                       sg.getEndRes() + 1), null,
2703               MessageManager.getString("label.edit_sequence"), null,
2704               MessageManager.getString("label.edit_sequence"),
2705               ap.alignFrame);
2706
2707       if (dialog.accept)
2708       {
2709         EditCommand editCommand = new EditCommand(
2710                 MessageManager.getString("label.edit_sequences"),
2711                 Action.REPLACE, dialog.getName().replace(' ',
2712                         ap.av.getGapCharacter()),
2713                 sg.getSequencesAsArray(ap.av.getHiddenRepSequences()),
2714                 sg.getStartRes(), sg.getEndRes() + 1, ap.av.getAlignment());
2715
2716         ap.alignFrame.addHistoryItem(editCommand);
2717
2718         ap.av.firePropertyChange("alignment", null, ap.av.getAlignment()
2719                 .getSequences());
2720       }
2721     }
2722   }
2723
2724 }