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