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