JAL-1628 method to hide insertions to current sequence selection
[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   JMenu structureMenu = new JMenu();
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     viewStructureMenu.setText(MessageManager
1507             .getString("label.view_structure"));
1508     // colStructureMenu.setText("Colour By Structure");
1509     editSequence.setText(MessageManager.getString("label.edit_sequence")
1510             + "...");
1511     editSequence.addActionListener(new ActionListener()
1512     {
1513       @Override
1514       public void actionPerformed(ActionEvent actionEvent)
1515       {
1516         editSequence_actionPerformed(actionEvent);
1517       }
1518     });
1519     makeReferenceSeq.setText("Mark as representative");
1520     makeReferenceSeq.addActionListener(new ActionListener()
1521     {
1522       
1523       @Override
1524       public void actionPerformed(ActionEvent actionEvent)
1525       {
1526         makeReferenceSeq_actionPerformed(actionEvent);
1527         
1528       }
1529     });
1530     hideInsertions.setText(MessageManager.getString("label.hide_insertions"));
1531     hideInsertions.addActionListener(new ActionListener()
1532     {
1533
1534       @Override
1535       public void actionPerformed(ActionEvent e)
1536       {
1537         hideInsertions_actionPerformed(e);
1538       }
1539     });
1540     /*
1541      * annotationMenuItem.setText("By Annotation");
1542      * annotationMenuItem.addActionListener(new ActionListener() { public void
1543      * actionPerformed(ActionEvent actionEvent) {
1544      * annotationMenuItem_actionPerformed(actionEvent); } });
1545      */
1546     groupMenu.add(sequenceSelDetails);
1547     add(groupMenu);
1548     add(sequenceMenu);
1549     add(structureMenu);
1550     if (sequence!=null)
1551     {
1552       add(hideInsertions);
1553     }
1554     // annotations configuration panel suppressed for now
1555     // groupMenu.add(chooseAnnotations);
1556
1557     /*
1558      * Add show/hide annotations to the Sequence menu, and to the Selection menu
1559      * (if a selection group is in force).
1560      */
1561     sequenceMenu.add(seqShowAnnotationsMenu);
1562     sequenceMenu.add(seqHideAnnotationsMenu);
1563     sequenceMenu.add(seqAddReferenceAnnotations);
1564     groupMenu.add(groupShowAnnotationsMenu);
1565     groupMenu.add(groupHideAnnotationsMenu);
1566     groupMenu.add(groupAddReferenceAnnotations);
1567     groupMenu.add(editMenu);
1568     groupMenu.add(outputMenu);
1569     groupMenu.add(sequenceFeature);
1570     groupMenu.add(createGroupMenuItem);
1571     groupMenu.add(unGroupMenuItem);
1572     groupMenu.add(jMenu1);
1573     sequenceMenu.add(sequenceName);
1574     sequenceMenu.add(sequenceDetails);
1575     sequenceMenu.add(makeReferenceSeq);
1576     colourMenu.add(textColour);
1577     colourMenu.add(noColourmenuItem);
1578     colourMenu.add(clustalColour);
1579     colourMenu.add(BLOSUM62Colour);
1580     colourMenu.add(PIDColour);
1581     colourMenu.add(zappoColour);
1582     colourMenu.add(taylorColour);
1583     colourMenu.add(hydrophobicityColour);
1584     colourMenu.add(helixColour);
1585     colourMenu.add(strandColour);
1586     colourMenu.add(turnColour);
1587     colourMenu.add(buriedColour);
1588     colourMenu.add(nucleotideMenuItem);
1589     if (ap.getAlignment().isNucleotide())
1590     {
1591       // JBPNote - commented since the colourscheme isn't functional
1592       // colourMenu.add(RNAInteractionColour);
1593       colourMenu.add(purinePyrimidineColour);
1594     }
1595     // colourMenu.add(covariationColour);
1596     colourMenu.add(userDefinedColour);
1597
1598     if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
1599     {
1600       java.util.Enumeration userColours = jalview.gui.UserDefinedColours
1601               .getUserColourSchemes().keys();
1602
1603       while (userColours.hasMoreElements())
1604       {
1605         JMenuItem item = new JMenuItem(userColours.nextElement().toString());
1606         item.addActionListener(new ActionListener()
1607         {
1608           @Override
1609           public void actionPerformed(ActionEvent evt)
1610           {
1611             userDefinedColour_actionPerformed(evt);
1612           }
1613         });
1614         colourMenu.add(item);
1615       }
1616     }
1617
1618     colourMenu.addSeparator();
1619     colourMenu.add(abovePIDColour);
1620     colourMenu.add(conservationMenuItem);
1621     // colourMenu.add(annotationMenuItem);
1622     editMenu.add(copy);
1623     editMenu.add(cut);
1624     editMenu.add(editSequence);
1625     editMenu.add(upperCase);
1626     editMenu.add(lowerCase);
1627     editMenu.add(toggle);
1628     pdbMenu.add(pdbFromFile);
1629     // JBPNote: These shouldn't be added here - should appear in a generic
1630     // 'apply web service to this sequence menu'
1631     // pdbMenu.add(RNAFold);
1632     // pdbMenu.add(ContraFold);
1633     pdbMenu.add(enterPDB);
1634     pdbMenu.add(discoverPDB);
1635     jMenu1.add(groupName);
1636     jMenu1.add(colourMenu);
1637     jMenu1.add(showBoxes);
1638     jMenu1.add(showText);
1639     jMenu1.add(showColourText);
1640     jMenu1.add(outline);
1641     jMenu1.add(displayNonconserved);
1642     structureMenu.add(pdbMenu);
1643     structureMenu.add(viewStructureMenu);
1644     // structureMenu.add(colStructureMenu);
1645     noColourmenuItem.setText(MessageManager.getString("label.none"));
1646     noColourmenuItem.addActionListener(new java.awt.event.ActionListener()
1647     {
1648       @Override
1649       public void actionPerformed(ActionEvent e)
1650       {
1651         noColourmenuItem_actionPerformed();
1652       }
1653     });
1654
1655     clustalColour.setText(MessageManager
1656             .getString("label.clustalx_colours"));
1657     clustalColour.addActionListener(new java.awt.event.ActionListener()
1658     {
1659       @Override
1660       public void actionPerformed(ActionEvent e)
1661       {
1662         clustalColour_actionPerformed();
1663       }
1664     });
1665     zappoColour.setText(MessageManager.getString("label.zappo"));
1666     zappoColour.addActionListener(new java.awt.event.ActionListener()
1667     {
1668       @Override
1669       public void actionPerformed(ActionEvent e)
1670       {
1671         zappoColour_actionPerformed();
1672       }
1673     });
1674     taylorColour.setText(MessageManager.getString("label.taylor"));
1675     taylorColour.addActionListener(new java.awt.event.ActionListener()
1676     {
1677       @Override
1678       public void actionPerformed(ActionEvent e)
1679       {
1680         taylorColour_actionPerformed();
1681       }
1682     });
1683     hydrophobicityColour.setText(MessageManager
1684             .getString("label.hydrophobicity"));
1685     hydrophobicityColour
1686             .addActionListener(new java.awt.event.ActionListener()
1687             {
1688               @Override
1689               public void actionPerformed(ActionEvent e)
1690               {
1691                 hydrophobicityColour_actionPerformed();
1692               }
1693             });
1694     helixColour.setText(MessageManager.getString("label.helix_propensity"));
1695     helixColour.addActionListener(new java.awt.event.ActionListener()
1696     {
1697       @Override
1698       public void actionPerformed(ActionEvent e)
1699       {
1700         helixColour_actionPerformed();
1701       }
1702     });
1703     strandColour.setText(MessageManager
1704             .getString("label.strand_propensity"));
1705     strandColour.addActionListener(new java.awt.event.ActionListener()
1706     {
1707       @Override
1708       public void actionPerformed(ActionEvent e)
1709       {
1710         strandColour_actionPerformed();
1711       }
1712     });
1713     turnColour.setText(MessageManager.getString("label.turn_propensity"));
1714     turnColour.addActionListener(new java.awt.event.ActionListener()
1715     {
1716       @Override
1717       public void actionPerformed(ActionEvent e)
1718       {
1719         turnColour_actionPerformed();
1720       }
1721     });
1722     buriedColour.setText(MessageManager.getString("label.buried_index"));
1723     buriedColour.addActionListener(new java.awt.event.ActionListener()
1724     {
1725       @Override
1726       public void actionPerformed(ActionEvent e)
1727       {
1728         buriedColour_actionPerformed();
1729       }
1730     });
1731     abovePIDColour.setText(MessageManager
1732             .getString("label.above_identity_percentage"));
1733     abovePIDColour.addActionListener(new java.awt.event.ActionListener()
1734     {
1735       @Override
1736       public void actionPerformed(ActionEvent e)
1737       {
1738         abovePIDColour_actionPerformed();
1739       }
1740     });
1741     userDefinedColour.setText(MessageManager
1742             .getString("action.user_defined"));
1743     userDefinedColour.addActionListener(new java.awt.event.ActionListener()
1744     {
1745       @Override
1746       public void actionPerformed(ActionEvent e)
1747       {
1748         userDefinedColour_actionPerformed(e);
1749       }
1750     });
1751     PIDColour
1752             .setText(MessageManager.getString("label.percentage_identity"));
1753     PIDColour.addActionListener(new java.awt.event.ActionListener()
1754     {
1755       @Override
1756       public void actionPerformed(ActionEvent e)
1757       {
1758         PIDColour_actionPerformed();
1759       }
1760     });
1761     BLOSUM62Colour.setText(MessageManager.getString("label.blosum62"));
1762     BLOSUM62Colour.addActionListener(new java.awt.event.ActionListener()
1763     {
1764       @Override
1765       public void actionPerformed(ActionEvent e)
1766       {
1767         BLOSUM62Colour_actionPerformed();
1768       }
1769     });
1770     purinePyrimidineColour.setText(MessageManager
1771             .getString("label.purine_pyrimidine"));
1772     purinePyrimidineColour
1773             .addActionListener(new java.awt.event.ActionListener()
1774             {
1775               @Override
1776               public void actionPerformed(ActionEvent e)
1777               {
1778                 purinePyrimidineColour_actionPerformed();
1779               }
1780             });
1781
1782     /*
1783      * covariationColour.addActionListener(new java.awt.event.ActionListener() {
1784      * public void actionPerformed(ActionEvent e) {
1785      * covariationColour_actionPerformed(); } });
1786      */
1787
1788     conservationMenuItem.setText(MessageManager
1789             .getString("label.conservation"));
1790     conservationMenuItem
1791             .addActionListener(new java.awt.event.ActionListener()
1792             {
1793               @Override
1794               public void actionPerformed(ActionEvent e)
1795               {
1796                 conservationMenuItem_actionPerformed();
1797               }
1798             });
1799   }
1800
1801   /**
1802    * Check for any annotations on the underlying dataset sequences (for the
1803    * current selection group) which are not 'on the alignment'.If any are found,
1804    * enable the option to add them to the alignment. The criteria for 'on the
1805    * alignment' is finding an alignment annotation on the alignment, matched on
1806    * calcId, label and sequenceRef.
1807    * 
1808    * A tooltip is also constructed that displays the source (calcId) and type
1809    * (label) of the annotations that can be added.
1810    * 
1811    * @param menuItem
1812    * @param forSequences
1813    */
1814   protected void configureReferenceAnnotationsMenu(
1815           JMenuItem menuItem, List<SequenceI> forSequences)
1816   {
1817     menuItem.setText(MessageManager
1818             .getString("label.add_reference_annotations"));
1819     menuItem.setEnabled(false);
1820     if (forSequences == null)
1821     {
1822       return;
1823     }
1824
1825     /*
1826      * Temporary store to hold distinct calcId / type pairs for the tooltip.
1827      * Using TreeMap means calcIds are shown in alphabetical order.
1828      */
1829     Map<String, String> tipEntries = new TreeMap<String, String>();
1830     StringBuilder tooltip = new StringBuilder(64);
1831     tooltip.append(MessageManager.getString("label.add_annotations_for"));
1832
1833     /*
1834      * For each sequence selected in the alignment, make a list of any
1835      * annotations on the underlying dataset sequence which are not already on
1836      * the alignment.
1837      * 
1838      * Build a map of { alignmentSequence, <List of annotations to add> }
1839      */
1840     AlignmentI al = this.ap.av.getAlignment();
1841     final Map<SequenceI, List<AlignmentAnnotation>> candidates = new LinkedHashMap<SequenceI, List<AlignmentAnnotation>>();
1842     for (SequenceI seq : forSequences)
1843     {
1844       SequenceI dataset = seq.getDatasetSequence();
1845       if (dataset == null)
1846       {
1847         continue;
1848       }
1849       AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1850       if (datasetAnnotations == null)
1851       {
1852         continue;
1853       }
1854       final List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1855       for (AlignmentAnnotation dsann : datasetAnnotations)
1856       {
1857         /*
1858          * Find matching annotations on the alignment.
1859          */
1860         final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
1861                 .findAnnotations(seq, dsann.getCalcId(),
1862                         dsann.label);
1863         if (!matchedAlignmentAnnotations.iterator().hasNext())
1864         {
1865           result.add(dsann);
1866           tipEntries.put(dsann.getCalcId(), dsann.label);
1867         }
1868       }
1869       /*
1870        * Save any addable annotations for this sequence
1871        */
1872       if (!result.isEmpty())
1873       {
1874         candidates.put(seq, result);
1875       }
1876     }
1877     if (!candidates.isEmpty())
1878     {
1879       /*
1880        * Found annotations that could be added. Enable the menu item, and
1881        * configure its tooltip and action.
1882        */
1883       menuItem.setEnabled(true);
1884       for (String calcId : tipEntries.keySet())
1885       {
1886         tooltip.append("<br/>" + calcId + "/" + tipEntries.get(calcId));
1887       }
1888       String tooltipText = JvSwingUtils.wrapTooltip(true,
1889               tooltip.toString());
1890       menuItem.setToolTipText(tooltipText);
1891
1892       menuItem.addActionListener(new ActionListener()
1893       {
1894         @Override
1895         public void actionPerformed(ActionEvent e)
1896         {
1897           addReferenceAnnotations_actionPerformed(candidates);
1898         }
1899       });
1900     }
1901   }
1902
1903   /**
1904    * Add annotations to the sequences and to the alignment.
1905    * 
1906    * @param candidates
1907    *          a map whose keys are sequences on the alignment, and values a list
1908    *          of annotations to add to each sequence
1909    */
1910   protected void addReferenceAnnotations_actionPerformed(
1911           Map<SequenceI, List<AlignmentAnnotation>> candidates)
1912   {
1913     /*
1914      * Add annotations at the top of the annotation, in the same order as their
1915      * related sequences.
1916      */
1917     for (SequenceI seq : candidates.keySet())
1918     {
1919       for (AlignmentAnnotation ann : candidates.get(seq))
1920       {
1921         AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1922         int startRes = 0;
1923         int endRes = ann.annotations.length;
1924         final SequenceGroup selectionGroup = this.ap.av.getSelectionGroup();
1925         if (selectionGroup != null)
1926         {
1927           startRes = selectionGroup.getStartRes();
1928           endRes = selectionGroup.getEndRes();
1929         }
1930         copyAnn.restrict(startRes, endRes);
1931
1932         /*
1933          * Add to the sequence (sets copyAnn.datasetSequence), unless the
1934          * original annotation is already on the sequence.
1935          */
1936         if (!seq.hasAnnotation(ann))
1937         {
1938           seq.addAlignmentAnnotation(copyAnn);
1939         }
1940         // adjust for gaps
1941         copyAnn.adjustForAlignment();
1942         // add to the alignment and set visible
1943         this.ap.getAlignment().addAnnotation(copyAnn);
1944         copyAnn.visible = true;
1945       }
1946     }
1947     refresh();
1948   }
1949 protected void makeReferenceSeq_actionPerformed(ActionEvent actionEvent)
1950 {
1951   if (!ap.av.getAlignment().hasSeqrep())
1952   {
1953     // initialise the display flags so the user sees something happen
1954     ap.av.setDisplayReferenceSeq(true);
1955     ap.av.setColourByReferenceSeq(true);
1956     ap.av.getAlignment().setSeqrep(sequence);
1957   }
1958   else
1959   {
1960     if (ap.av.getAlignment().getSeqrep() == sequence)
1961     {
1962       ap.av.getAlignment().setSeqrep(null);
1963     }
1964     else
1965     {
1966       ap.av.getAlignment().setSeqrep(sequence);
1967     }
1968   }
1969   refresh();
1970 }
1971
1972   protected void hideInsertions_actionPerformed(ActionEvent actionEvent)
1973   {
1974     if (sequence != null)
1975     {
1976       ColumnSelection cs = ap.av.getColumnSelection();
1977       if (cs == null)
1978       {
1979         cs = new ColumnSelection();
1980       }
1981       cs.hideInsertionsFor(sequence);
1982       ap.av.setColumnSelection(cs);
1983     }
1984     refresh();
1985   }
1986   protected void sequenceSelectionDetails_actionPerformed()
1987   {
1988     createSequenceDetailsReport(ap.av.getSequenceSelection());
1989   }
1990
1991   protected void sequenceDetails_actionPerformed()
1992   {
1993     createSequenceDetailsReport(new SequenceI[]
1994     { sequence });
1995   }
1996
1997   public void createSequenceDetailsReport(SequenceI[] sequences)
1998   {
1999     CutAndPasteHtmlTransfer cap = new CutAndPasteHtmlTransfer();
2000     StringBuffer contents = new StringBuffer();
2001     for (SequenceI seq : sequences)
2002     {
2003       contents.append("<p><h2>"
2004               + MessageManager
2005                       .formatMessage(
2006                               "label.create_sequence_details_report_annotation_for",
2007                               new String[]
2008                               { seq.getDisplayId(true) }) + "</h2></p><p>");
2009       new SequenceAnnotationReport(null)
2010               .createSequenceAnnotationReport(
2011                       contents,
2012                       seq,
2013                       true,
2014                       true,
2015                       false,
2016                       (ap.getSeqPanel().seqCanvas.fr != null) ? ap
2017                               .getSeqPanel().seqCanvas.fr
2018                               .getMinMax()
2019                               : null);
2020       contents.append("</p>");
2021     }
2022     cap.setText("<html>" + contents.toString() + "</html>");
2023
2024     Desktop.instance.addInternalFrame(cap, MessageManager.formatMessage(
2025             "label.sequece_details_for",
2026             (sequences.length == 1 ? new String[]
2027             { sequences[0].getDisplayId(true) } : new String[]
2028             { MessageManager.getString("label.selection") })), 500, 400);
2029
2030   }
2031
2032   protected void showNonconserved_actionPerformed()
2033   {
2034     getGroup().setShowNonconserved(displayNonconserved.isSelected());
2035     refresh();
2036   }
2037
2038   /**
2039    * call to refresh view after settings change
2040    */
2041   void refresh()
2042   {
2043     ap.updateAnnotation();
2044     ap.paintAlignment(true);
2045
2046     PaintRefresher.Refresh(this, ap.av.getSequenceSetId());
2047   }
2048
2049   /**
2050    * DOCUMENT ME!
2051    * 
2052    * @param e
2053    *          DOCUMENT ME!
2054    */
2055   protected void clustalColour_actionPerformed()
2056   {
2057     SequenceGroup sg = getGroup();
2058     sg.cs = new ClustalxColourScheme(sg, ap.av.getHiddenRepSequences());
2059     refresh();
2060   }
2061
2062   /**
2063    * DOCUMENT ME!
2064    * 
2065    * @param e
2066    *          DOCUMENT ME!
2067    */
2068   protected void zappoColour_actionPerformed()
2069   {
2070     getGroup().cs = new ZappoColourScheme();
2071     refresh();
2072   }
2073
2074   /**
2075    * DOCUMENT ME!
2076    * 
2077    * @param e
2078    *          DOCUMENT ME!
2079    */
2080   protected void taylorColour_actionPerformed()
2081   {
2082     getGroup().cs = new TaylorColourScheme();
2083     refresh();
2084   }
2085
2086   /**
2087    * DOCUMENT ME!
2088    * 
2089    * @param e
2090    *          DOCUMENT ME!
2091    */
2092   protected void hydrophobicityColour_actionPerformed()
2093   {
2094     getGroup().cs = new HydrophobicColourScheme();
2095     refresh();
2096   }
2097
2098   /**
2099    * DOCUMENT ME!
2100    * 
2101    * @param e
2102    *          DOCUMENT ME!
2103    */
2104   protected void helixColour_actionPerformed()
2105   {
2106     getGroup().cs = new HelixColourScheme();
2107     refresh();
2108   }
2109
2110   /**
2111    * DOCUMENT ME!
2112    * 
2113    * @param e
2114    *          DOCUMENT ME!
2115    */
2116   protected void strandColour_actionPerformed()
2117   {
2118     getGroup().cs = new StrandColourScheme();
2119     refresh();
2120   }
2121
2122   /**
2123    * DOCUMENT ME!
2124    * 
2125    * @param e
2126    *          DOCUMENT ME!
2127    */
2128   protected void turnColour_actionPerformed()
2129   {
2130     getGroup().cs = new TurnColourScheme();
2131     refresh();
2132   }
2133
2134   /**
2135    * DOCUMENT ME!
2136    * 
2137    * @param e
2138    *          DOCUMENT ME!
2139    */
2140   protected void buriedColour_actionPerformed()
2141   {
2142     getGroup().cs = new BuriedColourScheme();
2143     refresh();
2144   }
2145
2146   /**
2147    * DOCUMENT ME!
2148    * 
2149    * @param e
2150    *          DOCUMENT ME!
2151    */
2152   public void nucleotideMenuItem_actionPerformed()
2153   {
2154     getGroup().cs = new NucleotideColourScheme();
2155     refresh();
2156   }
2157
2158   protected void purinePyrimidineColour_actionPerformed()
2159   {
2160     getGroup().cs = new PurinePyrimidineColourScheme();
2161     refresh();
2162   }
2163
2164   /*
2165    * protected void covariationColour_actionPerformed() { getGroup().cs = new
2166    * CovariationColourScheme(sequence.getAnnotation()[0]); refresh(); }
2167    */
2168   /**
2169    * DOCUMENT ME!
2170    * 
2171    * @param e
2172    *          DOCUMENT ME!
2173    */
2174   protected void abovePIDColour_actionPerformed()
2175   {
2176     SequenceGroup sg = getGroup();
2177     if (sg.cs == null)
2178     {
2179       return;
2180     }
2181
2182     if (abovePIDColour.isSelected())
2183     {
2184       sg.cs.setConsensus(AAFrequency.calculate(
2185               sg.getSequences(ap.av.getHiddenRepSequences()),
2186               sg.getStartRes(), sg.getEndRes() + 1));
2187
2188       int threshold = SliderPanel.setPIDSliderSource(ap, sg.cs, getGroup()
2189               .getName());
2190
2191       sg.cs.setThreshold(threshold, ap.av.getIgnoreGapsConsensus());
2192
2193       SliderPanel.showPIDSlider();
2194     }
2195     else
2196     // remove PIDColouring
2197     {
2198       sg.cs.setThreshold(0, ap.av.getIgnoreGapsConsensus());
2199     }
2200
2201     refresh();
2202   }
2203
2204   /**
2205    * DOCUMENT ME!
2206    * 
2207    * @param e
2208    *          DOCUMENT ME!
2209    */
2210   protected void userDefinedColour_actionPerformed(ActionEvent e)
2211   {
2212     SequenceGroup sg = getGroup();
2213
2214     if (e.getSource().equals(userDefinedColour))
2215     {
2216       new UserDefinedColours(ap, sg);
2217     }
2218     else
2219     {
2220       UserColourScheme udc = (UserColourScheme) UserDefinedColours
2221               .getUserColourSchemes().get(e.getActionCommand());
2222
2223       sg.cs = udc;
2224     }
2225     refresh();
2226   }
2227
2228   /**
2229    * Open a panel where the user can choose which types of sequence annotation
2230    * to show or hide.
2231    * 
2232    * @param e
2233    */
2234   protected void chooseAnnotations_actionPerformed(ActionEvent e)
2235   {
2236     // todo correct way to guard against opening a duplicate panel?
2237     new AnnotationChooser(ap);
2238   }
2239
2240   /**
2241    * DOCUMENT ME!
2242    * 
2243    * @param e
2244    *          DOCUMENT ME!
2245    */
2246   protected void PIDColour_actionPerformed()
2247   {
2248     SequenceGroup sg = getGroup();
2249     sg.cs = new PIDColourScheme();
2250     sg.cs.setConsensus(AAFrequency.calculate(
2251             sg.getSequences(ap.av.getHiddenRepSequences()),
2252             sg.getStartRes(), sg.getEndRes() + 1));
2253     refresh();
2254   }
2255
2256   /**
2257    * DOCUMENT ME!
2258    * 
2259    * @param e
2260    *          DOCUMENT ME!
2261    */
2262   protected void BLOSUM62Colour_actionPerformed()
2263   {
2264     SequenceGroup sg = getGroup();
2265
2266     sg.cs = new Blosum62ColourScheme();
2267
2268     sg.cs.setConsensus(AAFrequency.calculate(
2269             sg.getSequences(ap.av.getHiddenRepSequences()),
2270             sg.getStartRes(), sg.getEndRes() + 1));
2271
2272     refresh();
2273   }
2274
2275   /**
2276    * DOCUMENT ME!
2277    * 
2278    * @param e
2279    *          DOCUMENT ME!
2280    */
2281   protected void noColourmenuItem_actionPerformed()
2282   {
2283     getGroup().cs = null;
2284     refresh();
2285   }
2286
2287   /**
2288    * DOCUMENT ME!
2289    * 
2290    * @param e
2291    *          DOCUMENT ME!
2292    */
2293   protected void conservationMenuItem_actionPerformed()
2294   {
2295     SequenceGroup sg = getGroup();
2296     if (sg.cs == null)
2297     {
2298       return;
2299     }
2300
2301     if (conservationMenuItem.isSelected())
2302     {
2303       // JBPNote: Conservation name shouldn't be i18n translated
2304       Conservation c = new Conservation("Group",
2305               ResidueProperties.propHash, 3, sg.getSequences(ap.av
2306                       .getHiddenRepSequences()), sg.getStartRes(),
2307               sg.getEndRes() + 1);
2308
2309       c.calculate();
2310       c.verdict(false, ap.av.getConsPercGaps());
2311
2312       sg.cs.setConservation(c);
2313
2314       SliderPanel.setConservationSlider(ap, sg.cs, sg.getName());
2315       SliderPanel.showConservationSlider();
2316     }
2317     else
2318     // remove ConservationColouring
2319     {
2320       sg.cs.setConservation(null);
2321     }
2322
2323     refresh();
2324   }
2325
2326   public void annotationMenuItem_actionPerformed(ActionEvent actionEvent)
2327   {
2328     SequenceGroup sg = getGroup();
2329     if (sg == null)
2330     {
2331       return;
2332     }
2333
2334     AnnotationColourGradient acg = new AnnotationColourGradient(
2335             sequence.getAnnotation()[0], null,
2336             AnnotationColourGradient.NO_THRESHOLD);
2337
2338     acg.setPredefinedColours(true);
2339     sg.cs = acg;
2340
2341     refresh();
2342   }
2343
2344   /**
2345    * DOCUMENT ME!
2346    * 
2347    * @param e
2348    *          DOCUMENT ME!
2349    */
2350   protected void groupName_actionPerformed()
2351   {
2352
2353     SequenceGroup sg = getGroup();
2354     EditNameDialog dialog = new EditNameDialog(sg.getName(),
2355             sg.getDescription(), "       "
2356                     + MessageManager.getString("label.group_name") + " ",
2357             MessageManager.getString("label.group_description") + " ",
2358             MessageManager.getString("label.edit_group_name_description"),
2359             ap.alignFrame);
2360
2361     if (!dialog.accept)
2362     {
2363       return;
2364     }
2365
2366     sg.setName(dialog.getName());
2367     sg.setDescription(dialog.getDescription());
2368     refresh();
2369   }
2370
2371   /**
2372    * Get selection group - adding it to the alignment if necessary.
2373    * 
2374    * @return sequence group to operate on
2375    */
2376   SequenceGroup getGroup()
2377   {
2378     SequenceGroup sg = ap.av.getSelectionGroup();
2379     // this method won't add a new group if it already exists
2380     if (sg != null)
2381     {
2382       ap.av.getAlignment().addGroup(sg);
2383     }
2384
2385     return sg;
2386   }
2387
2388   /**
2389    * DOCUMENT ME!
2390    * 
2391    * @param e
2392    *          DOCUMENT ME!
2393    */
2394   void sequenceName_actionPerformed()
2395   {
2396     EditNameDialog dialog = new EditNameDialog(sequence.getName(),
2397             sequence.getDescription(),
2398             "       " + MessageManager.getString("label.sequence_name")
2399                     + " ",
2400             MessageManager.getString("label.sequence_description") + " ",
2401             MessageManager
2402                     .getString("label.edit_sequence_name_description"),
2403             ap.alignFrame);
2404
2405     if (!dialog.accept)
2406     {
2407       return;
2408     }
2409
2410     if (dialog.getName() != null)
2411     {
2412       if (dialog.getName().indexOf(" ") > -1)
2413       {
2414         JOptionPane
2415                 .showMessageDialog(
2416                         ap,
2417                         MessageManager
2418                                 .getString("label.spaces_converted_to_backslashes"),
2419                         MessageManager
2420                                 .getString("label.no_spaces_allowed_sequence_name"),
2421                         JOptionPane.WARNING_MESSAGE);
2422       }
2423
2424       sequence.setName(dialog.getName().replace(' ', '_'));
2425       ap.paintAlignment(false);
2426     }
2427
2428     sequence.setDescription(dialog.getDescription());
2429
2430     ap.av.firePropertyChange("alignment", null, ap.av.getAlignment()
2431             .getSequences());
2432
2433   }
2434
2435   /**
2436    * DOCUMENT ME!
2437    * 
2438    * @param e
2439    *          DOCUMENT ME!
2440    */
2441   void unGroupMenuItem_actionPerformed()
2442   {
2443     SequenceGroup sg = ap.av.getSelectionGroup();
2444     ap.av.getAlignment().deleteGroup(sg);
2445     ap.av.setSelectionGroup(null);
2446     refresh();
2447   }
2448
2449   void createGroupMenuItem_actionPerformed()
2450   {
2451     getGroup(); // implicitly creates group - note - should apply defaults / use
2452                 // standard alignment window logic for this
2453     refresh();
2454   }
2455
2456   /**
2457    * DOCUMENT ME!
2458    * 
2459    * @param e
2460    *          DOCUMENT ME!
2461    */
2462   protected void outline_actionPerformed()
2463   {
2464     SequenceGroup sg = getGroup();
2465     Color col = JColorChooser.showDialog(this,
2466             MessageManager.getString("label.select_outline_colour"),
2467             Color.BLUE);
2468
2469     if (col != null)
2470     {
2471       sg.setOutlineColour(col);
2472     }
2473
2474     refresh();
2475   }
2476
2477   /**
2478    * DOCUMENT ME!
2479    * 
2480    * @param e
2481    *          DOCUMENT ME!
2482    */
2483   public void showBoxes_actionPerformed()
2484   {
2485     getGroup().setDisplayBoxes(showBoxes.isSelected());
2486     refresh();
2487   }
2488
2489   /**
2490    * DOCUMENT ME!
2491    * 
2492    * @param e
2493    *          DOCUMENT ME!
2494    */
2495   public void showText_actionPerformed()
2496   {
2497     getGroup().setDisplayText(showText.isSelected());
2498     refresh();
2499   }
2500
2501   /**
2502    * DOCUMENT ME!
2503    * 
2504    * @param e
2505    *          DOCUMENT ME!
2506    */
2507   public void showColourText_actionPerformed()
2508   {
2509     getGroup().setColourText(showColourText.isSelected());
2510     refresh();
2511   }
2512
2513   public void showLink(String url)
2514   {
2515     try
2516     {
2517       jalview.util.BrowserLauncher.openURL(url);
2518     } catch (Exception ex)
2519     {
2520       JOptionPane.showInternalMessageDialog(Desktop.desktop,
2521               MessageManager.getString("label.web_browser_not_found_unix"),
2522               MessageManager.getString("label.web_browser_not_found"),
2523               JOptionPane.WARNING_MESSAGE);
2524
2525       ex.printStackTrace();
2526     }
2527   }
2528
2529   void hideSequences(boolean representGroup)
2530   {
2531     SequenceGroup sg = ap.av.getSelectionGroup();
2532     if (sg == null || sg.getSize() < 1)
2533     {
2534       ap.av.hideSequence(new SequenceI[]
2535       { sequence });
2536       return;
2537     }
2538
2539     ap.av.setSelectionGroup(null);
2540
2541     if (representGroup)
2542     {
2543       ap.av.hideRepSequences(sequence, sg);
2544
2545       return;
2546     }
2547
2548     int gsize = sg.getSize();
2549     SequenceI[] hseqs;
2550
2551     hseqs = new SequenceI[gsize];
2552
2553     int index = 0;
2554     for (int i = 0; i < gsize; i++)
2555     {
2556       hseqs[index++] = sg.getSequenceAt(i);
2557     }
2558
2559     ap.av.hideSequence(hseqs);
2560     // refresh(); TODO: ? needed ?
2561     ap.av.sendSelection();
2562   }
2563
2564   public void copy_actionPerformed()
2565   {
2566     ap.alignFrame.copy_actionPerformed(null);
2567   }
2568
2569   public void cut_actionPerformed()
2570   {
2571     ap.alignFrame.cut_actionPerformed(null);
2572   }
2573
2574   void changeCase(ActionEvent e)
2575   {
2576     Object source = e.getSource();
2577     SequenceGroup sg = ap.av.getSelectionGroup();
2578
2579     if (sg != null)
2580     {
2581       int[][] startEnd = ap.av.getVisibleRegionBoundaries(sg.getStartRes(),
2582               sg.getEndRes() + 1);
2583
2584       String description;
2585       int caseChange;
2586
2587       if (source == toggle)
2588       {
2589         description = MessageManager.getString("label.toggle_case");
2590         caseChange = ChangeCaseCommand.TOGGLE_CASE;
2591       }
2592       else if (source == upperCase)
2593       {
2594         description = MessageManager.getString("label.to_upper_case");
2595         caseChange = ChangeCaseCommand.TO_UPPER;
2596       }
2597       else
2598       {
2599         description = MessageManager.getString("label.to_lower_case");
2600         caseChange = ChangeCaseCommand.TO_LOWER;
2601       }
2602
2603       ChangeCaseCommand caseCommand = new ChangeCaseCommand(description,
2604               sg.getSequencesAsArray(ap.av.getHiddenRepSequences()),
2605               startEnd, caseChange);
2606
2607       ap.alignFrame.addHistoryItem(caseCommand);
2608
2609       ap.av.firePropertyChange("alignment", null, ap.av.getAlignment()
2610               .getSequences());
2611
2612     }
2613   }
2614
2615   public void outputText_actionPerformed(ActionEvent e)
2616   {
2617     CutAndPasteTransfer cap = new CutAndPasteTransfer();
2618     cap.setForInput(null);
2619     Desktop.addInternalFrame(cap, MessageManager.formatMessage(
2620             "label.alignment_output_command", new String[]
2621             { e.getActionCommand() }), 600, 500);
2622
2623     String[] omitHidden = null;
2624
2625     System.out.println("PROMPT USER HERE"); // TODO: decide if a prompt happens
2626     // or we simply trust the user wants
2627     // wysiwig behaviour
2628
2629     cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
2630             ap.av, true));
2631   }
2632
2633   public void pdbFromFile_actionPerformed()
2634   {
2635     jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
2636             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
2637     chooser.setFileView(new jalview.io.JalviewFileView());
2638     chooser.setDialogTitle(MessageManager.formatMessage(
2639             "label.select_pdb_file_for", new String[]
2640             { sequence.getDisplayId(false) }));
2641     chooser.setToolTipText(MessageManager.formatMessage(
2642             "label.load_pdb_file_associate_with_sequence", new String[]
2643             { sequence.getDisplayId(false) }));
2644
2645     int value = chooser.showOpenDialog(null);
2646
2647     if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
2648     {
2649       String choice = chooser.getSelectedFile().getPath();
2650       jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
2651       new AssociatePdbFileWithSeq().associatePdbWithSeq(choice,
2652               jalview.io.AppletFormatAdapter.FILE, sequence, true,
2653               Desktop.instance);
2654     }
2655
2656   }
2657
2658   // JBNote: commented out - these won't be instantiated here...!
2659   // public void RNAFold_actionPerformed() throws Exception
2660   // {
2661   // Predict2D P2D = new Predict2D();
2662   // P2D.getStructure2DFromRNAFold("toto");
2663   // }
2664   //
2665   // public void ContraFold_actionPerformed() throws Exception
2666   // {
2667   // Predict2D P2D = new Predict2D();
2668   // P2D.getStructure2DFromContraFold("toto");
2669   // }
2670   public void enterPDB_actionPerformed()
2671   {
2672     String id = JOptionPane.showInternalInputDialog(Desktop.desktop,
2673             MessageManager.getString("label.enter_pdb_id"),
2674             MessageManager.getString("label.enter_pdb_id"),
2675             JOptionPane.QUESTION_MESSAGE);
2676
2677     if (id != null && id.length() > 0)
2678     {
2679       PDBEntry entry = new PDBEntry();
2680       entry.setId(id.toUpperCase());
2681       sequence.getDatasetSequence().addPDBId(entry);
2682     }
2683   }
2684
2685   public void discoverPDB_actionPerformed()
2686   {
2687
2688     final SequenceI[] sequences = ((ap.av.getSelectionGroup() == null) ? new SequenceI[]
2689     { sequence }
2690             : ap.av.getSequenceSelection());
2691     Thread discpdb = new Thread(new Runnable()
2692     {
2693       @Override
2694       public void run()
2695       {
2696
2697         new jalview.ws.DBRefFetcher(sequences, ap.alignFrame)
2698                 .fetchDBRefs(false);
2699       }
2700
2701     });
2702     discpdb.start();
2703   }
2704
2705   public void sequenceFeature_actionPerformed()
2706   {
2707     SequenceGroup sg = ap.av.getSelectionGroup();
2708     if (sg == null)
2709     {
2710       return;
2711     }
2712
2713     int rsize = 0, gSize = sg.getSize();
2714     SequenceI[] rseqs, seqs = new SequenceI[gSize];
2715     SequenceFeature[] tfeatures, features = new SequenceFeature[gSize];
2716
2717     for (int i = 0; i < gSize; i++)
2718     {
2719       int start = sg.getSequenceAt(i).findPosition(sg.getStartRes());
2720       int end = sg.findEndRes(sg.getSequenceAt(i));
2721       if (start <= end)
2722       {
2723         seqs[rsize] = sg.getSequenceAt(i).getDatasetSequence();
2724         features[rsize] = new SequenceFeature(null, null, null, start, end,
2725                 "Jalview");
2726         rsize++;
2727       }
2728     }
2729     rseqs = new SequenceI[rsize];
2730     tfeatures = new SequenceFeature[rsize];
2731     System.arraycopy(seqs, 0, rseqs, 0, rsize);
2732     System.arraycopy(features, 0, tfeatures, 0, rsize);
2733     features = tfeatures;
2734     seqs = rseqs;
2735     if (ap.getSeqPanel().seqCanvas.getFeatureRenderer().amendFeatures(seqs,
2736             features, true, ap))
2737     {
2738       ap.alignFrame.setShowSeqFeatures(true);
2739       ap.highlightSearchResults(null);
2740     }
2741   }
2742
2743   public void textColour_actionPerformed()
2744   {
2745     SequenceGroup sg = getGroup();
2746     if (sg != null)
2747     {
2748       new TextColourChooser().chooseColour(ap, sg);
2749     }
2750   }
2751
2752   public void colourByStructure(String pdbid)
2753   {
2754     Annotation[] anots = ap.av.getStructureSelectionManager()
2755             .colourSequenceFromStructure(sequence, pdbid);
2756
2757     AlignmentAnnotation an = new AlignmentAnnotation("Structure",
2758             "Coloured by " + pdbid, anots);
2759
2760     ap.av.getAlignment().addAnnotation(an);
2761     an.createSequenceMapping(sequence, 0, true);
2762     // an.adjustForAlignment();
2763     ap.av.getAlignment().setAnnotationIndex(an, 0);
2764
2765     ap.adjustAnnotationHeight();
2766
2767     sequence.addAlignmentAnnotation(an);
2768
2769   }
2770
2771   public void editSequence_actionPerformed(ActionEvent actionEvent)
2772   {
2773     SequenceGroup sg = ap.av.getSelectionGroup();
2774
2775     if (sg != null)
2776     {
2777       if (sequence == null)
2778       {
2779         sequence = sg.getSequenceAt(0);
2780       }
2781
2782       EditNameDialog dialog = new EditNameDialog(
2783               sequence.getSequenceAsString(sg.getStartRes(),
2784                       sg.getEndRes() + 1), null,
2785               MessageManager.getString("label.edit_sequence"), null,
2786               MessageManager.getString("label.edit_sequence"),
2787               ap.alignFrame);
2788
2789       if (dialog.accept)
2790       {
2791         EditCommand editCommand = new EditCommand(
2792                 MessageManager.getString("label.edit_sequences"),
2793                 Action.REPLACE, dialog.getName().replace(' ',
2794                         ap.av.getGapCharacter()),
2795                 sg.getSequencesAsArray(ap.av.getHiddenRepSequences()),
2796                 sg.getStartRes(), sg.getEndRes() + 1, ap.av.getAlignment());
2797
2798         ap.alignFrame.addHistoryItem(editCommand);
2799
2800         ap.av.firePropertyChange("alignment", null, ap.av.getAlignment()
2801                 .getSequences());
2802       }
2803     }
2804   }
2805
2806 }