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