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