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