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