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