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