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