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