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