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