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