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