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