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