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