Merge branch 'task/JAL-3763_newDatasetForCds' into merge/develop_task/JAL-3763_newDat...
[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.Cache;
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         Cache.log.error("Exception for URLLink '" + link + "'", foo);
234         continue;
235       }
236
237       if (!urlLink.isValid())
238       {
239         Cache.log.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 residue)
363    * 
364    * @param ap
365    *              the panel in which the mouse is clicked
366    * @param seq
367    *              the sequence under the mouse
368    * @throws NullPointerException
369    *                                if seq is null
370    */
371   public PopupMenu(final AlignmentPanel ap, SequenceI seq, int column)
372   {
373     this(false, ap, seq, column, null);
374   }
375
376   /**
377    * Constructor for a PopupMenu for a click in the sequence id panel
378    * 
379    * @param alignPanel
380    *                     the panel in which the mouse is clicked
381    * @param seq
382    *                     the sequence under the mouse click
383    * @param groupLinks
384    *                     templates for sequence external links
385    * @throws NullPointerException
386    *                                if seq is null
387    */
388   public PopupMenu(final AlignmentPanel alignPanel, final SequenceI seq,
389           List<String> groupLinks)
390   {
391     this(true, alignPanel, seq, -1, groupLinks);
392   }
393
394   /**
395    * Private constructor that constructs a popup menu for either sequence ID
396    * Panel, or alignment context
397    * 
398    * @param fromIdPanel
399    * @param alignPanel
400    * @param seq
401    * @param column
402    *                      aligned column position (0...)
403    * @param groupLinks
404    */
405   private PopupMenu(boolean fromIdPanel,
406           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.getSelectionGroup() == null
447             ? Collections.<SequenceI> emptyList()
448             : alignPanel.av.getSelectionGroup().getSequences());
449     buildAnnotationTypesMenus(groupShowAnnotationsMenu,
450             groupHideAnnotationsMenu, selectedGroup);
451     configureReferenceAnnotationsMenu(groupAddReferenceAnnotations,
452             selectedGroup);
453
454     try
455     {
456       jbInit();
457     } catch (Exception e)
458     {
459       e.printStackTrace();
460     }
461
462     if (forIdPanel)
463     {
464       JMenuItem menuItem;
465       sequenceMenu.setText(sequence.getName());
466       if (seq == alignPanel.av.getAlignment().getSeqrep())
467       {
468         makeReferenceSeq.setText(
469                 MessageManager.getString("action.unmark_as_reference"));
470       }
471       else
472       {
473         makeReferenceSeq.setText(
474                 MessageManager.getString("action.set_as_reference"));
475       }
476
477       if (!alignPanel.av.getAlignment().isNucleotide())
478       {
479         remove(rnaStructureMenu);
480       }
481       else
482       {
483         int origCount = rnaStructureMenu.getItemCount();
484         /*
485          * add menu items to 2D-render any alignment or sequence secondary
486          * structure annotation
487          */
488         AlignmentAnnotation[] aas = alignPanel.av.getAlignment()
489                 .getAlignmentAnnotation();
490         if (aas != null)
491         {
492           for (final AlignmentAnnotation aa : aas)
493           {
494             if (aa.isValidStruc() && aa.sequenceRef == null)
495             {
496               /*
497                * valid alignment RNA secondary structure annotation
498                */
499               menuItem = new JMenuItem();
500               menuItem.setText(MessageManager.formatMessage(
501                       "label.2d_rna_structure_line", new Object[]
502                       { aa.label }));
503               menuItem.addActionListener(new ActionListener()
504               {
505                 @Override
506                 public void actionPerformed(ActionEvent e)
507                 {
508                   new AppVarna(seq, aa, alignPanel);
509                 }
510               });
511               rnaStructureMenu.add(menuItem);
512             }
513           }
514         }
515
516         if (seq.getAnnotation() != null)
517         {
518           AlignmentAnnotation seqAnns[] = seq.getAnnotation();
519           for (final AlignmentAnnotation aa : seqAnns)
520           {
521             if (aa.isValidStruc())
522             {
523               /*
524                * valid sequence RNA secondary structure annotation
525                */
526               // TODO: make rnastrucF a bit more nice
527               menuItem = new JMenuItem();
528               menuItem.setText(MessageManager.formatMessage(
529                       "label.2d_rna_sequence_name", new Object[]
530                       { seq.getName() }));
531               menuItem.addActionListener(new ActionListener()
532               {
533                 @Override
534                 public void actionPerformed(ActionEvent e)
535                 {
536                   // TODO: VARNA does'nt print gaps in the sequence
537                   new AppVarna(seq, aa, alignPanel);
538                 }
539               });
540               rnaStructureMenu.add(menuItem);
541             }
542           }
543         }
544         if (rnaStructureMenu.getItemCount() == origCount)
545         {
546           remove(rnaStructureMenu);
547         }
548       }
549
550       menuItem = new JMenuItem(
551               MessageManager.getString("action.hide_sequences"));
552       menuItem.addActionListener(new ActionListener()
553       {
554         @Override
555         public void actionPerformed(ActionEvent e)
556         {
557           hideSequences(false);
558         }
559       });
560       add(menuItem);
561
562       if (alignPanel.av.getSelectionGroup() != null
563               && alignPanel.av.getSelectionGroup().getSize() > 1)
564       {
565         menuItem = new JMenuItem(MessageManager
566                 .formatMessage("label.represent_group_with", new Object[]
567                 { seq.getName() }));
568         menuItem.addActionListener(new ActionListener()
569         {
570           @Override
571           public void actionPerformed(ActionEvent e)
572           {
573             hideSequences(true);
574           }
575         });
576         sequenceMenu.add(menuItem);
577       }
578
579       if (alignPanel.av.hasHiddenRows())
580       {
581         final int index = alignPanel.av.getAlignment().findIndex(seq);
582
583         if (alignPanel.av.adjustForHiddenSeqs(index)
584                 - alignPanel.av.adjustForHiddenSeqs(index - 1) > 1)
585         {
586           menuItem = new JMenuItem(
587                   MessageManager.getString("action.reveal_sequences"));
588           menuItem.addActionListener(new ActionListener()
589           {
590             @Override
591             public void actionPerformed(ActionEvent e)
592             {
593               alignPanel.av.showSequence(index);
594               if (alignPanel.overviewPanel != null)
595               {
596                 alignPanel.overviewPanel.updateOverviewImage();
597               }
598             }
599           });
600           add(menuItem);
601         }
602       }
603     }
604
605     /*
606      * offer 'Reveal All'
607      * - in the IdPanel (seq not null) if any sequence is hidden
608      * - in the IdPanel or SeqPanel if all sequences are hidden (seq is null)
609      */
610     if (alignPanel.av.hasHiddenRows())
611     {
612       boolean addOption = seq != null;
613       if (!addOption && alignPanel.av.getAlignment().getHeight() == 0)
614       {
615         addOption = true;
616       }
617       if (addOption)
618       {
619         JMenuItem menuItem = new JMenuItem(
620                 MessageManager.getString("action.reveal_all"));
621         menuItem.addActionListener(new ActionListener()
622         {
623           @Override
624           public void actionPerformed(ActionEvent e)
625           {
626             alignPanel.av.showAllHiddenSeqs();
627             if (alignPanel.overviewPanel != null)
628             {
629               alignPanel.overviewPanel.updateOverviewImage();
630             }
631           }
632         });
633         add(menuItem);
634       }
635     }
636
637     SequenceGroup sg = alignPanel.av.getSelectionGroup();
638     boolean isDefinedGroup = (sg != null)
639             ? alignPanel.av.getAlignment().getGroups().contains(sg)
640             : false;
641
642     if (sg != null && sg.getSize() > 0)
643     {
644       groupName.setText(MessageManager
645               .getString("label.edit_name_and_description_current_group"));
646
647       ColourMenuHelper.setColourSelected(colourMenu, sg.getColourScheme());
648
649       conservationMenuItem.setEnabled(!sg.isNucleotide());
650
651       if (sg.cs != null)
652       {
653         if (sg.cs.conservationApplied())
654         {
655           conservationMenuItem.setSelected(true);
656         }
657         if (sg.cs.getThreshold() > 0)
658         {
659           abovePIDColour.setSelected(true);
660         }
661       }
662       modifyConservation.setEnabled(conservationMenuItem.isSelected());
663       modifyPID.setEnabled(abovePIDColour.isSelected());
664       displayNonconserved.setSelected(sg.getShowNonconserved());
665       showText.setSelected(sg.getDisplayText());
666       showColourText.setSelected(sg.getColourText());
667       showBoxes.setSelected(sg.getDisplayBoxes());
668       // add any groupURLs to the groupURL submenu and make it visible
669       if (groupLinks != null && groupLinks.size() > 0)
670       {
671         buildGroupURLMenu(sg, groupLinks);
672       }
673       // Add a 'show all structures' for the current selection
674       Hashtable<String, PDBEntry> pdbe = new Hashtable<>(), reppdb = new Hashtable<>();
675
676       SequenceI sqass = null;
677       for (SequenceI sq : alignPanel.av.getSequenceSelection())
678       {
679         Vector<PDBEntry> pes = sq.getDatasetSequence().getAllPDBEntries();
680         if (pes != null && pes.size() > 0)
681         {
682           reppdb.put(pes.get(0).getId(), pes.get(0));
683           for (PDBEntry pe : pes)
684           {
685             pdbe.put(pe.getId(), pe);
686             if (sqass == null)
687             {
688               sqass = sq;
689             }
690           }
691         }
692       }
693       if (pdbe.size() > 0)
694       {
695         final PDBEntry[] pe = pdbe.values()
696                 .toArray(new PDBEntry[pdbe.size()]),
697                 pr = reppdb.values().toArray(new PDBEntry[reppdb.size()]);
698         final JMenuItem gpdbview, rpdbview;
699       }
700     }
701     else
702     {
703       groupMenu.setVisible(false);
704       editMenu.setVisible(false);
705     }
706
707     if (!isDefinedGroup)
708     {
709       createGroupMenuItem.setVisible(true);
710       unGroupMenuItem.setVisible(false);
711       editGroupMenu.setText(MessageManager.getString("action.edit_new_group"));
712     }
713     else
714     {
715       createGroupMenuItem.setVisible(false);
716       unGroupMenuItem.setVisible(true);
717       editGroupMenu.setText(MessageManager.getString("action.edit_group"));
718     }
719
720     if (!forIdPanel)
721     {
722       sequenceMenu.setVisible(false);
723       chooseStructure.setVisible(false);
724       rnaStructureMenu.setVisible(false);
725     }
726
727     addLinksAndFeatures(seq, column);
728   }
729
730   /**
731    * Adds
732    * <ul>
733    * <li>configured sequence database links (ID panel popup menu)</li>
734    * <li>non-positional feature links (ID panel popup menu)</li>
735    * <li>positional feature links (alignment panel popup menu)</li>
736    * <li>feature details links (alignment panel popup menu)</li>
737    * </ul>
738    * If this panel is also showed complementary (CDS/protein) features, then links
739    * to their feature details are also added.
740    * 
741    * @param seq
742    * @param column
743    */
744   void addLinksAndFeatures(final SequenceI seq, final int column)
745   {
746     List<SequenceFeature> features = null;
747     if (forIdPanel)
748     {
749       features = sequence.getFeatures().getNonPositionalFeatures();
750     }
751     else
752     {
753       features = ap.getFeatureRenderer().findFeaturesAtColumn(sequence,
754               column + 1);
755     }
756
757     addLinks(seq, features);
758
759     if (!forIdPanel)
760     {
761       addFeatureDetails(features, seq, column);
762     }
763   }
764
765   /**
766    * Add a menu item to show feature details for each sequence feature. Any
767    * linked 'virtual' features (CDS/protein) are also optionally found and
768    * included.
769    * 
770    * @param features
771    * @param seq
772    * @param column
773    */
774   protected void addFeatureDetails(List<SequenceFeature> features,
775           final SequenceI seq, final int column)
776   {
777     /*
778      * add features in CDS/protein complement at the corresponding
779      * position if configured to do so
780      */
781     MappedFeatures mf = null;
782     if (ap.av.isShowComplementFeatures())
783     {
784       if (!Comparison.isGap(sequence.getCharAt(column)))
785       {
786         AlignViewportI complement = ap.getAlignViewport()
787                 .getCodingComplement();
788         AlignFrame af = Desktop.getAlignFrameFor(complement);
789         FeatureRendererModel fr2 = af.getFeatureRenderer();
790         int seqPos = sequence.findPosition(column);
791         mf = fr2.findComplementFeaturesAtResidue(sequence, seqPos);
792       }
793     }
794
795     if (features.isEmpty() && mf == null)
796     {
797       /*
798        * no features to show at this position
799        */
800       return;
801     }
802
803     JMenu details = new JMenu(
804             MessageManager.getString("label.feature_details"));
805     add(details);
806
807     String name = seq.getName();
808     for (final SequenceFeature sf : features)
809     {
810       addFeatureDetailsMenuItem(details, name, sf, null);
811     }
812
813     if (mf != null)
814     {
815       for (final SequenceFeature sf : mf.features)
816       {
817         addFeatureDetailsMenuItem(details, name, sf, mf);
818       }
819     }
820   }
821
822   /**
823    * A helper method to add one menu item whose action is to show details for
824    * one feature. The menu text includes feature description, but this may be
825    * truncated.
826    * 
827    * @param details
828    * @param seqName
829    * @param sf
830    * @param mf
831    */
832   void addFeatureDetailsMenuItem(JMenu details, final String seqName,
833           final SequenceFeature sf, MappedFeatures mf)
834   {
835     int start = sf.getBegin();
836     int end = sf.getEnd();
837     if (mf != null)
838     {
839       /*
840        * show local rather than linked feature coordinates
841        */
842       int[] beginRange = mf.getMappedPositions(start, start);
843       int[] endRange = mf.getMappedPositions(end, end);
844       if (beginRange == null || endRange == null)
845       {
846         // e.g. variant extending to stop codon so not mappable
847         return;
848       }
849       start = beginRange[0];
850       end = endRange[endRange.length - 1];
851     }
852     StringBuilder desc = new StringBuilder();
853     desc.append(sf.getType()).append(" ").append(String.valueOf(start));
854     if (start != end)
855     {
856       desc.append(sf.isContactFeature() ? ":" : "-");
857       desc.append(String.valueOf(end));
858     }
859     String description = sf.getDescription();
860     if (description != null)
861     {
862       desc.append(" ");
863       description = StringUtils.stripHtmlTags(description);
864
865       /*
866        * truncate overlong descriptions unless they contain an href
867        * (as truncation could leave corrupted html)
868        */
869       boolean hasLink = description.indexOf("a href") > -1;
870       if (description.length() > FEATURE_DESC_MAX && !hasLink)
871       {
872         description = description.substring(0, FEATURE_DESC_MAX) + "...";
873       }
874       desc.append(description);
875     }
876     String featureGroup = sf.getFeatureGroup();
877     if (featureGroup != null)
878     {
879       desc.append(" (").append(featureGroup).append(")");
880     }
881     String htmlText = JvSwingUtils.wrapTooltip(true, desc.toString());
882     JMenuItem item = new JMenuItem(htmlText);
883     item.addActionListener(new ActionListener()
884     {
885       @Override
886       public void actionPerformed(ActionEvent e)
887       {
888         showFeatureDetails(sf, seqName, mf);
889       }
890     });
891     details.add(item);
892   }
893
894   /**
895    * Opens a panel showing a text report of feature details
896    * 
897    * @param sf
898    * @param seqName
899    * @param mf
900    */
901   protected void showFeatureDetails(SequenceFeature sf, String seqName,
902           MappedFeatures mf)
903   {
904     JInternalFrame details;
905     if (Platform.isJS())
906     {
907       details = new JInternalFrame();
908       JPanel panel = new JPanel(new BorderLayout());
909       panel.setOpaque(true);
910       panel.setBackground(Color.white);
911       // TODO JAL-3026 set style of table correctly for feature details
912       JLabel reprt = new JLabel(MessageManager
913               .formatMessage("label.html_content", new Object[]
914               { sf.getDetailsReport(seqName, mf) }));
915       reprt.setBackground(Color.WHITE);
916       reprt.setOpaque(true);
917       panel.add(reprt, BorderLayout.CENTER);
918       details.setContentPane(panel);
919       details.pack();
920     }
921     else
922     /**
923      * Java only
924      * 
925      * @j2sIgnore
926      */
927     {
928       CutAndPasteHtmlTransfer cap = new CutAndPasteHtmlTransfer();
929       // it appears Java's CSS does not support border-collapse :-(
930       cap.addStylesheetRule("table { border-collapse: collapse;}");
931       cap.addStylesheetRule("table, td, th {border: 1px solid black;}");
932       cap.setText(sf.getDetailsReport(seqName, mf));
933       details = cap;
934     }
935     Desktop.addInternalFrame(details,
936             MessageManager.getString("label.feature_details"), 500, 500);
937   }
938
939   /**
940    * Adds a 'Link' menu item with a sub-menu item for each hyperlink provided.
941    * When seq is not null, these are links for the sequence id, which may be to
942    * external web sites for the sequence accession, and/or links embedded in
943    * non-positional features. When seq is null, only links embedded in the
944    * provided features are added. If no links are found, the menu is not added.
945    * 
946    * @param seq
947    * @param features
948    */
949   void addLinks(final SequenceI seq, List<SequenceFeature> features)
950   {
951     JMenu linkMenu = buildLinkMenu(forIdPanel ? seq : null, features);
952
953     // only add link menu if it has entries
954     if (linkMenu.getItemCount() > 0)
955     {
956       if (forIdPanel)
957       {
958         sequenceMenu.add(linkMenu);
959       }
960       else
961       {
962         add(linkMenu);
963       }
964     }
965   }
966
967   /**
968    * Add annotation types to 'Show annotations' and/or 'Hide annotations' menus.
969    * "All" is added first, followed by a separator. Then add any annotation
970    * types associated with the current selection. Separate menus are built for
971    * the selected sequence group (if any), and the selected sequence.
972    * <p>
973    * Some annotation rows are always rendered together - these can be identified
974    * by a common graphGroup property > -1. Only one of each group will be marked
975    * as visible (to avoid duplication of the display). For such groups we add a
976    * composite type name, e.g.
977    * <p>
978    * IUPredWS (Long), IUPredWS (Short)
979    * 
980    * @param seq
981    */
982   protected void buildAnnotationTypesMenus(JMenu showMenu, JMenu hideMenu,
983           List<SequenceI> forSequences)
984   {
985     showMenu.removeAll();
986     hideMenu.removeAll();
987
988     final List<String> all = Arrays
989             .asList(new String[]
990             { MessageManager.getString("label.all") });
991     addAnnotationTypeToShowHide(showMenu, forSequences, "", all, true,
992             true);
993     addAnnotationTypeToShowHide(hideMenu, forSequences, "", all, true,
994             false);
995     showMenu.addSeparator();
996     hideMenu.addSeparator();
997
998     final AlignmentAnnotation[] annotations = ap.getAlignment()
999             .getAlignmentAnnotation();
1000
1001     /*
1002      * Find shown/hidden annotations types, distinguished by source (calcId),
1003      * and grouped by graphGroup. Using LinkedHashMap means we will retrieve in
1004      * the insertion order, which is the order of the annotations on the
1005      * alignment.
1006      */
1007     Map<String, List<List<String>>> shownTypes = new LinkedHashMap<>();
1008     Map<String, List<List<String>>> hiddenTypes = new LinkedHashMap<>();
1009     AlignmentAnnotationUtils.getShownHiddenTypes(shownTypes, hiddenTypes,
1010             AlignmentAnnotationUtils.asList(annotations), forSequences);
1011
1012     for (String calcId : hiddenTypes.keySet())
1013     {
1014       for (List<String> type : hiddenTypes.get(calcId))
1015       {
1016         addAnnotationTypeToShowHide(showMenu, forSequences, calcId, type,
1017                 false, true);
1018       }
1019     }
1020     // grey out 'show annotations' if none are hidden
1021     showMenu.setEnabled(!hiddenTypes.isEmpty());
1022
1023     for (String calcId : shownTypes.keySet())
1024     {
1025       for (List<String> type : shownTypes.get(calcId))
1026       {
1027         addAnnotationTypeToShowHide(hideMenu, forSequences, calcId, type,
1028                 false, false);
1029       }
1030     }
1031     // grey out 'hide annotations' if none are shown
1032     hideMenu.setEnabled(!shownTypes.isEmpty());
1033   }
1034
1035   /**
1036    * Returns a list of sequences - either the current selection group (if there
1037    * is one), else the specified single sequence.
1038    * 
1039    * @param seq
1040    * @return
1041    */
1042   protected List<SequenceI> getSequenceScope(SequenceI seq)
1043   {
1044     List<SequenceI> forSequences = null;
1045     final SequenceGroup selectionGroup = ap.av.getSelectionGroup();
1046     if (selectionGroup != null && selectionGroup.getSize() > 0)
1047     {
1048       forSequences = selectionGroup.getSequences();
1049     }
1050     else
1051     {
1052       forSequences = seq == null ? Collections.<SequenceI> emptyList()
1053               : Arrays.asList(seq);
1054     }
1055     return forSequences;
1056   }
1057
1058   /**
1059    * Add one annotation type to the 'Show Annotations' or 'Hide Annotations'
1060    * menus.
1061    * 
1062    * @param showOrHideMenu
1063    *          the menu to add to
1064    * @param forSequences
1065    *          the sequences whose annotations may be shown or hidden
1066    * @param calcId
1067    * @param types
1068    *          the label to add
1069    * @param allTypes
1070    *          if true this is a special label meaning 'All'
1071    * @param actionIsShow
1072    *          if true, the select menu item action is to show the annotation
1073    *          type, else hide
1074    */
1075   protected void addAnnotationTypeToShowHide(JMenu showOrHideMenu,
1076           final List<SequenceI> forSequences, String calcId,
1077           final List<String> types, final boolean allTypes,
1078           final boolean actionIsShow)
1079   {
1080     String label = types.toString(); // [a, b, c]
1081     label = label.substring(1, label.length() - 1); // a, b, c
1082     final JMenuItem item = new JMenuItem(label);
1083     item.setToolTipText(calcId);
1084     item.addActionListener(new ActionListener()
1085     {
1086       @Override
1087       public void actionPerformed(ActionEvent e)
1088       {
1089         AlignmentUtils.showOrHideSequenceAnnotations(ap.getAlignment(),
1090                 types, forSequences, allTypes, actionIsShow);
1091         refresh();
1092       }
1093     });
1094     showOrHideMenu.add(item);
1095   }
1096
1097   private void buildGroupURLMenu(SequenceGroup sg, List<String> groupLinks)
1098   {
1099
1100     // TODO: usability: thread off the generation of group url content so root
1101     // menu appears asap
1102     // sequence only URLs
1103     // ID/regex match URLs
1104     JMenu groupLinksMenu = new JMenu(
1105             MessageManager.getString("action.group_link"));
1106     // three types of url that might be created.
1107     JMenu[] linkMenus = new JMenu[] { null,
1108         new JMenu(MessageManager.getString("action.ids")),
1109         new JMenu(MessageManager.getString("action.sequences")),
1110         new JMenu(MessageManager.getString("action.ids_sequences")) };
1111
1112     SequenceI[] seqs = ap.av.getSelectionAsNewSequence();
1113     String[][] idandseqs = GroupUrlLink.formStrings(seqs);
1114     Hashtable<String, Object[]> commonDbrefs = new Hashtable<>();
1115     for (int sq = 0; sq < seqs.length; sq++)
1116     {
1117
1118       int start = seqs[sq].findPosition(sg.getStartRes()),
1119               end = seqs[sq].findPosition(sg.getEndRes());
1120       // just collect ids from dataset sequence
1121       // TODO: check if IDs collected from selecton group intersects with the
1122       // current selection, too
1123       SequenceI sqi = seqs[sq];
1124       while (sqi.getDatasetSequence() != null)
1125       {
1126         sqi = sqi.getDatasetSequence();
1127       }
1128       List<DBRefEntry> dbr = sqi.getDBRefs();
1129       int nd;
1130       if (dbr != null && (nd = dbr.size()) > 0)
1131       {
1132         for (int d = 0; d < nd; d++)
1133         {
1134           DBRefEntry e = dbr.get(d);
1135           String src = e.getSource(); // jalview.util.DBRefUtils.getCanonicalName(dbr[d].getSource()).toUpperCase(Locale.ROOT);
1136           Object[] sarray = commonDbrefs.get(src);
1137           if (sarray == null)
1138           {
1139             sarray = new Object[2];
1140             sarray[0] = new int[] { 0 };
1141             sarray[1] = new String[seqs.length];
1142
1143             commonDbrefs.put(src, sarray);
1144           }
1145
1146           if (((String[]) sarray[1])[sq] == null)
1147           {
1148             if (!e.hasMap() || (e.getMap()
1149                     .locateMappedRange(start, end) != null))
1150             {
1151               ((String[]) sarray[1])[sq] = e.getAccessionId();
1152               ((int[]) sarray[0])[0]++;
1153             }
1154           }
1155         }
1156       }
1157     }
1158     // now create group links for all distinct ID/sequence sets.
1159     boolean addMenu = false; // indicates if there are any group links to give
1160                              // to user
1161     for (String link : groupLinks)
1162     {
1163       GroupUrlLink urlLink = null;
1164       try
1165       {
1166         urlLink = new GroupUrlLink(link);
1167       } catch (Exception foo)
1168       {
1169         Cache.log.error("Exception for GroupURLLink '" + link + "'", foo);
1170         continue;
1171       }
1172       if (!urlLink.isValid())
1173       {
1174         Cache.log.error(urlLink.getInvalidMessage());
1175         continue;
1176       }
1177       final String label = urlLink.getLabel();
1178       boolean usingNames = false;
1179       // Now see which parts of the group apply for this URL
1180       String ltarget = urlLink.getTarget(); // jalview.util.DBRefUtils.getCanonicalName(urlLink.getTarget());
1181       Object[] idset = commonDbrefs.get(ltarget.toUpperCase(Locale.ROOT));
1182       String[] seqstr, ids; // input to makeUrl
1183       if (idset != null)
1184       {
1185         int numinput = ((int[]) idset[0])[0];
1186         String[] allids = ((String[]) idset[1]);
1187         seqstr = new String[numinput];
1188         ids = new String[numinput];
1189         for (int sq = 0, idcount = 0; sq < seqs.length; sq++)
1190         {
1191           if (allids[sq] != null)
1192           {
1193             ids[idcount] = allids[sq];
1194             seqstr[idcount++] = idandseqs[1][sq];
1195           }
1196         }
1197       }
1198       else
1199       {
1200         // just use the id/seq set
1201         seqstr = idandseqs[1];
1202         ids = idandseqs[0];
1203         usingNames = true;
1204       }
1205       // and try and make the groupURL!
1206
1207       Object[] urlset = null;
1208       try
1209       {
1210         urlset = urlLink.makeUrlStubs(ids, seqstr,
1211                 "FromJalview" + System.currentTimeMillis(), false);
1212       } catch (UrlStringTooLongException e)
1213       {
1214       }
1215       if (urlset != null)
1216       {
1217         int type = urlLink.getGroupURLType() & 3;
1218         // first two bits ofurlLink type bitfield are sequenceids and sequences
1219         // TODO: FUTURE: ensure the groupURL menu structure can be generalised
1220         addshowLink(linkMenus[type],
1221                 label + (((type & 1) == 1)
1222                         ? ("(" + (usingNames ? "Names" : ltarget) + ")")
1223                         : ""),
1224                 urlLink, urlset);
1225         addMenu = true;
1226       }
1227     }
1228     if (addMenu)
1229     {
1230       groupLinksMenu = new JMenu(
1231               MessageManager.getString("action.group_link"));
1232       for (int m = 0; m < linkMenus.length; m++)
1233       {
1234         if (linkMenus[m] != null
1235                 && linkMenus[m].getMenuComponentCount() > 0)
1236         {
1237           groupLinksMenu.add(linkMenus[m]);
1238         }
1239       }
1240
1241       groupMenu.add(groupLinksMenu);
1242     }
1243   }
1244
1245   /**
1246    * DOCUMENT ME!
1247    * 
1248    * @throws Exception
1249    *           DOCUMENT ME!
1250    */
1251   private void jbInit() throws Exception
1252   {
1253     groupMenu.setText(MessageManager.getString("label.selection"));
1254     groupName.setText(MessageManager.getString("label.name"));
1255     groupName.addActionListener(new ActionListener()
1256     {
1257       @Override
1258       public void actionPerformed(ActionEvent e)
1259       {
1260         groupName_actionPerformed();
1261       }
1262     });
1263     sequenceMenu.setText(MessageManager.getString("label.sequence"));
1264
1265     JMenuItem sequenceName = new JMenuItem(
1266             MessageManager.getString("label.edit_name_description"));
1267     sequenceName.addActionListener(new ActionListener()
1268     {
1269       @Override
1270       public void actionPerformed(ActionEvent e)
1271       {
1272         sequenceName_actionPerformed();
1273       }
1274     });
1275     JMenuItem chooseAnnotations = new JMenuItem(
1276             MessageManager.getString("action.choose_annotations"));
1277     chooseAnnotations.addActionListener(new ActionListener()
1278     {
1279       @Override
1280       public void actionPerformed(ActionEvent e)
1281       {
1282         chooseAnnotations_actionPerformed(e);
1283       }
1284     });
1285     JMenuItem sequenceDetails = new JMenuItem(
1286             MessageManager.getString("label.sequence_details"));
1287     sequenceDetails.addActionListener(new ActionListener()
1288     {
1289       @Override
1290       public void actionPerformed(ActionEvent e)
1291       {
1292         createSequenceDetailsReport(new SequenceI[] { sequence });
1293       }
1294     });
1295     JMenuItem sequenceSelDetails = new JMenuItem(
1296             MessageManager.getString("label.sequence_details"));
1297     sequenceSelDetails.addActionListener(new ActionListener()
1298     {
1299       @Override
1300       public void actionPerformed(ActionEvent e)
1301       {
1302         createSequenceDetailsReport(ap.av.getSequenceSelection());
1303       }
1304     });
1305
1306     unGroupMenuItem
1307             .setText(MessageManager.getString("action.remove_group"));
1308     unGroupMenuItem.addActionListener(new ActionListener()
1309     {
1310       @Override
1311       public void actionPerformed(ActionEvent e)
1312       {
1313         unGroupMenuItem_actionPerformed();
1314       }
1315     });
1316     createGroupMenuItem
1317             .setText(MessageManager.getString("action.create_group"));
1318     createGroupMenuItem.addActionListener(new ActionListener()
1319     {
1320       @Override
1321       public void actionPerformed(ActionEvent e)
1322       {
1323         createGroupMenuItem_actionPerformed();
1324       }
1325     });
1326
1327     JMenuItem outline = new JMenuItem(
1328             MessageManager.getString("action.border_colour"));
1329     outline.addActionListener(new ActionListener()
1330     {
1331       @Override
1332       public void actionPerformed(ActionEvent e)
1333       {
1334         outline_actionPerformed();
1335       }
1336     });
1337     showBoxes.setText(MessageManager.getString("action.boxes"));
1338     showBoxes.setState(true);
1339     showBoxes.addActionListener(new ActionListener()
1340     {
1341       @Override
1342       public void actionPerformed(ActionEvent e)
1343       {
1344         showBoxes_actionPerformed();
1345       }
1346     });
1347     showText.setText(MessageManager.getString("action.text"));
1348     showText.setState(true);
1349     showText.addActionListener(new ActionListener()
1350     {
1351       @Override
1352       public void actionPerformed(ActionEvent e)
1353       {
1354         showText_actionPerformed();
1355       }
1356     });
1357     showColourText.setText(MessageManager.getString("label.colour_text"));
1358     showColourText.addActionListener(new ActionListener()
1359     {
1360       @Override
1361       public void actionPerformed(ActionEvent e)
1362       {
1363         showColourText_actionPerformed();
1364       }
1365     });
1366     displayNonconserved
1367             .setText(MessageManager.getString("label.show_non_conserved"));
1368     displayNonconserved.setState(true);
1369     displayNonconserved.addActionListener(new ActionListener()
1370     {
1371       @Override
1372       public void actionPerformed(ActionEvent e)
1373       {
1374         showNonconserved_actionPerformed();
1375       }
1376     });
1377     editMenu.setText(MessageManager.getString("action.edit"));
1378     JMenuItem cut = new JMenuItem(MessageManager.getString("action.cut"));
1379     cut.addActionListener(new ActionListener()
1380     {
1381       @Override
1382       public void actionPerformed(ActionEvent e)
1383       {
1384         cut_actionPerformed();
1385       }
1386     });
1387     upperCase.setText(MessageManager.getString("label.to_upper_case"));
1388     upperCase.addActionListener(new ActionListener()
1389     {
1390       @Override
1391       public void actionPerformed(ActionEvent e)
1392       {
1393         changeCase(e);
1394       }
1395     });
1396     JMenuItem copy = new JMenuItem(MessageManager.getString("action.copy"));
1397     copy.addActionListener(new ActionListener()
1398     {
1399       @Override
1400       public void actionPerformed(ActionEvent e)
1401       {
1402         copy_actionPerformed();
1403       }
1404     });
1405     lowerCase.setText(MessageManager.getString("label.to_lower_case"));
1406     lowerCase.addActionListener(new ActionListener()
1407     {
1408       @Override
1409       public void actionPerformed(ActionEvent e)
1410       {
1411         changeCase(e);
1412       }
1413     });
1414     toggle.setText(MessageManager.getString("label.toggle_case"));
1415     toggle.addActionListener(new ActionListener()
1416     {
1417       @Override
1418       public void actionPerformed(ActionEvent e)
1419       {
1420         changeCase(e);
1421       }
1422     });
1423     outputMenu.setText(
1424             MessageManager.getString("label.out_to_textbox") + "...");
1425     seqShowAnnotationsMenu
1426             .setText(MessageManager.getString("label.show_annotations"));
1427     seqHideAnnotationsMenu
1428             .setText(MessageManager.getString("label.hide_annotations"));
1429     groupShowAnnotationsMenu
1430             .setText(MessageManager.getString("label.show_annotations"));
1431     groupHideAnnotationsMenu
1432             .setText(MessageManager.getString("label.hide_annotations"));
1433     JMenuItem sequenceFeature = new JMenuItem(
1434             MessageManager.getString("label.create_sequence_feature"));
1435     sequenceFeature.addActionListener(new ActionListener()
1436     {
1437       @Override
1438       public void actionPerformed(ActionEvent e)
1439       {
1440         sequenceFeature_actionPerformed();
1441       }
1442     });
1443     editGroupMenu.setText(MessageManager.getString("label.group"));
1444     chooseStructure.setText(
1445             MessageManager.getString("label.show_pdbstruct_dialog"));
1446     chooseStructure.addActionListener(new ActionListener()
1447     {
1448       @Override
1449       public void actionPerformed(ActionEvent actionEvent)
1450       {
1451         SequenceI[] selectedSeqs = new SequenceI[] { sequence };
1452         if (ap.av.getSelectionGroup() != null)
1453         {
1454           selectedSeqs = ap.av.getSequenceSelection();
1455         }
1456         new StructureChooser(selectedSeqs, sequence, ap);
1457       }
1458     });
1459
1460     rnaStructureMenu
1461             .setText(MessageManager.getString("label.view_rna_structure"));
1462
1463     // colStructureMenu.setText("Colour By Structure");
1464     JMenuItem editSequence = new JMenuItem(
1465             MessageManager.getString("label.edit_sequence") + "...");
1466     editSequence.addActionListener(new ActionListener()
1467     {
1468       @Override
1469       public void actionPerformed(ActionEvent actionEvent)
1470       {
1471         editSequence_actionPerformed();
1472       }
1473     });
1474     makeReferenceSeq.setText(
1475             MessageManager.getString("label.mark_as_representative"));
1476     makeReferenceSeq.addActionListener(new ActionListener()
1477     {
1478
1479       @Override
1480       public void actionPerformed(ActionEvent actionEvent)
1481       {
1482         makeReferenceSeq_actionPerformed(actionEvent);
1483
1484       }
1485     });
1486
1487     groupMenu.add(sequenceSelDetails);
1488     add(groupMenu);
1489     add(sequenceMenu);
1490     add(rnaStructureMenu);
1491     add(chooseStructure);
1492     if (forIdPanel)
1493     {
1494       JMenuItem hideInsertions = new JMenuItem(
1495               MessageManager.getString("label.hide_insertions"));
1496       hideInsertions.addActionListener(new ActionListener()
1497       {
1498
1499         @Override
1500         public void actionPerformed(ActionEvent e)
1501         {
1502           hideInsertions_actionPerformed(e);
1503         }
1504       });
1505       add(hideInsertions);
1506     }
1507     // annotations configuration panel suppressed for now
1508     // groupMenu.add(chooseAnnotations);
1509
1510     /*
1511      * Add show/hide annotations to the Sequence menu, and to the Selection menu
1512      * (if a selection group is in force).
1513      */
1514     sequenceMenu.add(seqShowAnnotationsMenu);
1515     sequenceMenu.add(seqHideAnnotationsMenu);
1516     sequenceMenu.add(seqAddReferenceAnnotations);
1517     groupMenu.add(groupShowAnnotationsMenu);
1518     groupMenu.add(groupHideAnnotationsMenu);
1519     groupMenu.add(groupAddReferenceAnnotations);
1520     groupMenu.add(editMenu);
1521     groupMenu.add(outputMenu);
1522     groupMenu.add(sequenceFeature);
1523     groupMenu.add(createGroupMenuItem);
1524     groupMenu.add(unGroupMenuItem);
1525     groupMenu.add(editGroupMenu);
1526     sequenceMenu.add(sequenceName);
1527     sequenceMenu.add(sequenceDetails);
1528     sequenceMenu.add(makeReferenceSeq);
1529
1530     initColourMenu();
1531     buildColourMenu();
1532
1533     editMenu.add(copy);
1534     editMenu.add(cut);
1535     editMenu.add(editSequence);
1536     editMenu.add(upperCase);
1537     editMenu.add(lowerCase);
1538     editMenu.add(toggle);
1539     editGroupMenu.add(groupName);
1540     editGroupMenu.add(colourMenu);
1541     editGroupMenu.add(showBoxes);
1542     editGroupMenu.add(showText);
1543     editGroupMenu.add(showColourText);
1544     editGroupMenu.add(outline);
1545     editGroupMenu.add(displayNonconserved);
1546   }
1547
1548   /**
1549    * Constructs the entries for the colour menu
1550    */
1551   protected void initColourMenu()
1552   {
1553     colourMenu.setText(MessageManager.getString("label.group_colour"));
1554     textColour.setText(MessageManager.getString("label.text_colour"));
1555     textColour.addActionListener(new ActionListener()
1556     {
1557       @Override
1558       public void actionPerformed(ActionEvent e)
1559       {
1560         textColour_actionPerformed();
1561       }
1562     });
1563
1564     abovePIDColour.setText(
1565             MessageManager.getString("label.above_identity_threshold"));
1566     abovePIDColour.addActionListener(new ActionListener()
1567     {
1568       @Override
1569       public void actionPerformed(ActionEvent e)
1570       {
1571         abovePIDColour_actionPerformed(abovePIDColour.isSelected());
1572       }
1573     });
1574
1575     modifyPID.setText(
1576             MessageManager.getString("label.modify_identity_threshold"));
1577     modifyPID.addActionListener(new ActionListener()
1578     {
1579       @Override
1580       public void actionPerformed(ActionEvent e)
1581       {
1582         modifyPID_actionPerformed();
1583       }
1584     });
1585
1586     conservationMenuItem
1587             .setText(MessageManager.getString("action.by_conservation"));
1588     conservationMenuItem.addActionListener(new ActionListener()
1589     {
1590       @Override
1591       public void actionPerformed(ActionEvent e)
1592       {
1593         conservationMenuItem_actionPerformed(
1594                 conservationMenuItem.isSelected());
1595       }
1596     });
1597
1598     annotationColour = new JRadioButtonMenuItem(
1599             MessageManager.getString("action.by_annotation"));
1600     annotationColour.setName(ResidueColourScheme.ANNOTATION_COLOUR);
1601     annotationColour.setEnabled(false);
1602     annotationColour.setToolTipText(
1603             MessageManager.getString("label.by_annotation_tooltip"));
1604
1605     modifyConservation.setText(MessageManager
1606             .getString("label.modify_conservation_threshold"));
1607     modifyConservation.addActionListener(new ActionListener()
1608     {
1609       @Override
1610       public void actionPerformed(ActionEvent e)
1611       {
1612         modifyConservation_actionPerformed();
1613       }
1614     });
1615   }
1616
1617   /**
1618    * Builds the group colour sub-menu, including any user-defined colours which
1619    * were loaded at startup or during the Jalview session
1620    */
1621   protected void buildColourMenu()
1622   {
1623     SequenceGroup sg = ap.av.getSelectionGroup();
1624     if (sg == null)
1625     {
1626       /*
1627        * popup menu with no sequence group scope
1628        */
1629       return;
1630     }
1631     colourMenu.removeAll();
1632     colourMenu.add(textColour);
1633     colourMenu.addSeparator();
1634
1635     ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this, sg,
1636             false);
1637     bg.add(annotationColour);
1638     colourMenu.add(annotationColour);
1639
1640     colourMenu.addSeparator();
1641     colourMenu.add(conservationMenuItem);
1642     colourMenu.add(modifyConservation);
1643     colourMenu.add(abovePIDColour);
1644     colourMenu.add(modifyPID);
1645   }
1646
1647   protected void modifyConservation_actionPerformed()
1648   {
1649     SequenceGroup sg = getGroup();
1650     if (sg.cs != null)
1651     {
1652       SliderPanel.setConservationSlider(ap, sg.cs, sg.getName());
1653       SliderPanel.showConservationSlider();
1654     }
1655   }
1656
1657   protected void modifyPID_actionPerformed()
1658   {
1659     SequenceGroup sg = getGroup();
1660     if (sg.cs != null)
1661     {
1662       // int threshold = SliderPanel.setPIDSliderSource(ap, sg.cs, getGroup()
1663       // .getName());
1664       // sg.cs.setThreshold(threshold, ap.av.isIgnoreGapsConsensus());
1665       SliderPanel.setPIDSliderSource(ap, sg.cs, getGroup().getName());
1666       SliderPanel.showPIDSlider();
1667     }
1668   }
1669
1670   /**
1671    * Check for any annotations on the underlying dataset sequences (for the
1672    * current selection group) which are not 'on the alignment'.If any are found,
1673    * enable the option to add them to the alignment. The criteria for 'on the
1674    * alignment' is finding an alignment annotation on the alignment, matched on
1675    * calcId, label and sequenceRef.
1676    * 
1677    * A tooltip is also constructed that displays the source (calcId) and type
1678    * (label) of the annotations that can be added.
1679    * 
1680    * @param menuItem
1681    * @param forSequences
1682    */
1683   protected void configureReferenceAnnotationsMenu(JMenuItem menuItem,
1684           List<SequenceI> forSequences)
1685   {
1686     menuItem.setEnabled(false);
1687
1688     /*
1689      * Temporary store to hold distinct calcId / type pairs for the tooltip.
1690      * Using TreeMap means calcIds are shown in alphabetical order.
1691      */
1692     SortedMap<String, String> tipEntries = new TreeMap<>();
1693     final Map<SequenceI, List<AlignmentAnnotation>> candidates = new LinkedHashMap<>();
1694     AlignmentI al = this.ap.av.getAlignment();
1695     AlignmentUtils.findAddableReferenceAnnotations(forSequences, tipEntries,
1696             candidates, al);
1697     if (!candidates.isEmpty())
1698     {
1699       StringBuilder tooltip = new StringBuilder(64);
1700       tooltip.append(MessageManager.getString("label.add_annotations_for"));
1701
1702       /*
1703        * Found annotations that could be added. Enable the menu item, and
1704        * configure its tooltip and action.
1705        */
1706       menuItem.setEnabled(true);
1707       for (String calcId : tipEntries.keySet())
1708       {
1709         tooltip.append("<br/>" + calcId + "/" + tipEntries.get(calcId));
1710       }
1711       String tooltipText = JvSwingUtils.wrapTooltip(true,
1712               tooltip.toString());
1713       menuItem.setToolTipText(tooltipText);
1714
1715       menuItem.addActionListener(new ActionListener()
1716       {
1717         @Override
1718         public void actionPerformed(ActionEvent e)
1719         {
1720           addReferenceAnnotations_actionPerformed(candidates);
1721         }
1722       });
1723     }
1724   }
1725
1726   /**
1727    * Add annotations to the sequences and to the alignment.
1728    * 
1729    * @param candidates
1730    *          a map whose keys are sequences on the alignment, and values a list
1731    *          of annotations to add to each sequence
1732    */
1733   protected void addReferenceAnnotations_actionPerformed(
1734           Map<SequenceI, List<AlignmentAnnotation>> candidates)
1735   {
1736     final SequenceGroup selectionGroup = this.ap.av.getSelectionGroup();
1737     final AlignmentI alignment = this.ap.getAlignment();
1738     AlignmentUtils.addReferenceAnnotations(candidates, alignment,
1739             selectionGroup);
1740     refresh();
1741   }
1742
1743   protected void makeReferenceSeq_actionPerformed(ActionEvent actionEvent)
1744   {
1745     if (!ap.av.getAlignment().hasSeqrep())
1746     {
1747       // initialise the display flags so the user sees something happen
1748       ap.av.setDisplayReferenceSeq(true);
1749       ap.av.setColourByReferenceSeq(true);
1750       ap.av.getAlignment().setSeqrep(sequence);
1751     }
1752     else
1753     {
1754       if (ap.av.getAlignment().getSeqrep() == sequence)
1755       {
1756         ap.av.getAlignment().setSeqrep(null);
1757       }
1758       else
1759       {
1760         ap.av.getAlignment().setSeqrep(sequence);
1761       }
1762     }
1763     refresh();
1764   }
1765
1766   protected void hideInsertions_actionPerformed(ActionEvent actionEvent)
1767   {
1768     HiddenColumns hidden = ap.av.getAlignment().getHiddenColumns();
1769     BitSet inserts = new BitSet();
1770
1771     boolean markedPopup = false;
1772     // mark inserts in current selection
1773     if (ap.av.getSelectionGroup() != null)
1774     {
1775       // mark just the columns in the selection group to be hidden
1776       inserts.set(ap.av.getSelectionGroup().getStartRes(),
1777               ap.av.getSelectionGroup().getEndRes() + 1); // TODO why +1?
1778
1779       // now clear columns without gaps
1780       for (SequenceI sq : ap.av.getSelectionGroup().getSequences())
1781       {
1782         if (sq == sequence)
1783         {
1784           markedPopup = true;
1785         }
1786         inserts.and(sq.getInsertionsAsBits());
1787       }
1788       hidden.clearAndHideColumns(inserts, ap.av.getSelectionGroup().getStartRes(),
1789               ap.av.getSelectionGroup().getEndRes());
1790     }
1791
1792     // now mark for sequence under popup if we haven't already done it
1793     else if (!markedPopup && sequence != null)
1794     {
1795       inserts.or(sequence.getInsertionsAsBits());
1796
1797       // and set hidden columns accordingly
1798       hidden.hideColumns(inserts);
1799     }
1800     refresh();
1801   }
1802
1803   protected void sequenceSelectionDetails_actionPerformed()
1804   {
1805     createSequenceDetailsReport(ap.av.getSequenceSelection());
1806   }
1807
1808   public void createSequenceDetailsReport(SequenceI[] sequences)
1809   {
1810     StringBuilder contents = new StringBuilder(128);
1811     contents.append("<html><body>");
1812     for (SequenceI seq : sequences)
1813     {
1814       contents.append("<p><h2>" + MessageManager.formatMessage(
1815               "label.create_sequence_details_report_annotation_for",
1816               new Object[]
1817               { seq.getDisplayId(true) }) + "</h2></p><p>");
1818       new SequenceAnnotationReport(false).createSequenceAnnotationReport(
1819               contents, seq, true, true, ap.getSeqPanel().seqCanvas.fr);
1820       contents.append("</p>");
1821     }
1822     contents.append("</body></html>");
1823     String report = contents.toString();
1824
1825     JInternalFrame frame;
1826     if (Platform.isJS())
1827     {
1828       JLabel textLabel = new JLabel();
1829       textLabel.setText(report);
1830       textLabel.setBackground(Color.WHITE);
1831       JPanel pane = new JPanel(new BorderLayout());
1832       pane.setOpaque(true);
1833       pane.setBackground(Color.WHITE);
1834       pane.add(textLabel, BorderLayout.NORTH);
1835       frame = new JInternalFrame();
1836       frame.getContentPane().add(new JScrollPane(pane));
1837     }
1838     else
1839     /**
1840      * Java only
1841      * 
1842      * @j2sIgnore
1843      */
1844     {
1845       CutAndPasteHtmlTransfer cap = new CutAndPasteHtmlTransfer();
1846       cap.setText(report);
1847       frame = cap;
1848     }
1849
1850     Desktop.addInternalFrame(frame,
1851             MessageManager.formatMessage("label.sequence_details_for",
1852                     (sequences.length == 1 ? new Object[]
1853                     { sequences[0].getDisplayId(true) }
1854                             : new Object[]
1855                             { MessageManager
1856                                     .getString("label.selection") })),
1857             500, 400);
1858   }
1859
1860   protected void showNonconserved_actionPerformed()
1861   {
1862     getGroup().setShowNonconserved(displayNonconserved.isSelected());
1863     refresh();
1864   }
1865
1866   /**
1867    * call to refresh view after settings change
1868    */
1869   void refresh()
1870   {
1871     ap.updateAnnotation();
1872     // removed paintAlignment(true) here:
1873     // updateAnnotation calls paintAlignment already, so don't need to call
1874     // again
1875
1876     PaintRefresher.Refresh(this, ap.av.getSequenceSetId());
1877   }
1878
1879   /*
1880    * protected void covariationColour_actionPerformed() { getGroup().cs = new
1881    * CovariationColourScheme(sequence.getAnnotation()[0]); refresh(); }
1882    */
1883   /**
1884    * DOCUMENT ME!
1885    * 
1886    * @param selected
1887    * 
1888    * @param e
1889    *          DOCUMENT ME!
1890    */
1891   public void abovePIDColour_actionPerformed(boolean selected)
1892   {
1893     SequenceGroup sg = getGroup();
1894     if (sg.cs == null)
1895     {
1896       return;
1897     }
1898
1899     if (selected)
1900     {
1901       sg.cs.setConsensus(AAFrequency.calculate(
1902               sg.getSequences(ap.av.getHiddenRepSequences()),
1903               sg.getStartRes(), sg.getEndRes() + 1));
1904
1905       int threshold = SliderPanel.setPIDSliderSource(ap,
1906               sg.getGroupColourScheme(), getGroup().getName());
1907
1908       sg.cs.setThreshold(threshold, ap.av.isIgnoreGapsConsensus());
1909
1910       SliderPanel.showPIDSlider();
1911     }
1912     else
1913     // remove PIDColouring
1914     {
1915       sg.cs.setThreshold(0, ap.av.isIgnoreGapsConsensus());
1916       SliderPanel.hidePIDSlider();
1917     }
1918     modifyPID.setEnabled(selected);
1919
1920     refresh();
1921   }
1922
1923   /**
1924    * Open a panel where the user can choose which types of sequence annotation
1925    * to show or hide.
1926    * 
1927    * @param e
1928    */
1929   protected void chooseAnnotations_actionPerformed(ActionEvent e)
1930   {
1931     // todo correct way to guard against opening a duplicate panel?
1932     new AnnotationChooser(ap);
1933   }
1934
1935   /**
1936    * DOCUMENT ME!
1937    * 
1938    * @param e
1939    *          DOCUMENT ME!
1940    */
1941   public void conservationMenuItem_actionPerformed(boolean selected)
1942   {
1943     SequenceGroup sg = getGroup();
1944     if (sg.cs == null)
1945     {
1946       return;
1947     }
1948
1949     if (selected)
1950     {
1951       // JBPNote: Conservation name shouldn't be i18n translated
1952       Conservation c = new Conservation("Group",
1953               sg.getSequences(ap.av.getHiddenRepSequences()),
1954               sg.getStartRes(), sg.getEndRes() + 1);
1955
1956       c.calculate();
1957       c.verdict(false, ap.av.getConsPercGaps());
1958       sg.cs.setConservation(c);
1959
1960       SliderPanel.setConservationSlider(ap, sg.getGroupColourScheme(),
1961               sg.getName());
1962       SliderPanel.showConservationSlider();
1963     }
1964     else
1965     // remove ConservationColouring
1966     {
1967       sg.cs.setConservation(null);
1968       SliderPanel.hideConservationSlider();
1969     }
1970     modifyConservation.setEnabled(selected);
1971
1972     refresh();
1973   }
1974
1975   /**
1976    * Shows a dialog where group name and description may be edited
1977    */
1978   protected void groupName_actionPerformed()
1979   {
1980     SequenceGroup sg = getGroup();
1981     EditNameDialog dialog = new EditNameDialog(sg.getName(),
1982             sg.getDescription(),
1983             MessageManager.getString("label.group_name"),
1984             MessageManager.getString("label.group_description"));
1985     dialog.showDialog(ap.alignFrame,
1986             MessageManager.getString("label.edit_group_name_description"),
1987             new Runnable()
1988             {
1989               @Override
1990               public void run()
1991               {
1992                 sg.setName(dialog.getName());
1993                 sg.setDescription(dialog.getDescription());
1994                 refresh();
1995               }
1996             });
1997   }
1998
1999   /**
2000    * Get selection group - adding it to the alignment if necessary.
2001    * 
2002    * @return sequence group to operate on
2003    */
2004   SequenceGroup getGroup()
2005   {
2006     SequenceGroup sg = ap.av.getSelectionGroup();
2007     // this method won't add a new group if it already exists
2008     if (sg != null)
2009     {
2010       ap.av.getAlignment().addGroup(sg);
2011     }
2012
2013     return sg;
2014   }
2015
2016   /**
2017    * Shows a dialog where the sequence name and description may be edited. If a
2018    * name containing spaces is entered, these are converted to underscores, with a
2019    * warning message.
2020    */
2021   void sequenceName_actionPerformed()
2022   {
2023     EditNameDialog dialog = new EditNameDialog(sequence.getName(),
2024             sequence.getDescription(),
2025             MessageManager.getString("label.sequence_name"),
2026             MessageManager.getString("label.sequence_description"));
2027     dialog.showDialog(ap.alignFrame,
2028             MessageManager.getString(
2029                     "label.edit_sequence_name_description"),
2030             new Runnable()
2031             {
2032               @Override
2033               public void run()
2034               {
2035                 if (dialog.getName() != null)
2036                 {
2037                   if (dialog.getName().indexOf(" ") > -1)
2038                   {
2039                     JvOptionPane.showMessageDialog(ap,
2040                             MessageManager.getString(
2041                                     "label.spaces_converted_to_underscores"),
2042                             MessageManager.getString(
2043                                     "label.no_spaces_allowed_sequence_name"),
2044                             JvOptionPane.WARNING_MESSAGE);
2045                   }
2046                   sequence.setName(dialog.getName().replace(' ', '_'));
2047                   ap.paintAlignment(false, false);
2048                 }
2049                 sequence.setDescription(dialog.getDescription());
2050                 ap.av.firePropertyChange("alignment", null,
2051                         ap.av.getAlignment().getSequences());
2052               }
2053             });
2054   }
2055
2056   /**
2057    * DOCUMENT ME!
2058    * 
2059    * @param e
2060    *          DOCUMENT ME!
2061    */
2062   void unGroupMenuItem_actionPerformed()
2063   {
2064     SequenceGroup sg = ap.av.getSelectionGroup();
2065     ap.av.getAlignment().deleteGroup(sg);
2066     ap.av.setSelectionGroup(null);
2067     refresh();
2068   }
2069
2070   void createGroupMenuItem_actionPerformed()
2071   {
2072     getGroup(); // implicitly creates group - note - should apply defaults / use
2073                 // standard alignment window logic for this
2074     refresh();
2075   }
2076
2077   /**
2078    * Offers a colour chooser and sets the selected colour as the group outline
2079    */
2080   protected void outline_actionPerformed()
2081   {
2082     String title = MessageManager
2083             .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(),
2094             title, 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 }