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