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