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