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