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