Merge branch 'develop' into Jalview-JS/develop
[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       jalview.util.BrowserLauncher.openURL(url);
302     } catch (Exception ex)
303     {
304       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
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
799     JMenu details = new JMenu(
800             MessageManager.getString("label.feature_details"));
801     add(details);
802
803     String name = seq.getName();
804     for (final SequenceFeature sf : features)
805     {
806       addFeatureDetailsMenuItem(details, name, sf);
807     }
808
809     if (mf != null)
810     {
811       name = mf.fromSeq == seq ? mf.mapping.getTo().getName()
812               : mf.fromSeq.getName();
813       for (final SequenceFeature sf : mf.features)
814       {
815         addFeatureDetailsMenuItem(details, name, sf);
816       }
817     }
818   }
819
820   /**
821    * A helper method to add one menu item whose action is to show details for one
822    * feature. The menu text includes feature description, but this may be
823    * truncated.
824    * 
825    * @param details
826    * @param seqName
827    * @param sf
828    */
829   void addFeatureDetailsMenuItem(JMenu details, final String seqName,
830           final SequenceFeature sf)
831   {
832     int start = sf.getBegin();
833     int end = sf.getEnd();
834     StringBuilder desc = new StringBuilder();
835     desc.append(sf.getType()).append(" ").append(String.valueOf(start));
836     if (start != end)
837     {
838       desc.append("-").append(String.valueOf(end));
839     }
840     String description = sf.getDescription();
841     if (description != null)
842     {
843       desc.append(" ");
844       description = StringUtils.stripHtmlTags(description);
845
846       /*
847        * truncate overlong descriptions unless they contain an href
848        * (as truncation could leave corrupted html)
849        */
850       boolean hasLink = description.indexOf("a href") > -1;
851       if (description.length() > FEATURE_DESC_MAX && !hasLink)
852       {
853         description = description.substring(0, FEATURE_DESC_MAX) + "...";
854       }
855       desc.append(description);
856     }
857     String featureGroup = sf.getFeatureGroup();
858     if (featureGroup != null)
859     {
860       desc.append(" (").append(featureGroup).append(")");
861     }
862     String htmlText = JvSwingUtils.wrapTooltip(true, desc.toString());
863     JMenuItem item = new JMenuItem(htmlText);
864     item.addActionListener(new ActionListener()
865     {
866       @Override
867       public void actionPerformed(ActionEvent e)
868       {
869         showFeatureDetails(seqName, sf);
870       }
871     });
872     details.add(item);
873   }
874
875   /**
876    * Opens a panel showing a text report of feature dteails
877    * 
878    * @param seqName
879    * 
880    * @param sf
881    */
882   protected void showFeatureDetails(String seqName, SequenceFeature sf)
883   {
884     JInternalFrame details;
885     if (Platform.isJS())
886     {
887       details = new JInternalFrame();
888       JPanel panel = new JPanel(new BorderLayout());
889       panel.setOpaque(true);
890       panel.setBackground(Color.white);
891       // TODO JAL-3026 set style of table correctly for feature details
892       JLabel reprt = new JLabel(MessageManager
893               .formatMessage("label.html_content", new Object[]
894               { sf.getDetailsReport(seqName) }));
895       reprt.setBackground(Color.WHITE);
896       reprt.setOpaque(true);
897       panel.add(reprt, BorderLayout.CENTER);
898       details.setContentPane(panel);
899       details.pack();
900     }
901     else
902     /**
903      * Java only
904      * 
905      * @j2sIgnore
906      */
907     {
908       CutAndPasteHtmlTransfer cap = new CutAndPasteHtmlTransfer();
909       // it appears Java's CSS does not support border-collaps :-(
910       cap.addStylesheetRule("table { border-collapse: collapse;}");
911       cap.addStylesheetRule("table, td, th {border: 1px solid black;}");
912       cap.setText(sf.getDetailsReport(seqName));
913       details = cap;
914     }
915     Desktop.addInternalFrame(details,
916             MessageManager.getString("label.feature_details"), 500, 500);
917   }
918
919   /**
920    * Adds a 'Link' menu item with a sub-menu item for each hyperlink provided.
921    * When seq is not null, these are links for the sequence id, which may be to
922    * external web sites for the sequence accession, and/or links embedded in
923    * non-positional features. When seq is null, only links embedded in the
924    * provided features are added. If no links are found, the menu is not added.
925    * 
926    * @param seq
927    * @param features
928    */
929   void addLinks(final SequenceI seq, List<SequenceFeature> features)
930   {
931     JMenu linkMenu = buildLinkMenu(forIdPanel ? seq : null, features);
932
933     // only add link menu if it has entries
934     if (linkMenu.getItemCount() > 0)
935     {
936       if (forIdPanel)
937       {
938         sequenceMenu.add(linkMenu);
939       }
940       else
941       {
942         add(linkMenu);
943       }
944     }
945   }
946
947   /**
948    * Add annotation types to 'Show annotations' and/or 'Hide annotations' menus.
949    * "All" is added first, followed by a separator. Then add any annotation
950    * types associated with the current selection. Separate menus are built for
951    * the selected sequence group (if any), and the selected sequence.
952    * <p>
953    * Some annotation rows are always rendered together - these can be identified
954    * by a common graphGroup property > -1. Only one of each group will be marked
955    * as visible (to avoid duplication of the display). For such groups we add a
956    * composite type name, e.g.
957    * <p>
958    * IUPredWS (Long), IUPredWS (Short)
959    * 
960    * @param seq
961    */
962   protected void buildAnnotationTypesMenus(JMenu showMenu, JMenu hideMenu,
963           List<SequenceI> forSequences)
964   {
965     showMenu.removeAll();
966     hideMenu.removeAll();
967
968     final List<String> all = Arrays
969             .asList(new String[]
970             { MessageManager.getString("label.all") });
971     addAnnotationTypeToShowHide(showMenu, forSequences, "", all, true,
972             true);
973     addAnnotationTypeToShowHide(hideMenu, forSequences, "", all, true,
974             false);
975     showMenu.addSeparator();
976     hideMenu.addSeparator();
977
978     final AlignmentAnnotation[] annotations = ap.getAlignment()
979             .getAlignmentAnnotation();
980
981     /*
982      * Find shown/hidden annotations types, distinguished by source (calcId),
983      * and grouped by graphGroup. Using LinkedHashMap means we will retrieve in
984      * the insertion order, which is the order of the annotations on the
985      * alignment.
986      */
987     Map<String, List<List<String>>> shownTypes = new LinkedHashMap<>();
988     Map<String, List<List<String>>> hiddenTypes = new LinkedHashMap<>();
989     AlignmentAnnotationUtils.getShownHiddenTypes(shownTypes, hiddenTypes,
990             AlignmentAnnotationUtils.asList(annotations), forSequences);
991
992     for (String calcId : hiddenTypes.keySet())
993     {
994       for (List<String> type : hiddenTypes.get(calcId))
995       {
996         addAnnotationTypeToShowHide(showMenu, forSequences, calcId, type,
997                 false, true);
998       }
999     }
1000     // grey out 'show annotations' if none are hidden
1001     showMenu.setEnabled(!hiddenTypes.isEmpty());
1002
1003     for (String calcId : shownTypes.keySet())
1004     {
1005       for (List<String> type : shownTypes.get(calcId))
1006       {
1007         addAnnotationTypeToShowHide(hideMenu, forSequences, calcId, type,
1008                 false, false);
1009       }
1010     }
1011     // grey out 'hide annotations' if none are shown
1012     hideMenu.setEnabled(!shownTypes.isEmpty());
1013   }
1014
1015   /**
1016    * Returns a list of sequences - either the current selection group (if there
1017    * is one), else the specified single sequence.
1018    * 
1019    * @param seq
1020    * @return
1021    */
1022   protected List<SequenceI> getSequenceScope(SequenceI seq)
1023   {
1024     List<SequenceI> forSequences = null;
1025     final SequenceGroup selectionGroup = ap.av.getSelectionGroup();
1026     if (selectionGroup != null && selectionGroup.getSize() > 0)
1027     {
1028       forSequences = selectionGroup.getSequences();
1029     }
1030     else
1031     {
1032       forSequences = seq == null ? Collections.<SequenceI> emptyList()
1033               : Arrays.asList(seq);
1034     }
1035     return forSequences;
1036   }
1037
1038   /**
1039    * Add one annotation type to the 'Show Annotations' or 'Hide Annotations'
1040    * menus.
1041    * 
1042    * @param showOrHideMenu
1043    *          the menu to add to
1044    * @param forSequences
1045    *          the sequences whose annotations may be shown or hidden
1046    * @param calcId
1047    * @param types
1048    *          the label to add
1049    * @param allTypes
1050    *          if true this is a special label meaning 'All'
1051    * @param actionIsShow
1052    *          if true, the select menu item action is to show the annotation
1053    *          type, else hide
1054    */
1055   protected void addAnnotationTypeToShowHide(JMenu showOrHideMenu,
1056           final List<SequenceI> forSequences, String calcId,
1057           final List<String> types, final boolean allTypes,
1058           final boolean actionIsShow)
1059   {
1060     String label = types.toString(); // [a, b, c]
1061     label = label.substring(1, label.length() - 1); // a, b, c
1062     final JMenuItem item = new JMenuItem(label);
1063     item.setToolTipText(calcId);
1064     item.addActionListener(new ActionListener()
1065     {
1066       @Override
1067       public void actionPerformed(ActionEvent e)
1068       {
1069         AlignmentUtils.showOrHideSequenceAnnotations(ap.getAlignment(),
1070                 types, forSequences, allTypes, actionIsShow);
1071         refresh();
1072       }
1073     });
1074     showOrHideMenu.add(item);
1075   }
1076
1077   private void buildGroupURLMenu(SequenceGroup sg, List<String> groupLinks)
1078   {
1079
1080     // TODO: usability: thread off the generation of group url content so root
1081     // menu appears asap
1082     // sequence only URLs
1083     // ID/regex match URLs
1084     JMenu groupLinksMenu = new JMenu(
1085             MessageManager.getString("action.group_link"));
1086     // three types of url that might be created.
1087     JMenu[] linkMenus = new JMenu[] { null,
1088         new JMenu(MessageManager.getString("action.ids")),
1089         new JMenu(MessageManager.getString("action.sequences")),
1090         new JMenu(MessageManager.getString("action.ids_sequences")) };
1091
1092     SequenceI[] seqs = ap.av.getSelectionAsNewSequence();
1093     String[][] idandseqs = GroupUrlLink.formStrings(seqs);
1094     Hashtable<String, Object[]> commonDbrefs = new Hashtable<>();
1095     for (int sq = 0; sq < seqs.length; sq++)
1096     {
1097
1098       int start = seqs[sq].findPosition(sg.getStartRes()),
1099               end = seqs[sq].findPosition(sg.getEndRes());
1100       // just collect ids from dataset sequence
1101       // TODO: check if IDs collected from selecton group intersects with the
1102       // current selection, too
1103       SequenceI sqi = seqs[sq];
1104       while (sqi.getDatasetSequence() != null)
1105       {
1106         sqi = sqi.getDatasetSequence();
1107       }
1108       List<DBRefEntry> dbr = sqi.getDBRefs();
1109       int nd;
1110       if (dbr != null && (nd = dbr.size()) > 0)
1111       {
1112         for (int d = 0; d < nd; d++)
1113         {
1114           DBRefEntry e = dbr.get(d);
1115           String src = e.getSource(); // jalview.util.DBRefUtils.getCanonicalName(dbr[d].getSource()).toUpperCase();
1116           Object[] sarray = commonDbrefs.get(src);
1117           if (sarray == null)
1118           {
1119             sarray = new Object[2];
1120             sarray[0] = new int[] { 0 };
1121             sarray[1] = new String[seqs.length];
1122
1123             commonDbrefs.put(src, sarray);
1124           }
1125
1126           if (((String[]) sarray[1])[sq] == null)
1127           {
1128             if (!e.hasMap() || (e.getMap()
1129                     .locateMappedRange(start, end) != null))
1130             {
1131               ((String[]) sarray[1])[sq] = e.getAccessionId();
1132               ((int[]) sarray[0])[0]++;
1133             }
1134           }
1135         }
1136       }
1137     }
1138     // now create group links for all distinct ID/sequence sets.
1139     boolean addMenu = false; // indicates if there are any group links to give
1140                              // to user
1141     for (String link : groupLinks)
1142     {
1143       GroupUrlLink urlLink = null;
1144       try
1145       {
1146         urlLink = new GroupUrlLink(link);
1147       } catch (Exception foo)
1148       {
1149         Cache.log.error("Exception for GroupURLLink '" + link + "'", foo);
1150         continue;
1151       }
1152       if (!urlLink.isValid())
1153       {
1154         Cache.log.error(urlLink.getInvalidMessage());
1155         continue;
1156       }
1157       final String label = urlLink.getLabel();
1158       boolean usingNames = false;
1159       // Now see which parts of the group apply for this URL
1160       String ltarget = urlLink.getTarget(); // jalview.util.DBRefUtils.getCanonicalName(urlLink.getTarget());
1161       Object[] idset = commonDbrefs.get(ltarget.toUpperCase());
1162       String[] seqstr, ids; // input to makeUrl
1163       if (idset != null)
1164       {
1165         int numinput = ((int[]) idset[0])[0];
1166         String[] allids = ((String[]) idset[1]);
1167         seqstr = new String[numinput];
1168         ids = new String[numinput];
1169         for (int sq = 0, idcount = 0; sq < seqs.length; sq++)
1170         {
1171           if (allids[sq] != null)
1172           {
1173             ids[idcount] = allids[sq];
1174             seqstr[idcount++] = idandseqs[1][sq];
1175           }
1176         }
1177       }
1178       else
1179       {
1180         // just use the id/seq set
1181         seqstr = idandseqs[1];
1182         ids = idandseqs[0];
1183         usingNames = true;
1184       }
1185       // and try and make the groupURL!
1186
1187       Object[] urlset = null;
1188       try
1189       {
1190         urlset = urlLink.makeUrlStubs(ids, seqstr,
1191                 "FromJalview" + System.currentTimeMillis(), false);
1192       } catch (UrlStringTooLongException e)
1193       {
1194       }
1195       if (urlset != null)
1196       {
1197         int type = urlLink.getGroupURLType() & 3;
1198         // first two bits ofurlLink type bitfield are sequenceids and sequences
1199         // TODO: FUTURE: ensure the groupURL menu structure can be generalised
1200         addshowLink(linkMenus[type],
1201                 label + (((type & 1) == 1)
1202                         ? ("(" + (usingNames ? "Names" : ltarget) + ")")
1203                         : ""),
1204                 urlLink, urlset);
1205         addMenu = true;
1206       }
1207     }
1208     if (addMenu)
1209     {
1210       groupLinksMenu = new JMenu(
1211               MessageManager.getString("action.group_link"));
1212       for (int m = 0; m < linkMenus.length; m++)
1213       {
1214         if (linkMenus[m] != null
1215                 && linkMenus[m].getMenuComponentCount() > 0)
1216         {
1217           groupLinksMenu.add(linkMenus[m]);
1218         }
1219       }
1220
1221       groupMenu.add(groupLinksMenu);
1222     }
1223   }
1224
1225   /**
1226    * DOCUMENT ME!
1227    * 
1228    * @throws Exception
1229    *           DOCUMENT ME!
1230    */
1231   private void jbInit() throws Exception
1232   {
1233     groupMenu.setText(MessageManager.getString("label.selection"));
1234     groupName.setText(MessageManager.getString("label.name"));
1235     groupName.addActionListener(new ActionListener()
1236     {
1237       @Override
1238       public void actionPerformed(ActionEvent e)
1239       {
1240         groupName_actionPerformed();
1241       }
1242     });
1243     sequenceMenu.setText(MessageManager.getString("label.sequence"));
1244
1245     JMenuItem sequenceName = new JMenuItem(
1246             MessageManager.getString("label.edit_name_description"));
1247     sequenceName.addActionListener(new ActionListener()
1248     {
1249       @Override
1250       public void actionPerformed(ActionEvent e)
1251       {
1252         sequenceName_actionPerformed();
1253       }
1254     });
1255     JMenuItem chooseAnnotations = new JMenuItem(
1256             MessageManager.getString("action.choose_annotations"));
1257     chooseAnnotations.addActionListener(new ActionListener()
1258     {
1259       @Override
1260       public void actionPerformed(ActionEvent e)
1261       {
1262         chooseAnnotations_actionPerformed(e);
1263       }
1264     });
1265     JMenuItem sequenceDetails = new JMenuItem(
1266             MessageManager.getString("label.sequence_details"));
1267     sequenceDetails.addActionListener(new ActionListener()
1268     {
1269       @Override
1270       public void actionPerformed(ActionEvent e)
1271       {
1272         createSequenceDetailsReport(new SequenceI[] { sequence });
1273       }
1274     });
1275     JMenuItem sequenceSelDetails = new JMenuItem(
1276             MessageManager.getString("label.sequence_details"));
1277     sequenceSelDetails.addActionListener(new ActionListener()
1278     {
1279       @Override
1280       public void actionPerformed(ActionEvent e)
1281       {
1282         createSequenceDetailsReport(ap.av.getSequenceSelection());
1283       }
1284     });
1285
1286     unGroupMenuItem
1287             .setText(MessageManager.getString("action.remove_group"));
1288     unGroupMenuItem.addActionListener(new ActionListener()
1289     {
1290       @Override
1291       public void actionPerformed(ActionEvent e)
1292       {
1293         unGroupMenuItem_actionPerformed();
1294       }
1295     });
1296     createGroupMenuItem
1297             .setText(MessageManager.getString("action.create_group"));
1298     createGroupMenuItem.addActionListener(new ActionListener()
1299     {
1300       @Override
1301       public void actionPerformed(ActionEvent e)
1302       {
1303         createGroupMenuItem_actionPerformed();
1304       }
1305     });
1306
1307     JMenuItem outline = new JMenuItem(
1308             MessageManager.getString("action.border_colour"));
1309     outline.addActionListener(new ActionListener()
1310     {
1311       @Override
1312       public void actionPerformed(ActionEvent e)
1313       {
1314         outline_actionPerformed();
1315       }
1316     });
1317     showBoxes.setText(MessageManager.getString("action.boxes"));
1318     showBoxes.setState(true);
1319     showBoxes.addActionListener(new ActionListener()
1320     {
1321       @Override
1322       public void actionPerformed(ActionEvent e)
1323       {
1324         showBoxes_actionPerformed();
1325       }
1326     });
1327     showText.setText(MessageManager.getString("action.text"));
1328     showText.setState(true);
1329     showText.addActionListener(new ActionListener()
1330     {
1331       @Override
1332       public void actionPerformed(ActionEvent e)
1333       {
1334         showText_actionPerformed();
1335       }
1336     });
1337     showColourText.setText(MessageManager.getString("label.colour_text"));
1338     showColourText.addActionListener(new ActionListener()
1339     {
1340       @Override
1341       public void actionPerformed(ActionEvent e)
1342       {
1343         showColourText_actionPerformed();
1344       }
1345     });
1346     displayNonconserved
1347             .setText(MessageManager.getString("label.show_non_conserved"));
1348     displayNonconserved.setState(true);
1349     displayNonconserved.addActionListener(new ActionListener()
1350     {
1351       @Override
1352       public void actionPerformed(ActionEvent e)
1353       {
1354         showNonconserved_actionPerformed();
1355       }
1356     });
1357     editMenu.setText(MessageManager.getString("action.edit"));
1358     JMenuItem cut = new JMenuItem(MessageManager.getString("action.cut"));
1359     cut.addActionListener(new ActionListener()
1360     {
1361       @Override
1362       public void actionPerformed(ActionEvent e)
1363       {
1364         cut_actionPerformed();
1365       }
1366     });
1367     upperCase.setText(MessageManager.getString("label.to_upper_case"));
1368     upperCase.addActionListener(new ActionListener()
1369     {
1370       @Override
1371       public void actionPerformed(ActionEvent e)
1372       {
1373         changeCase(e);
1374       }
1375     });
1376     JMenuItem copy = new JMenuItem(MessageManager.getString("action.copy"));
1377     copy.addActionListener(new ActionListener()
1378     {
1379       @Override
1380       public void actionPerformed(ActionEvent e)
1381       {
1382         copy_actionPerformed();
1383       }
1384     });
1385     lowerCase.setText(MessageManager.getString("label.to_lower_case"));
1386     lowerCase.addActionListener(new ActionListener()
1387     {
1388       @Override
1389       public void actionPerformed(ActionEvent e)
1390       {
1391         changeCase(e);
1392       }
1393     });
1394     toggle.setText(MessageManager.getString("label.toggle_case"));
1395     toggle.addActionListener(new ActionListener()
1396     {
1397       @Override
1398       public void actionPerformed(ActionEvent e)
1399       {
1400         changeCase(e);
1401       }
1402     });
1403     outputMenu.setText(
1404             MessageManager.getString("label.out_to_textbox") + "...");
1405     seqShowAnnotationsMenu
1406             .setText(MessageManager.getString("label.show_annotations"));
1407     seqHideAnnotationsMenu
1408             .setText(MessageManager.getString("label.hide_annotations"));
1409     groupShowAnnotationsMenu
1410             .setText(MessageManager.getString("label.show_annotations"));
1411     groupHideAnnotationsMenu
1412             .setText(MessageManager.getString("label.hide_annotations"));
1413     JMenuItem sequenceFeature = new JMenuItem(
1414             MessageManager.getString("label.create_sequence_feature"));
1415     sequenceFeature.addActionListener(new ActionListener()
1416     {
1417       @Override
1418       public void actionPerformed(ActionEvent e)
1419       {
1420         sequenceFeature_actionPerformed();
1421       }
1422     });
1423     editGroupMenu.setText(MessageManager.getString("label.group"));
1424     chooseStructure.setText(
1425             MessageManager.getString("label.show_pdbstruct_dialog"));
1426     chooseStructure.addActionListener(new ActionListener()
1427     {
1428       @Override
1429       public void actionPerformed(ActionEvent actionEvent)
1430       {
1431         SequenceI[] selectedSeqs = new SequenceI[] { sequence };
1432         if (ap.av.getSelectionGroup() != null)
1433         {
1434           selectedSeqs = ap.av.getSequenceSelection();
1435         }
1436         new StructureChooser(selectedSeqs, sequence, ap);
1437       }
1438     });
1439
1440     rnaStructureMenu
1441             .setText(MessageManager.getString("label.view_rna_structure"));
1442
1443     // colStructureMenu.setText("Colour By Structure");
1444     JMenuItem editSequence = new JMenuItem(
1445             MessageManager.getString("label.edit_sequence") + "...");
1446     editSequence.addActionListener(new ActionListener()
1447     {
1448       @Override
1449       public void actionPerformed(ActionEvent actionEvent)
1450       {
1451         editSequence_actionPerformed();
1452       }
1453     });
1454     makeReferenceSeq.setText(
1455             MessageManager.getString("label.mark_as_representative"));
1456     makeReferenceSeq.addActionListener(new ActionListener()
1457     {
1458
1459       @Override
1460       public void actionPerformed(ActionEvent actionEvent)
1461       {
1462         makeReferenceSeq_actionPerformed(actionEvent);
1463
1464       }
1465     });
1466
1467     groupMenu.add(sequenceSelDetails);
1468     add(groupMenu);
1469     add(sequenceMenu);
1470     add(rnaStructureMenu);
1471     add(chooseStructure);
1472     if (forIdPanel)
1473     {
1474       JMenuItem hideInsertions = new JMenuItem(
1475               MessageManager.getString("label.hide_insertions"));
1476       hideInsertions.addActionListener(new ActionListener()
1477       {
1478
1479         @Override
1480         public void actionPerformed(ActionEvent e)
1481         {
1482           hideInsertions_actionPerformed(e);
1483         }
1484       });
1485       add(hideInsertions);
1486     }
1487     // annotations configuration panel suppressed for now
1488     // groupMenu.add(chooseAnnotations);
1489
1490     /*
1491      * Add show/hide annotations to the Sequence menu, and to the Selection menu
1492      * (if a selection group is in force).
1493      */
1494     sequenceMenu.add(seqShowAnnotationsMenu);
1495     sequenceMenu.add(seqHideAnnotationsMenu);
1496     sequenceMenu.add(seqAddReferenceAnnotations);
1497     groupMenu.add(groupShowAnnotationsMenu);
1498     groupMenu.add(groupHideAnnotationsMenu);
1499     groupMenu.add(groupAddReferenceAnnotations);
1500     groupMenu.add(editMenu);
1501     groupMenu.add(outputMenu);
1502     groupMenu.add(sequenceFeature);
1503     groupMenu.add(createGroupMenuItem);
1504     groupMenu.add(unGroupMenuItem);
1505     groupMenu.add(editGroupMenu);
1506     sequenceMenu.add(sequenceName);
1507     sequenceMenu.add(sequenceDetails);
1508     sequenceMenu.add(makeReferenceSeq);
1509
1510     initColourMenu();
1511     buildColourMenu();
1512
1513     editMenu.add(copy);
1514     editMenu.add(cut);
1515     editMenu.add(editSequence);
1516     editMenu.add(upperCase);
1517     editMenu.add(lowerCase);
1518     editMenu.add(toggle);
1519     editGroupMenu.add(groupName);
1520     editGroupMenu.add(colourMenu);
1521     editGroupMenu.add(showBoxes);
1522     editGroupMenu.add(showText);
1523     editGroupMenu.add(showColourText);
1524     editGroupMenu.add(outline);
1525     editGroupMenu.add(displayNonconserved);
1526   }
1527
1528   /**
1529    * Constructs the entries for the colour menu
1530    */
1531   protected void initColourMenu()
1532   {
1533     colourMenu.setText(MessageManager.getString("label.group_colour"));
1534     textColour.setText(MessageManager.getString("label.text_colour"));
1535     textColour.addActionListener(new ActionListener()
1536     {
1537       @Override
1538       public void actionPerformed(ActionEvent e)
1539       {
1540         textColour_actionPerformed();
1541       }
1542     });
1543
1544     abovePIDColour.setText(
1545             MessageManager.getString("label.above_identity_threshold"));
1546     abovePIDColour.addActionListener(new ActionListener()
1547     {
1548       @Override
1549       public void actionPerformed(ActionEvent e)
1550       {
1551         abovePIDColour_actionPerformed(abovePIDColour.isSelected());
1552       }
1553     });
1554
1555     modifyPID.setText(
1556             MessageManager.getString("label.modify_identity_threshold"));
1557     modifyPID.addActionListener(new ActionListener()
1558     {
1559       @Override
1560       public void actionPerformed(ActionEvent e)
1561       {
1562         modifyPID_actionPerformed();
1563       }
1564     });
1565
1566     conservationMenuItem
1567             .setText(MessageManager.getString("action.by_conservation"));
1568     conservationMenuItem.addActionListener(new ActionListener()
1569     {
1570       @Override
1571       public void actionPerformed(ActionEvent e)
1572       {
1573         conservationMenuItem_actionPerformed(
1574                 conservationMenuItem.isSelected());
1575       }
1576     });
1577
1578     annotationColour = new JRadioButtonMenuItem(
1579             MessageManager.getString("action.by_annotation"));
1580     annotationColour.setName(ResidueColourScheme.ANNOTATION_COLOUR);
1581     annotationColour.setEnabled(false);
1582     annotationColour.setToolTipText(
1583             MessageManager.getString("label.by_annotation_tooltip"));
1584
1585     modifyConservation.setText(MessageManager
1586             .getString("label.modify_conservation_threshold"));
1587     modifyConservation.addActionListener(new ActionListener()
1588     {
1589       @Override
1590       public void actionPerformed(ActionEvent e)
1591       {
1592         modifyConservation_actionPerformed();
1593       }
1594     });
1595   }
1596
1597   /**
1598    * Builds the group colour sub-menu, including any user-defined colours which
1599    * were loaded at startup or during the Jalview session
1600    */
1601   protected void buildColourMenu()
1602   {
1603     SequenceGroup sg = ap.av.getSelectionGroup();
1604     if (sg == null)
1605     {
1606       /*
1607        * popup menu with no sequence group scope
1608        */
1609       return;
1610     }
1611     colourMenu.removeAll();
1612     colourMenu.add(textColour);
1613     colourMenu.addSeparator();
1614
1615     ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this, sg,
1616             false);
1617     bg.add(annotationColour);
1618     colourMenu.add(annotationColour);
1619
1620     colourMenu.addSeparator();
1621     colourMenu.add(conservationMenuItem);
1622     colourMenu.add(modifyConservation);
1623     colourMenu.add(abovePIDColour);
1624     colourMenu.add(modifyPID);
1625   }
1626
1627   protected void modifyConservation_actionPerformed()
1628   {
1629     SequenceGroup sg = getGroup();
1630     if (sg.cs != null)
1631     {
1632       SliderPanel.setConservationSlider(ap, sg.cs, sg.getName());
1633       SliderPanel.showConservationSlider();
1634     }
1635   }
1636
1637   protected void modifyPID_actionPerformed()
1638   {
1639     SequenceGroup sg = getGroup();
1640     if (sg.cs != null)
1641     {
1642       // int threshold = SliderPanel.setPIDSliderSource(ap, sg.cs, getGroup()
1643       // .getName());
1644       // sg.cs.setThreshold(threshold, ap.av.isIgnoreGapsConsensus());
1645       SliderPanel.setPIDSliderSource(ap, sg.cs, getGroup().getName());
1646       SliderPanel.showPIDSlider();
1647     }
1648   }
1649
1650   /**
1651    * Check for any annotations on the underlying dataset sequences (for the
1652    * current selection group) which are not 'on the alignment'.If any are found,
1653    * enable the option to add them to the alignment. The criteria for 'on the
1654    * alignment' is finding an alignment annotation on the alignment, matched on
1655    * calcId, label and sequenceRef.
1656    * 
1657    * A tooltip is also constructed that displays the source (calcId) and type
1658    * (label) of the annotations that can be added.
1659    * 
1660    * @param menuItem
1661    * @param forSequences
1662    */
1663   protected void configureReferenceAnnotationsMenu(JMenuItem menuItem,
1664           List<SequenceI> forSequences)
1665   {
1666     menuItem.setEnabled(false);
1667
1668     /*
1669      * Temporary store to hold distinct calcId / type pairs for the tooltip.
1670      * Using TreeMap means calcIds are shown in alphabetical order.
1671      */
1672     SortedMap<String, String> tipEntries = new TreeMap<>();
1673     final Map<SequenceI, List<AlignmentAnnotation>> candidates = new LinkedHashMap<>();
1674     AlignmentI al = this.ap.av.getAlignment();
1675     AlignmentUtils.findAddableReferenceAnnotations(forSequences, tipEntries,
1676             candidates, al);
1677     if (!candidates.isEmpty())
1678     {
1679       StringBuilder tooltip = new StringBuilder(64);
1680       tooltip.append(MessageManager.getString("label.add_annotations_for"));
1681
1682       /*
1683        * Found annotations that could be added. Enable the menu item, and
1684        * configure its tooltip and action.
1685        */
1686       menuItem.setEnabled(true);
1687       for (String calcId : tipEntries.keySet())
1688       {
1689         tooltip.append("<br/>" + calcId + "/" + tipEntries.get(calcId));
1690       }
1691       String tooltipText = JvSwingUtils.wrapTooltip(true,
1692               tooltip.toString());
1693       menuItem.setToolTipText(tooltipText);
1694
1695       menuItem.addActionListener(new ActionListener()
1696       {
1697         @Override
1698         public void actionPerformed(ActionEvent e)
1699         {
1700           addReferenceAnnotations_actionPerformed(candidates);
1701         }
1702       });
1703     }
1704   }
1705
1706   /**
1707    * Add annotations to the sequences and to the alignment.
1708    * 
1709    * @param candidates
1710    *          a map whose keys are sequences on the alignment, and values a list
1711    *          of annotations to add to each sequence
1712    */
1713   protected void addReferenceAnnotations_actionPerformed(
1714           Map<SequenceI, List<AlignmentAnnotation>> candidates)
1715   {
1716     final SequenceGroup selectionGroup = this.ap.av.getSelectionGroup();
1717     final AlignmentI alignment = this.ap.getAlignment();
1718     AlignmentUtils.addReferenceAnnotations(candidates, alignment,
1719             selectionGroup);
1720     refresh();
1721   }
1722
1723   protected void makeReferenceSeq_actionPerformed(ActionEvent actionEvent)
1724   {
1725     if (!ap.av.getAlignment().hasSeqrep())
1726     {
1727       // initialise the display flags so the user sees something happen
1728       ap.av.setDisplayReferenceSeq(true);
1729       ap.av.setColourByReferenceSeq(true);
1730       ap.av.getAlignment().setSeqrep(sequence);
1731     }
1732     else
1733     {
1734       if (ap.av.getAlignment().getSeqrep() == sequence)
1735       {
1736         ap.av.getAlignment().setSeqrep(null);
1737       }
1738       else
1739       {
1740         ap.av.getAlignment().setSeqrep(sequence);
1741       }
1742     }
1743     refresh();
1744   }
1745
1746   protected void hideInsertions_actionPerformed(ActionEvent actionEvent)
1747   {
1748     HiddenColumns hidden = ap.av.getAlignment().getHiddenColumns();
1749     BitSet inserts = new BitSet();
1750
1751     boolean markedPopup = false;
1752     // mark inserts in current selection
1753     if (ap.av.getSelectionGroup() != null)
1754     {
1755       // mark just the columns in the selection group to be hidden
1756       inserts.set(ap.av.getSelectionGroup().getStartRes(),
1757               ap.av.getSelectionGroup().getEndRes() + 1); // TODO why +1?
1758
1759       // now clear columns without gaps
1760       for (SequenceI sq : ap.av.getSelectionGroup().getSequences())
1761       {
1762         if (sq == sequence)
1763         {
1764           markedPopup = true;
1765         }
1766         inserts.and(sq.getInsertionsAsBits());
1767       }
1768       hidden.clearAndHideColumns(inserts, ap.av.getSelectionGroup().getStartRes(),
1769               ap.av.getSelectionGroup().getEndRes());
1770     }
1771
1772     // now mark for sequence under popup if we haven't already done it
1773     else if (!markedPopup && sequence != null)
1774     {
1775       inserts.or(sequence.getInsertionsAsBits());
1776
1777       // and set hidden columns accordingly
1778       hidden.hideColumns(inserts);
1779     }
1780     refresh();
1781   }
1782
1783   protected void sequenceSelectionDetails_actionPerformed()
1784   {
1785     createSequenceDetailsReport(ap.av.getSequenceSelection());
1786   }
1787
1788   public void createSequenceDetailsReport(SequenceI[] sequences)
1789   {
1790     StringBuilder contents = new StringBuilder(128);
1791     contents.append("<html><body>");
1792     for (SequenceI seq : sequences)
1793     {
1794       contents.append("<p><h2>" + MessageManager.formatMessage(
1795               "label.create_sequence_details_report_annotation_for",
1796               new Object[]
1797               { seq.getDisplayId(true) }) + "</h2></p><p>");
1798       new SequenceAnnotationReport(null).createSequenceAnnotationReport(
1799               contents, seq, true, true, ap.getSeqPanel().seqCanvas.fr);
1800       contents.append("</p>");
1801     }
1802     contents.append("</body></html>");
1803     String report = contents.toString();
1804
1805     JInternalFrame frame;
1806     if (Platform.isJS())
1807     {
1808       JLabel textLabel = new JLabel();
1809       textLabel.setText(report);
1810       textLabel.setBackground(Color.WHITE);
1811       JPanel pane = new JPanel(new BorderLayout());
1812       pane.setOpaque(true);
1813       pane.setBackground(Color.WHITE);
1814       pane.add(textLabel, BorderLayout.NORTH);
1815       frame = new JInternalFrame();
1816       frame.getContentPane().add(new JScrollPane(pane));
1817     }
1818     else
1819     /**
1820      * Java only
1821      * 
1822      * @j2sIgnore
1823      */
1824     {
1825       CutAndPasteHtmlTransfer cap = new CutAndPasteHtmlTransfer();
1826       cap.setText(report);
1827       frame = cap;
1828     }
1829
1830     Desktop.addInternalFrame(frame,
1831             MessageManager.formatMessage("label.sequence_details_for",
1832                     (sequences.length == 1 ? new Object[]
1833                     { sequences[0].getDisplayId(true) }
1834                             : new Object[]
1835                             { MessageManager
1836                                     .getString("label.selection") })),
1837             500, 400);
1838   }
1839
1840   protected void showNonconserved_actionPerformed()
1841   {
1842     getGroup().setShowNonconserved(displayNonconserved.isSelected());
1843     refresh();
1844   }
1845
1846   /**
1847    * call to refresh view after settings change
1848    */
1849   void refresh()
1850   {
1851     ap.updateAnnotation();
1852     // removed paintAlignment(true) here:
1853     // updateAnnotation calls paintAlignment already, so don't need to call
1854     // again
1855
1856     PaintRefresher.Refresh(this, ap.av.getSequenceSetId());
1857   }
1858
1859   /*
1860    * protected void covariationColour_actionPerformed() { getGroup().cs = new
1861    * CovariationColourScheme(sequence.getAnnotation()[0]); refresh(); }
1862    */
1863   /**
1864    * DOCUMENT ME!
1865    * 
1866    * @param selected
1867    * 
1868    * @param e
1869    *          DOCUMENT ME!
1870    */
1871   public void abovePIDColour_actionPerformed(boolean selected)
1872   {
1873     SequenceGroup sg = getGroup();
1874     if (sg.cs == null)
1875     {
1876       return;
1877     }
1878
1879     if (selected)
1880     {
1881       sg.cs.setConsensus(AAFrequency.calculate(
1882               sg.getSequences(ap.av.getHiddenRepSequences()),
1883               sg.getStartRes(), sg.getEndRes() + 1));
1884
1885       int threshold = SliderPanel.setPIDSliderSource(ap,
1886               sg.getGroupColourScheme(), getGroup().getName());
1887
1888       sg.cs.setThreshold(threshold, ap.av.isIgnoreGapsConsensus());
1889
1890       SliderPanel.showPIDSlider();
1891     }
1892     else
1893     // remove PIDColouring
1894     {
1895       sg.cs.setThreshold(0, ap.av.isIgnoreGapsConsensus());
1896       SliderPanel.hidePIDSlider();
1897     }
1898     modifyPID.setEnabled(selected);
1899
1900     refresh();
1901   }
1902
1903   /**
1904    * Open a panel where the user can choose which types of sequence annotation
1905    * to show or hide.
1906    * 
1907    * @param e
1908    */
1909   protected void chooseAnnotations_actionPerformed(ActionEvent e)
1910   {
1911     // todo correct way to guard against opening a duplicate panel?
1912     new AnnotationChooser(ap);
1913   }
1914
1915   /**
1916    * DOCUMENT ME!
1917    * 
1918    * @param e
1919    *          DOCUMENT ME!
1920    */
1921   public void conservationMenuItem_actionPerformed(boolean selected)
1922   {
1923     SequenceGroup sg = getGroup();
1924     if (sg.cs == null)
1925     {
1926       return;
1927     }
1928
1929     if (selected)
1930     {
1931       // JBPNote: Conservation name shouldn't be i18n translated
1932       Conservation c = new Conservation("Group",
1933               sg.getSequences(ap.av.getHiddenRepSequences()),
1934               sg.getStartRes(), sg.getEndRes() + 1);
1935
1936       c.calculate();
1937       c.verdict(false, ap.av.getConsPercGaps());
1938       sg.cs.setConservation(c);
1939
1940       SliderPanel.setConservationSlider(ap, sg.getGroupColourScheme(),
1941               sg.getName());
1942       SliderPanel.showConservationSlider();
1943     }
1944     else
1945     // remove ConservationColouring
1946     {
1947       sg.cs.setConservation(null);
1948       SliderPanel.hideConservationSlider();
1949     }
1950     modifyConservation.setEnabled(selected);
1951
1952     refresh();
1953   }
1954
1955   /**
1956    * Shows a dialog where group name and description may be edited
1957    */
1958   protected void groupName_actionPerformed()
1959   {
1960     SequenceGroup sg = getGroup();
1961     EditNameDialog dialog = new EditNameDialog(sg.getName(),
1962             sg.getDescription(),
1963             MessageManager.getString("label.group_name"),
1964             MessageManager.getString("label.group_description"));
1965     dialog.showDialog(ap.alignFrame,
1966             MessageManager.getString("label.edit_group_name_description"),
1967             new Runnable()
1968             {
1969               @Override
1970               public void run()
1971               {
1972                 sg.setName(dialog.getName());
1973                 sg.setDescription(dialog.getDescription());
1974                 refresh();
1975               }
1976             });
1977   }
1978
1979   /**
1980    * Get selection group - adding it to the alignment if necessary.
1981    * 
1982    * @return sequence group to operate on
1983    */
1984   SequenceGroup getGroup()
1985   {
1986     SequenceGroup sg = ap.av.getSelectionGroup();
1987     // this method won't add a new group if it already exists
1988     if (sg != null)
1989     {
1990       ap.av.getAlignment().addGroup(sg);
1991     }
1992
1993     return sg;
1994   }
1995
1996   /**
1997    * Shows a dialog where the sequence name and description may be edited. If a
1998    * name containing spaces is entered, these are converted to underscores, with a
1999    * warning message.
2000    */
2001   void sequenceName_actionPerformed()
2002   {
2003     EditNameDialog dialog = new EditNameDialog(sequence.getName(),
2004             sequence.getDescription(),
2005             MessageManager.getString("label.sequence_name"),
2006             MessageManager.getString("label.sequence_description"));
2007     dialog.showDialog(ap.alignFrame,
2008             MessageManager.getString(
2009                     "label.edit_sequence_name_description"),
2010             new Runnable()
2011             {
2012               @Override
2013               public void run()
2014               {
2015                 if (dialog.getName() != null)
2016                 {
2017                   if (dialog.getName().indexOf(" ") > -1)
2018                   {
2019                     JvOptionPane.showMessageDialog(ap,
2020                             MessageManager.getString(
2021                                     "label.spaces_converted_to_underscores"),
2022                             MessageManager.getString(
2023                                     "label.no_spaces_allowed_sequence_name"),
2024                             JvOptionPane.WARNING_MESSAGE);
2025                   }
2026                   sequence.setName(dialog.getName().replace(' ', '_'));
2027                   ap.paintAlignment(false, false);
2028                 }
2029                 sequence.setDescription(dialog.getDescription());
2030                 ap.av.firePropertyChange("alignment", null,
2031                         ap.av.getAlignment().getSequences());
2032               }
2033             });
2034   }
2035
2036   /**
2037    * DOCUMENT ME!
2038    * 
2039    * @param e
2040    *          DOCUMENT ME!
2041    */
2042   void unGroupMenuItem_actionPerformed()
2043   {
2044     SequenceGroup sg = ap.av.getSelectionGroup();
2045     ap.av.getAlignment().deleteGroup(sg);
2046     ap.av.setSelectionGroup(null);
2047     refresh();
2048   }
2049
2050   void createGroupMenuItem_actionPerformed()
2051   {
2052     getGroup(); // implicitly creates group - note - should apply defaults / use
2053                 // standard alignment window logic for this
2054     refresh();
2055   }
2056
2057   /**
2058    * Offers a colour chooser and sets the selected colour as the group outline
2059    */
2060   protected void outline_actionPerformed()
2061   {
2062     String title = MessageManager
2063             .getString("label.select_outline_colour");
2064     ColourChooserListener listener = new ColourChooserListener()
2065     {
2066       @Override
2067       public void colourSelected(Color c)
2068       {
2069         getGroup().setOutlineColour(c);
2070         refresh();
2071       }
2072     };
2073     JalviewColourChooser.showColourChooser(Desktop.getDesktop(),
2074             title, Color.BLUE, listener);
2075   }
2076
2077   /**
2078    * DOCUMENT ME!
2079    * 
2080    * @param e
2081    *          DOCUMENT ME!
2082    */
2083   public void showBoxes_actionPerformed()
2084   {
2085     getGroup().setDisplayBoxes(showBoxes.isSelected());
2086     refresh();
2087   }
2088
2089   /**
2090    * DOCUMENT ME!
2091    * 
2092    * @param e
2093    *          DOCUMENT ME!
2094    */
2095   public void showText_actionPerformed()
2096   {
2097     getGroup().setDisplayText(showText.isSelected());
2098     refresh();
2099   }
2100
2101   /**
2102    * DOCUMENT ME!
2103    * 
2104    * @param e
2105    *          DOCUMENT ME!
2106    */
2107   public void showColourText_actionPerformed()
2108   {
2109     getGroup().setColourText(showColourText.isSelected());
2110     refresh();
2111   }
2112
2113   void hideSequences(boolean representGroup)
2114   {
2115     ap.av.hideSequences(sequence, representGroup);
2116   }
2117
2118   public void copy_actionPerformed()
2119   {
2120     ap.alignFrame.copy_actionPerformed();
2121   }
2122
2123   public void cut_actionPerformed()
2124   {
2125     ap.alignFrame.cut_actionPerformed();
2126   }
2127
2128   void changeCase(ActionEvent e)
2129   {
2130     Object source = e.getSource();
2131     SequenceGroup sg = ap.av.getSelectionGroup();
2132
2133     if (sg != null)
2134     {
2135       List<int[]> startEnd = ap.av.getVisibleRegionBoundaries(
2136               sg.getStartRes(), sg.getEndRes() + 1);
2137
2138       String description;
2139       int caseChange;
2140
2141       if (source == toggle)
2142       {
2143         description = MessageManager.getString("label.toggle_case");
2144         caseChange = ChangeCaseCommand.TOGGLE_CASE;
2145       }
2146       else if (source == upperCase)
2147       {
2148         description = MessageManager.getString("label.to_upper_case");
2149         caseChange = ChangeCaseCommand.TO_UPPER;
2150       }
2151       else
2152       {
2153         description = MessageManager.getString("label.to_lower_case");
2154         caseChange = ChangeCaseCommand.TO_LOWER;
2155       }
2156
2157       ChangeCaseCommand caseCommand = new ChangeCaseCommand(description,
2158               sg.getSequencesAsArray(ap.av.getHiddenRepSequences()),
2159               startEnd, caseChange);
2160
2161       ap.alignFrame.addHistoryItem(caseCommand);
2162
2163       ap.av.firePropertyChange("alignment", null,
2164               ap.av.getAlignment().getSequences());
2165
2166     }
2167   }
2168
2169   public void outputText_actionPerformed(ActionEvent e)
2170   {
2171     CutAndPasteTransfer cap = new CutAndPasteTransfer();
2172     cap.setForInput(null);
2173     Desktop.addInternalFrame(cap, MessageManager
2174             .formatMessage("label.alignment_output_command", new Object[]
2175             { e.getActionCommand() }), 600, 500);
2176
2177     String[] omitHidden = null;
2178
2179     System.out.println("PROMPT USER HERE"); // TODO: decide if a prompt happens
2180     // or we simply trust the user wants
2181     // wysiwig behaviour
2182
2183     FileFormatI fileFormat = FileFormats.getInstance()
2184             .forName(e.getActionCommand());
2185     cap.setText(
2186             new FormatAdapter(ap).formatSequences(fileFormat, ap, true));
2187   }
2188
2189   public void sequenceFeature_actionPerformed()
2190   {
2191     SequenceGroup sg = ap.av.getSelectionGroup();
2192     if (sg == null)
2193     {
2194       return;
2195     }
2196
2197     List<SequenceI> seqs = new ArrayList<>();
2198     List<SequenceFeature> features = new ArrayList<>();
2199
2200     /*
2201      * assemble dataset sequences, and template new sequence features,
2202      * for the amend features dialog
2203      */
2204     int gSize = sg.getSize();
2205     for (int i = 0; i < gSize; i++)
2206     {
2207       int start = sg.getSequenceAt(i).findPosition(sg.getStartRes());
2208       int end = sg.findEndRes(sg.getSequenceAt(i));
2209       if (start <= end)
2210       {
2211         seqs.add(sg.getSequenceAt(i).getDatasetSequence());
2212         features.add(new SequenceFeature(null, null, start, end, null));
2213       }
2214     }
2215
2216     /*
2217      * an entirely gapped region will generate empty lists of sequence / features
2218      */
2219     if (!seqs.isEmpty())
2220     {
2221       new FeatureEditor(ap, seqs, features, true).showDialog();
2222     }
2223   }
2224
2225   public void textColour_actionPerformed()
2226   {
2227     SequenceGroup sg = getGroup();
2228     if (sg != null)
2229     {
2230       new TextColourChooser().chooseColour(ap, sg);
2231     }
2232   }
2233
2234   /**
2235    * Shows a dialog where sequence characters may be edited. Any changes are
2236    * applied, and added as an available 'Undo' item in the edit commands
2237    * history.
2238    */
2239   public void editSequence_actionPerformed()
2240   {
2241     SequenceGroup sg = ap.av.getSelectionGroup();
2242
2243     SequenceI seq = sequence;
2244     if (sg != null)
2245     {
2246       if (seq == null)
2247       {
2248         seq = sg.getSequenceAt(0);
2249       }
2250
2251       EditNameDialog dialog = new EditNameDialog(
2252               seq.getSequenceAsString(sg.getStartRes(), sg.getEndRes() + 1),
2253               null, MessageManager.getString("label.edit_sequence"), null);
2254       dialog.showDialog(ap.alignFrame,
2255               MessageManager.getString("label.edit_sequence"),
2256               new Runnable()
2257               {
2258                 @Override
2259                 public void run()
2260                 {
2261                   EditCommand editCommand = new EditCommand(
2262                           MessageManager.getString("label.edit_sequences"),
2263                           Action.REPLACE,
2264                           dialog.getName().replace(' ',
2265                                   ap.av.getGapCharacter()),
2266                           sg.getSequencesAsArray(
2267                                   ap.av.getHiddenRepSequences()),
2268                           sg.getStartRes(), sg.getEndRes() + 1,
2269                           ap.av.getAlignment());
2270                   ap.alignFrame.addHistoryItem(editCommand);
2271                   ap.av.firePropertyChange("alignment", null,
2272                           ap.av.getAlignment().getSequences());
2273                 }
2274               });
2275     }
2276   }
2277
2278   /**
2279    * Action on user selecting an item from the colour menu (that does not have
2280    * its bespoke action handler)
2281    * 
2282    * @return
2283    */
2284   @Override
2285   public void changeColour_actionPerformed(String colourSchemeName)
2286   {
2287     SequenceGroup sg = getGroup();
2288     /*
2289      * switch to the chosen colour scheme (or null for None)
2290      */
2291     ColourSchemeI colourScheme = ColourSchemes.getInstance()
2292             .getColourScheme(colourSchemeName, ap.av, sg,
2293                     ap.av.getHiddenRepSequences());
2294     sg.setColourScheme(colourScheme);
2295     if (colourScheme instanceof Blosum62ColourScheme
2296             || colourScheme instanceof PIDColourScheme)
2297     {
2298       sg.cs.setConsensus(AAFrequency.calculate(
2299               sg.getSequences(ap.av.getHiddenRepSequences()),
2300               sg.getStartRes(), sg.getEndRes() + 1));
2301     }
2302
2303     refresh();
2304   }
2305
2306 }