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