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