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