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