JAL-1723 tooltip dbrefs sorted and limited to two per source
[jalview.git] / src / jalview / appletgui / APopupMenu.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.appletgui;
22
23 import jalview.analysis.AAFrequency;
24 import jalview.analysis.AlignmentAnnotationUtils;
25 import jalview.analysis.AlignmentUtils;
26 import jalview.analysis.Conservation;
27 import jalview.commands.ChangeCaseCommand;
28 import jalview.commands.EditCommand;
29 import jalview.commands.EditCommand.Action;
30 import jalview.datamodel.AlignmentAnnotation;
31 import jalview.datamodel.AlignmentI;
32 import jalview.datamodel.DBRefEntry;
33 import jalview.datamodel.PDBEntry;
34 import jalview.datamodel.SequenceFeature;
35 import jalview.datamodel.SequenceGroup;
36 import jalview.datamodel.SequenceI;
37 import jalview.io.AppletFormatAdapter;
38 import jalview.io.SequenceAnnotationReport;
39 import jalview.schemes.Blosum62ColourScheme;
40 import jalview.schemes.BuriedColourScheme;
41 import jalview.schemes.ClustalxColourScheme;
42 import jalview.schemes.HelixColourScheme;
43 import jalview.schemes.HydrophobicColourScheme;
44 import jalview.schemes.NucleotideColourScheme;
45 import jalview.schemes.PIDColourScheme;
46 import jalview.schemes.ResidueProperties;
47 import jalview.schemes.StrandColourScheme;
48 import jalview.schemes.TaylorColourScheme;
49 import jalview.schemes.TurnColourScheme;
50 import jalview.schemes.ZappoColourScheme;
51 import jalview.util.MessageManager;
52 import jalview.util.UrlLink;
53
54 import java.awt.CheckboxMenuItem;
55 import java.awt.Frame;
56 import java.awt.Menu;
57 import java.awt.MenuItem;
58 import java.awt.event.ActionEvent;
59 import java.awt.event.ActionListener;
60 import java.awt.event.ItemEvent;
61 import java.awt.event.ItemListener;
62 import java.util.Arrays;
63 import java.util.Collections;
64 import java.util.LinkedHashMap;
65 import java.util.List;
66 import java.util.Map;
67 import java.util.TreeMap;
68 import java.util.Vector;
69
70 public class APopupMenu extends java.awt.PopupMenu implements
71         ActionListener, ItemListener
72 {
73   private static final String ALL_ANNOTATIONS = "All";
74
75   Menu groupMenu = new Menu();
76
77   MenuItem editGroupName = new MenuItem();
78
79   protected MenuItem clustalColour = new MenuItem();
80
81   protected MenuItem zappoColour = new MenuItem();
82
83   protected MenuItem taylorColour = new MenuItem();
84
85   protected MenuItem hydrophobicityColour = new MenuItem();
86
87   protected MenuItem helixColour = new MenuItem();
88
89   protected MenuItem strandColour = new MenuItem();
90
91   protected MenuItem turnColour = new MenuItem();
92
93   protected MenuItem buriedColour = new MenuItem();
94
95   protected CheckboxMenuItem abovePIDColour = new CheckboxMenuItem();
96
97   protected MenuItem userDefinedColour = new MenuItem();
98
99   protected MenuItem PIDColour = new MenuItem();
100
101   protected MenuItem BLOSUM62Colour = new MenuItem();
102
103   MenuItem noColourmenuItem = new MenuItem();
104
105   protected CheckboxMenuItem conservationMenuItem = new CheckboxMenuItem();
106
107   final AlignmentPanel ap;
108
109   MenuItem unGroupMenuItem = new MenuItem();
110
111   MenuItem createGroupMenuItem = new MenuItem();
112
113   MenuItem nucleotideMenuItem = new MenuItem();
114
115   Menu colourMenu = new Menu();
116
117   CheckboxMenuItem showBoxes = new CheckboxMenuItem();
118
119   CheckboxMenuItem showText = new CheckboxMenuItem();
120
121   CheckboxMenuItem showColourText = new CheckboxMenuItem();
122
123   CheckboxMenuItem displayNonconserved = new CheckboxMenuItem();
124
125   Menu seqShowAnnotationsMenu = new Menu(
126           MessageManager.getString("label.show_annotations"));
127
128   Menu seqHideAnnotationsMenu = new Menu(
129           MessageManager.getString("label.hide_annotations"));
130
131   MenuItem seqAddReferenceAnnotations = new MenuItem(
132           MessageManager.getString("label.add_reference_annotations"));
133
134   Menu groupShowAnnotationsMenu = new Menu(
135           MessageManager.getString("label.show_annotations"));
136
137   Menu groupHideAnnotationsMenu = new Menu(
138           MessageManager.getString("label.hide_annotations"));
139
140   MenuItem groupAddReferenceAnnotations = new MenuItem(
141           MessageManager.getString("label.add_reference_annotations"));
142
143   Menu editMenu = new Menu(MessageManager.getString("action.edit"));
144
145   MenuItem copy = new MenuItem(MessageManager.getString("action.copy"));
146
147   MenuItem cut = new MenuItem(MessageManager.getString("action.cut"));
148
149   MenuItem toUpper = new MenuItem(
150           MessageManager.getString("label.to_upper_case"));
151
152   MenuItem toLower = new MenuItem(
153           MessageManager.getString("label.to_lower_case"));
154
155   MenuItem toggleCase = new MenuItem(
156           MessageManager.getString("label.toggle_case"));
157
158   Menu outputmenu = new Menu();
159
160   Menu seqMenu = new Menu();
161
162   MenuItem pdb = new MenuItem();
163
164   MenuItem hideSeqs = new MenuItem();
165
166   MenuItem repGroup = new MenuItem();
167
168   MenuItem sequenceName = new MenuItem(
169           MessageManager.getString("label.edit_name_description"));
170
171   MenuItem sequenceFeature = new MenuItem(
172           MessageManager.getString("label.create_sequence_feature"));
173
174   MenuItem editSequence = new MenuItem(
175           MessageManager.getString("label.edit_sequence"));
176
177   MenuItem sequenceDetails = new MenuItem(
178           MessageManager.getString("label.sequence_details"));
179
180   MenuItem selSeqDetails = new MenuItem(
181           MessageManager.getString("label.sequence_details"));
182
183   MenuItem makeReferenceSeq = new MenuItem();
184
185   SequenceI seq;
186
187   MenuItem revealAll = new MenuItem();
188
189   MenuItem revealSeq = new MenuItem();
190
191   /**
192    * index of sequence to be revealed
193    */
194   int revealSeq_index = -1;
195
196   Menu menu1 = new Menu();
197
198   public APopupMenu(AlignmentPanel apanel, final SequenceI seq,
199           Vector<String> links)
200   {
201     // /////////////////////////////////////////////////////////
202     // If this is activated from the sequence panel, the user may want to
203     // edit or annotate a particular residue. Therefore display the residue menu
204     //
205     // If from the IDPanel, we must display the sequence menu
206     // ////////////////////////////////////////////////////////
207
208     this.ap = apanel;
209     this.seq = seq;
210
211     try
212     {
213       jbInit();
214     } catch (Exception e)
215     {
216       e.printStackTrace();
217     }
218
219     for (int i = 0; i < jalview.io.AppletFormatAdapter.WRITEABLE_FORMATS.length; i++)
220     {
221       MenuItem item = new MenuItem(
222               jalview.io.AppletFormatAdapter.WRITEABLE_FORMATS[i]);
223
224       item.addActionListener(this);
225       outputmenu.add(item);
226     }
227
228     buildAnnotationSubmenus();
229
230     SequenceGroup sg = ap.av.getSelectionGroup();
231     if (sg != null && sg.getSize() > 0)
232     {
233       editGroupName.setLabel(MessageManager.formatMessage(
234               "label.name_param", new Object[] { sg.getName() }));
235       showText.setState(sg.getDisplayText());
236       showColourText.setState(sg.getColourText());
237       showBoxes.setState(sg.getDisplayBoxes());
238       displayNonconserved.setState(sg.getShowNonconserved());
239       if (!ap.av.getAlignment().getGroups().contains(sg))
240       {
241         menu1.setLabel(MessageManager.getString("action.edit_new_group"));
242         groupMenu.remove(unGroupMenuItem);
243       }
244       else
245       {
246         menu1.setLabel(MessageManager.getString("action.edit_group"));
247         groupMenu.remove(createGroupMenuItem);
248       }
249
250     }
251     else
252     {
253       remove(hideSeqs);
254       remove(groupMenu);
255     }
256
257     if (links != null && links.size() > 0)
258     {
259       Menu linkMenu = new Menu(MessageManager.getString("action.link"));
260       for (int i = 0; i < links.size(); i++)
261       {
262         String link = links.elementAt(i);
263         UrlLink urlLink = new UrlLink(link);
264         if (!urlLink.isValid())
265         {
266           System.err.println(urlLink.getInvalidMessage());
267           continue;
268         }
269         final String target = urlLink.getTarget(); // link.substring(0,
270         // link.indexOf("|"));
271         final String label = urlLink.getLabel();
272         if (seq != null && urlLink.isDynamic())
273         {
274
275           // collect matching db-refs
276           DBRefEntry[] dbr = jalview.util.DBRefUtils.selectRefs(
277                   seq.getDBRefs(), new String[] { target });
278           // collect id string too
279           String id = seq.getName();
280           String descr = seq.getDescription();
281           if (descr != null && descr.length() < 1)
282           {
283             descr = null;
284           }
285           if (dbr != null)
286           {
287             for (int r = 0; r < dbr.length; r++)
288             {
289               if (id != null && dbr[r].getAccessionId().equals(id))
290               {
291                 // suppress duplicate link creation for the bare sequence ID
292                 // string with this link
293                 id = null;
294               }
295               // create Bare ID link for this RUL
296               String[] urls = urlLink.makeUrls(dbr[r].getAccessionId(),
297                       true);
298               if (urls != null)
299               {
300                 for (int u = 0; u < urls.length; u += 2)
301                 {
302                   addshowLink(linkMenu, label + "|" + urls[u], urls[u + 1]);
303                 }
304               }
305             }
306           }
307           if (id != null)
308           {
309             // create Bare ID link for this RUL
310             String[] urls = urlLink.makeUrls(id, true);
311             if (urls != null)
312             {
313               for (int u = 0; u < urls.length; u += 2)
314               {
315                 addshowLink(linkMenu, label, urls[u + 1]);
316               }
317             }
318             // addshowLink(linkMenu, target, url_pref + id + url_suff);
319           }
320           // Now construct URLs from description but only try to do it for regex
321           // URL links
322           if (descr != null && urlLink.getRegexReplace() != null)
323           {
324             // create link for this URL from description only if regex matches
325             String[] urls = urlLink.makeUrls(descr, true);
326             if (urls != null)
327             {
328               for (int u = 0; u < urls.length; u += 2)
329               {
330                 addshowLink(linkMenu, label, urls[u + 1]);
331               }
332             }
333           }
334         }
335         else
336         {
337           addshowLink(linkMenu, target, urlLink.getUrl_prefix()); // link.substring(link.lastIndexOf("|")+1));
338         }
339         /*
340          * final String url;
341          * 
342          * if (link.indexOf("$SEQUENCE_ID$") > -1) { // Substitute SEQUENCE_ID
343          * string and any matching database reference accessions String url_pref
344          * = link.substring(link.indexOf("|") + 1,
345          * link.indexOf("$SEQUENCE_ID$"));
346          * 
347          * String url_suff = link.substring(link.indexOf("$SEQUENCE_ID$") + 13);
348          * // collect matching db-refs DBRefEntry[] dbr =
349          * jalview.util.DBRefUtils.selectRefs(seq.getDBRef(), new
350          * String[]{target}); // collect id string too String id =
351          * seq.getName(); if (id.indexOf("|") > -1) { id =
352          * id.substring(id.lastIndexOf("|") + 1); } if (dbr!=null) { for (int
353          * r=0;r<dbr.length; r++) { if (dbr[r].getAccessionId().equals(id)) { //
354          * suppress duplicate link creation for the bare sequence ID string with
355          * this link id = null; } addshowLink(linkMenu,
356          * dbr[r].getSource()+"|"+dbr[r].getAccessionId(), target,
357          * url_pref+dbr[r].getAccessionId()+url_suff); } } if (id!=null) { //
358          * create Bare ID link for this RUL addshowLink(linkMenu, target,
359          * url_pref + id + url_suff); } } else { addshowLink(linkMenu, target,
360          * link.substring(link.lastIndexOf("|")+1)); }
361          */
362       }
363       if (linkMenu.getItemCount() > 0)
364       {
365         if (seq != null)
366         {
367           seqMenu.add(linkMenu);
368         }
369         else
370         {
371           add(linkMenu);
372         }
373       }
374     }
375     // TODO: add group link menu entry here
376     if (seq != null)
377     {
378       seqMenu.setLabel(seq.getName());
379       if (seq == ap.av.getAlignment().getSeqrep())
380       {
381         makeReferenceSeq.setLabel(MessageManager
382                 .getString("action.unmark_as_reference"));// Unmark
383                                                           // representative");
384       }
385       else
386       {
387         makeReferenceSeq.setLabel(MessageManager
388                 .getString("action.set_as_reference")); // );
389       }
390       repGroup.setLabel(MessageManager.formatMessage(
391               "label.represent_group_with", new Object[] { seq.getName() }));
392     }
393     else
394     {
395       remove(seqMenu);
396     }
397
398     if (!ap.av.hasHiddenRows())
399     {
400       remove(revealAll);
401       remove(revealSeq);
402     }
403     else
404     {
405       final int index = ap.av.getAlignment().findIndex(seq);
406
407       if (ap.av.adjustForHiddenSeqs(index)
408               - ap.av.adjustForHiddenSeqs(index - 1) > 1)
409       {
410         revealSeq_index = index;
411       }
412       else
413       {
414         remove(revealSeq);
415       }
416     }
417   }
418
419   /**
420    * Build menus for annotation types that may be shown or hidden, and for
421    * 'reference annotations' that may be added to the alignment.
422    */
423   private void buildAnnotationSubmenus()
424   {
425     /*
426      * First for the currently selected sequence (if there is one):
427      */
428     final List<SequenceI> selectedSequence = (seq == null ? Collections
429             .<SequenceI> emptyList() : Arrays.asList(seq));
430     buildAnnotationTypesMenus(seqShowAnnotationsMenu,
431             seqHideAnnotationsMenu, selectedSequence);
432     configureReferenceAnnotationsMenu(seqAddReferenceAnnotations,
433             selectedSequence);
434
435     /*
436      * and repeat for the current selection group (if there is one):
437      */
438     final List<SequenceI> selectedGroup = (ap.av.getSelectionGroup() == null ? Collections
439             .<SequenceI> emptyList() : ap.av.getSelectionGroup()
440             .getSequences());
441     buildAnnotationTypesMenus(groupShowAnnotationsMenu,
442             groupHideAnnotationsMenu, selectedGroup);
443     configureReferenceAnnotationsMenu(groupAddReferenceAnnotations,
444             selectedGroup);
445   }
446
447   /**
448    * Determine whether or not to enable 'add reference annotations' menu item.
449    * It is enable if there are any annotations, on any of the selected
450    * sequences, which are not yet on the alignment (visible or not).
451    * 
452    * @param menu
453    * @param forSequences
454    */
455   private void configureReferenceAnnotationsMenu(MenuItem menuItem,
456           List<SequenceI> forSequences)
457   {
458     menuItem.setEnabled(false);
459
460     /*
461      * Temporary store to hold distinct calcId / type pairs for the tooltip.
462      * Using TreeMap means calcIds are shown in alphabetical order.
463      */
464     Map<String, String> tipEntries = new TreeMap<String, String>();
465     final Map<SequenceI, List<AlignmentAnnotation>> candidates = new LinkedHashMap<SequenceI, List<AlignmentAnnotation>>();
466     AlignmentI al = this.ap.av.getAlignment();
467     AlignmentUtils.findAddableReferenceAnnotations(forSequences,
468             tipEntries, candidates, al);
469     if (!candidates.isEmpty())
470     {
471       StringBuilder tooltip = new StringBuilder(64);
472       tooltip.append(MessageManager.getString("label.add_annotations_for"));
473
474       /*
475        * Found annotations that could be added. Enable the menu item, and
476        * configure its action.
477        */
478       menuItem.setEnabled(true);
479
480       menuItem.addActionListener(new ActionListener()
481       {
482         @Override
483         public void actionPerformed(ActionEvent e)
484         {
485           addReferenceAnnotations_actionPerformed(candidates);
486         }
487       });
488     }
489   }
490
491   /**
492    * Add annotations to the sequences and to the alignment.
493    * 
494    * @param candidates
495    *          a map whose keys are sequences on the alignment, and values a list
496    *          of annotations to add to each sequence
497    */
498   protected void addReferenceAnnotations_actionPerformed(
499           Map<SequenceI, List<AlignmentAnnotation>> candidates)
500   {
501     final SequenceGroup selectionGroup = this.ap.av.getSelectionGroup();
502     final AlignmentI alignment = this.ap.getAlignment();
503     AlignmentUtils.addReferenceAnnotations(candidates, alignment,
504             selectionGroup);
505     refresh();
506   }
507
508   /**
509    * add a show URL menu item to the given linkMenu
510    * 
511    * @param linkMenu
512    * @param target
513    *          - menu label string
514    * @param url
515    *          - url to open
516    */
517   private void addshowLink(Menu linkMenu, final String target,
518           final String url)
519   {
520     addshowLink(linkMenu, target, target, url);
521   }
522
523   /**
524    * add a show URL menu item to the given linkMenu
525    * 
526    * @param linkMenu
527    * @param target
528    *          - URL target window
529    * @param label
530    *          - menu label string
531    * @param url
532    *          - url to open
533    */
534   private void addshowLink(Menu linkMenu, final String target,
535           final String label, final String url)
536   {
537     MenuItem item = new MenuItem(label);
538     item.addActionListener(new java.awt.event.ActionListener()
539     {
540       @Override
541       public void actionPerformed(ActionEvent e)
542       {
543         ap.alignFrame.showURL(url, target);
544       }
545     });
546     linkMenu.add(item);
547   }
548
549   @Override
550   public void itemStateChanged(ItemEvent evt)
551   {
552     if (evt.getSource() == abovePIDColour)
553     {
554       abovePIDColour_itemStateChanged();
555     }
556     else if (evt.getSource() == showColourText)
557     {
558       showColourText_itemStateChanged();
559     }
560     else if (evt.getSource() == showText)
561     {
562       showText_itemStateChanged();
563     }
564     else if (evt.getSource() == showBoxes)
565     {
566       showBoxes_itemStateChanged();
567     }
568     else if (evt.getSource() == displayNonconserved)
569     {
570       this.showNonconserved_itemStateChanged();
571     }
572   }
573
574   @Override
575   public void actionPerformed(ActionEvent evt)
576   {
577     Object source = evt.getSource();
578     if (source == clustalColour)
579     {
580       clustalColour_actionPerformed();
581     }
582     else if (source == zappoColour)
583     {
584       zappoColour_actionPerformed();
585     }
586     else if (source == taylorColour)
587     {
588       taylorColour_actionPerformed();
589     }
590     else if (source == hydrophobicityColour)
591     {
592       hydrophobicityColour_actionPerformed();
593     }
594     else if (source == helixColour)
595     {
596       helixColour_actionPerformed();
597     }
598     else if (source == strandColour)
599     {
600       strandColour_actionPerformed();
601     }
602     else if (source == turnColour)
603     {
604       turnColour_actionPerformed();
605     }
606     else if (source == buriedColour)
607     {
608       buriedColour_actionPerformed();
609     }
610     else if (source == nucleotideMenuItem)
611     {
612       nucleotideMenuItem_actionPerformed();
613     }
614
615     else if (source == userDefinedColour)
616     {
617       userDefinedColour_actionPerformed();
618     }
619     else if (source == PIDColour)
620     {
621       PIDColour_actionPerformed();
622     }
623     else if (source == BLOSUM62Colour)
624     {
625       BLOSUM62Colour_actionPerformed();
626     }
627     else if (source == noColourmenuItem)
628     {
629       noColourmenuItem_actionPerformed();
630     }
631     else if (source == conservationMenuItem)
632     {
633       conservationMenuItem_itemStateChanged();
634     }
635     else if (source == unGroupMenuItem)
636     {
637       unGroupMenuItem_actionPerformed();
638     }
639
640     else if (source == createGroupMenuItem)
641     {
642       createGroupMenuItem_actionPerformed();
643     }
644
645     else if (source == sequenceName)
646     {
647       editName();
648     }
649     else if (source == makeReferenceSeq)
650     {
651       makeReferenceSeq_actionPerformed();
652     }
653     else if (source == sequenceDetails)
654     {
655       showSequenceDetails();
656     }
657     else if (source == selSeqDetails)
658     {
659       showSequenceSelectionDetails();
660     }
661     else if (source == pdb)
662     {
663       addPDB();
664     }
665     else if (source == hideSeqs)
666     {
667       hideSequences(false);
668     }
669     else if (source == repGroup)
670     {
671       hideSequences(true);
672     }
673     else if (source == revealSeq)
674     {
675       ap.av.showSequence(revealSeq_index);
676     }
677     else if (source == revealAll)
678     {
679       ap.av.showAllHiddenSeqs();
680     }
681
682     else if (source == editGroupName)
683     {
684       EditNameDialog dialog = new EditNameDialog(getGroup().getName(),
685               getGroup().getDescription(), "       Group Name",
686               "Group Description", ap.alignFrame,
687               "Edit Group Name / Description", 500, 100, true);
688
689       if (dialog.accept)
690       {
691         getGroup().setName(dialog.getName().replace(' ', '_'));
692         getGroup().setDescription(dialog.getDescription());
693       }
694
695     }
696     else if (source == copy)
697     {
698       ap.alignFrame.copy_actionPerformed();
699     }
700     else if (source == cut)
701     {
702       ap.alignFrame.cut_actionPerformed();
703     }
704     else if (source == editSequence)
705     {
706       SequenceGroup sg = ap.av.getSelectionGroup();
707
708       if (sg != null)
709       {
710         if (seq == null)
711         {
712           seq = sg.getSequenceAt(0);
713         }
714
715         EditNameDialog dialog = new EditNameDialog(seq.getSequenceAsString(
716                 sg.getStartRes(), sg.getEndRes() + 1), null,
717                 "Edit Sequence ", null,
718
719                 ap.alignFrame, "Edit Sequence", 500, 100, true);
720
721         if (dialog.accept)
722         {
723           EditCommand editCommand = new EditCommand(
724                   MessageManager.getString("label.edit_sequences"),
725                   Action.REPLACE, dialog.getName().replace(' ',
726                           ap.av.getGapCharacter()),
727                   sg.getSequencesAsArray(ap.av.getHiddenRepSequences()),
728                   sg.getStartRes(), sg.getEndRes() + 1,
729                   ap.av.getAlignment());
730
731           ap.alignFrame.addHistoryItem(editCommand);
732
733           ap.av.firePropertyChange("alignment", null, ap.av.getAlignment()
734                   .getSequences());
735         }
736       }
737     }
738     else if (source == toUpper || source == toLower || source == toggleCase)
739     {
740       SequenceGroup sg = ap.av.getSelectionGroup();
741       if (sg != null)
742       {
743         List<int[]> startEnd = ap.av.getVisibleRegionBoundaries(
744                 sg.getStartRes(), sg.getEndRes() + 1);
745
746         String description;
747         int caseChange;
748
749         if (source == toggleCase)
750         {
751           description = "Toggle Case";
752           caseChange = ChangeCaseCommand.TOGGLE_CASE;
753         }
754         else if (source == toUpper)
755         {
756           description = "To Upper Case";
757           caseChange = ChangeCaseCommand.TO_UPPER;
758         }
759         else
760         {
761           description = "To Lower Case";
762           caseChange = ChangeCaseCommand.TO_LOWER;
763         }
764
765         ChangeCaseCommand caseCommand = new ChangeCaseCommand(description,
766                 sg.getSequencesAsArray(ap.av.getHiddenRepSequences()),
767                 startEnd, caseChange);
768
769         ap.alignFrame.addHistoryItem(caseCommand);
770
771         ap.av.firePropertyChange("alignment", null, ap.av.getAlignment()
772                 .getSequences());
773
774       }
775     }
776     else if (source == sequenceFeature)
777     {
778       SequenceGroup sg = ap.av.getSelectionGroup();
779       if (sg == null)
780       {
781         return;
782       }
783
784       int rsize = 0, gSize = sg.getSize();
785       SequenceI[] rseqs, seqs = new SequenceI[gSize];
786       SequenceFeature[] tfeatures, features = new SequenceFeature[gSize];
787
788       for (int i = 0; i < gSize; i++)
789       {
790         int start = sg.getSequenceAt(i).findPosition(sg.getStartRes());
791         int end = sg.findEndRes(sg.getSequenceAt(i));
792         if (start <= end)
793         {
794           seqs[rsize] = sg.getSequenceAt(i);
795           features[rsize] = new SequenceFeature(null, null, null, start,
796                   end, "Jalview");
797           rsize++;
798         }
799       }
800       rseqs = new SequenceI[rsize];
801       tfeatures = new SequenceFeature[rsize];
802       System.arraycopy(seqs, 0, rseqs, 0, rsize);
803       System.arraycopy(features, 0, tfeatures, 0, rsize);
804       features = tfeatures;
805       seqs = rseqs;
806
807       if (ap.seqPanel.seqCanvas.getFeatureRenderer().amendFeatures(seqs,
808               features, true, ap))
809       {
810         ap.alignFrame.sequenceFeatures.setState(true);
811         ap.av.setShowSequenceFeatures(true);
812         ;
813         ap.highlightSearchResults(null);
814       }
815     }
816     else
817     {
818       outputText(evt);
819     }
820
821   }
822
823   void outputText(ActionEvent e)
824   {
825     CutAndPasteTransfer cap = new CutAndPasteTransfer(true, ap.alignFrame);
826
827     Frame frame = new Frame();
828     frame.add(cap);
829     jalview.bin.JalviewLite.addFrame(frame, MessageManager.formatMessage(
830             "label.selection_output_command",
831             new Object[] { e.getActionCommand() }), 600, 500);
832     // JBPNote: getSelectionAsNewSequence behaviour has changed - this method
833     // now returns a full copy of sequence data
834     // TODO consider using getSequenceSelection instead here
835
836     cap.setText(new jalview.io.AppletFormatAdapter().formatSequences(
837             e.getActionCommand(), ap.av.getShowJVSuffix(), ap, true));
838
839   }
840
841   protected void showSequenceSelectionDetails()
842   {
843     createSequenceDetailsReport(ap.av.getSequenceSelection());
844   }
845
846   protected void showSequenceDetails()
847   {
848     createSequenceDetailsReport(new SequenceI[] { seq });
849   }
850
851   public void createSequenceDetailsReport(SequenceI[] sequences)
852   {
853
854     CutAndPasteTransfer cap = new CutAndPasteTransfer(false, ap.alignFrame);
855
856     StringBuilder contents = new StringBuilder(128);
857     for (SequenceI seq : sequences)
858     {
859       contents.append(MessageManager.formatMessage(
860               "label.annotation_for_displayid",
861               new Object[] { seq.getDisplayId(true) }));
862       new SequenceAnnotationReport(null).createSequenceAnnotationReport(
863               contents,
864               seq,
865               true,
866               true,
867               (ap.seqPanel.seqCanvas.fr != null) ? ap.seqPanel.seqCanvas.fr
868                       .getMinMax() : null);
869       contents.append("</p>");
870     }
871     Frame frame = new Frame();
872     frame.add(cap);
873     jalview.bin.JalviewLite.addFrame(frame, "Sequence Details for "
874             + (sequences.length == 1 ? sequences[0].getDisplayId(true)
875                     : "Selection"), 600, 500);
876     cap.setText(MessageManager.formatMessage("label.html_content",
877             new Object[] { contents.toString() }));
878   }
879
880   void editName()
881   {
882     EditNameDialog dialog = new EditNameDialog(seq.getName(),
883             seq.getDescription(), "       Sequence Name",
884             "Sequence Description", ap.alignFrame,
885             "Edit Sequence Name / Description", 500, 100, true);
886
887     if (dialog.accept)
888     {
889       seq.setName(dialog.getName());
890       seq.setDescription(dialog.getDescription());
891       ap.paintAlignment(false);
892     }
893   }
894
895   void addPDB()
896   {
897     if (seq.getAllPDBEntries() != null)
898     {
899       PDBEntry entry = seq.getAllPDBEntries().firstElement();
900
901       if (ap.av.applet.jmolAvailable)
902       {
903         new jalview.appletgui.AppletJmol(entry, new SequenceI[] { seq },
904                 null, ap, AppletFormatAdapter.URL);
905       }
906       else
907       {
908         new MCview.AppletPDBViewer(entry, new SequenceI[] { seq }, null,
909                 ap, AppletFormatAdapter.URL);
910       }
911
912     }
913     else
914     {
915       CutAndPasteTransfer cap = new CutAndPasteTransfer(true, ap.alignFrame);
916       cap.setText(MessageManager.getString("label.paste_pdb_file"));
917       cap.setPDBImport(seq);
918       Frame frame = new Frame();
919       frame.add(cap);
920       jalview.bin.JalviewLite.addFrame(frame, MessageManager.formatMessage(
921               "label.paste_pdb_file_for_sequence",
922               new Object[] { seq.getName() }), 400, 300);
923     }
924   }
925
926   private void jbInit() throws Exception
927   {
928     groupMenu.setLabel(MessageManager.getString("label.selection"));
929     sequenceFeature.addActionListener(this);
930
931     editGroupName.addActionListener(this);
932     unGroupMenuItem.setLabel(MessageManager
933             .getString("action.remove_group"));
934     unGroupMenuItem.addActionListener(this);
935
936     createGroupMenuItem.setLabel(MessageManager
937             .getString("action.create_group"));
938     createGroupMenuItem.addActionListener(this);
939
940     nucleotideMenuItem.setLabel(MessageManager
941             .getString("label.nucleotide"));
942     nucleotideMenuItem.addActionListener(this);
943     conservationMenuItem.addItemListener(this);
944     abovePIDColour.addItemListener(this);
945     colourMenu.setLabel(MessageManager.getString("label.group_colour"));
946     showBoxes.setLabel(MessageManager.getString("action.boxes"));
947     showBoxes.setState(true);
948     showBoxes.addItemListener(this);
949     sequenceName.addActionListener(this);
950     sequenceDetails.addActionListener(this);
951     selSeqDetails.addActionListener(this);
952     displayNonconserved.setLabel(MessageManager
953             .getString("label.show_non_conversed"));
954     displayNonconserved.setState(false);
955     displayNonconserved.addItemListener(this);
956     showText.setLabel(MessageManager.getString("action.text"));
957     showText.addItemListener(this);
958     showColourText.setLabel(MessageManager.getString("label.colour_text"));
959     showColourText.addItemListener(this);
960     outputmenu.setLabel(MessageManager.getString("label.out_to_textbox"));
961     seqMenu.setLabel(MessageManager.getString("label.sequence"));
962     pdb.setLabel(MessageManager.getString("label.view_pdb_structure"));
963     hideSeqs.setLabel(MessageManager.getString("action.hide_sequences"));
964     repGroup.setLabel(MessageManager.formatMessage(
965             "label.represent_group_with", new Object[] { "" }));
966     revealAll.setLabel(MessageManager.getString("action.reveal_all"));
967     revealSeq.setLabel(MessageManager.getString("action.reveal_sequences"));
968     menu1.setLabel(MessageManager.getString("label.group") + ":");
969     add(groupMenu);
970     this.add(seqMenu);
971     this.add(hideSeqs);
972     this.add(revealSeq);
973     this.add(revealAll);
974     // groupMenu.add(selSeqDetails);
975     groupMenu.add(groupShowAnnotationsMenu);
976     groupMenu.add(groupHideAnnotationsMenu);
977     groupMenu.add(groupAddReferenceAnnotations);
978     groupMenu.add(editMenu);
979     groupMenu.add(outputmenu);
980     groupMenu.add(sequenceFeature);
981     groupMenu.add(createGroupMenuItem);
982     groupMenu.add(unGroupMenuItem);
983     groupMenu.add(menu1);
984
985     colourMenu.add(noColourmenuItem);
986     colourMenu.add(clustalColour);
987     colourMenu.add(BLOSUM62Colour);
988     colourMenu.add(PIDColour);
989     colourMenu.add(zappoColour);
990     colourMenu.add(taylorColour);
991     colourMenu.add(hydrophobicityColour);
992     colourMenu.add(helixColour);
993     colourMenu.add(strandColour);
994     colourMenu.add(turnColour);
995     colourMenu.add(buriedColour);
996     colourMenu.add(nucleotideMenuItem);
997     colourMenu.add(userDefinedColour);
998     colourMenu.addSeparator();
999     colourMenu.add(abovePIDColour);
1000     colourMenu.add(conservationMenuItem);
1001
1002     noColourmenuItem.setLabel(MessageManager.getString("label.none"));
1003     noColourmenuItem.addActionListener(this);
1004
1005     clustalColour.setLabel(MessageManager
1006             .getString("label.clustalx_colours"));
1007     clustalColour.addActionListener(this);
1008     zappoColour.setLabel(MessageManager.getString("label.zappo"));
1009     zappoColour.addActionListener(this);
1010     taylorColour.setLabel(MessageManager.getString("label.taylor"));
1011     taylorColour.addActionListener(this);
1012     hydrophobicityColour.setLabel(MessageManager
1013             .getString("label.hydrophobicity"));
1014     hydrophobicityColour.addActionListener(this);
1015     helixColour
1016             .setLabel(MessageManager.getString("label.helix_propensity"));
1017     helixColour.addActionListener(this);
1018     strandColour.setLabel(MessageManager
1019             .getString("label.strand_propensity"));
1020     strandColour.addActionListener(this);
1021     turnColour.setLabel(MessageManager.getString("label.turn_propensity"));
1022     turnColour.addActionListener(this);
1023     buriedColour.setLabel(MessageManager.getString("label.buried_index"));
1024     buriedColour.addActionListener(this);
1025     abovePIDColour.setLabel(MessageManager
1026             .getString("label.above_identity_percentage"));
1027
1028     userDefinedColour.setLabel(MessageManager
1029             .getString("action.user_defined"));
1030     userDefinedColour.addActionListener(this);
1031     PIDColour.setLabel(MessageManager
1032             .getString("label.percentage_identity"));
1033     PIDColour.addActionListener(this);
1034     BLOSUM62Colour.setLabel("BLOSUM62");
1035     BLOSUM62Colour.addActionListener(this);
1036     conservationMenuItem.setLabel(MessageManager
1037             .getString("label.conservation"));
1038
1039     editMenu.add(copy);
1040     copy.addActionListener(this);
1041     editMenu.add(cut);
1042     cut.addActionListener(this);
1043
1044     editMenu.add(editSequence);
1045     editSequence.addActionListener(this);
1046
1047     editMenu.add(toUpper);
1048     toUpper.addActionListener(this);
1049     editMenu.add(toLower);
1050     toLower.addActionListener(this);
1051     editMenu.add(toggleCase);
1052     seqMenu.add(seqShowAnnotationsMenu);
1053     seqMenu.add(seqHideAnnotationsMenu);
1054     seqMenu.add(seqAddReferenceAnnotations);
1055     seqMenu.add(sequenceName);
1056     seqMenu.add(makeReferenceSeq);
1057     // seqMenu.add(sequenceDetails);
1058
1059     if (!ap.av.applet.useXtrnalSviewer)
1060     {
1061       seqMenu.add(pdb);
1062     }
1063     seqMenu.add(repGroup);
1064     menu1.add(editGroupName);
1065     menu1.add(colourMenu);
1066     menu1.add(showBoxes);
1067     menu1.add(showText);
1068     menu1.add(showColourText);
1069     menu1.add(displayNonconserved);
1070     toggleCase.addActionListener(this);
1071     pdb.addActionListener(this);
1072     hideSeqs.addActionListener(this);
1073     repGroup.addActionListener(this);
1074     revealAll.addActionListener(this);
1075     revealSeq.addActionListener(this);
1076     makeReferenceSeq.addActionListener(this);
1077   }
1078
1079   void refresh()
1080   {
1081     ap.paintAlignment(true);
1082   }
1083
1084   protected void clustalColour_actionPerformed()
1085   {
1086     SequenceGroup sg = getGroup();
1087     sg.cs = new ClustalxColourScheme(sg, ap.av.getHiddenRepSequences());
1088     refresh();
1089   }
1090
1091   protected void zappoColour_actionPerformed()
1092   {
1093     getGroup().cs = new ZappoColourScheme();
1094     refresh();
1095   }
1096
1097   protected void taylorColour_actionPerformed()
1098   {
1099     getGroup().cs = new TaylorColourScheme();
1100     refresh();
1101   }
1102
1103   protected void hydrophobicityColour_actionPerformed()
1104   {
1105     getGroup().cs = new HydrophobicColourScheme();
1106     refresh();
1107   }
1108
1109   protected void helixColour_actionPerformed()
1110   {
1111     getGroup().cs = new HelixColourScheme();
1112     refresh();
1113   }
1114
1115   protected void strandColour_actionPerformed()
1116   {
1117     getGroup().cs = new StrandColourScheme();
1118     refresh();
1119   }
1120
1121   protected void turnColour_actionPerformed()
1122   {
1123     getGroup().cs = new TurnColourScheme();
1124     refresh();
1125   }
1126
1127   protected void buriedColour_actionPerformed()
1128   {
1129     getGroup().cs = new BuriedColourScheme();
1130     refresh();
1131   }
1132
1133   public void nucleotideMenuItem_actionPerformed()
1134   {
1135     getGroup().cs = new NucleotideColourScheme();
1136     refresh();
1137   }
1138
1139   protected void abovePIDColour_itemStateChanged()
1140   {
1141     SequenceGroup sg = getGroup();
1142     if (sg.cs == null)
1143     {
1144       return;
1145     }
1146
1147     if (abovePIDColour.getState())
1148     {
1149       sg.cs.setConsensus(AAFrequency.calculate(sg.getSequences(ap.av
1150               .getHiddenRepSequences()), 0, ap.av.getAlignment().getWidth()));
1151       int threshold = SliderPanel.setPIDSliderSource(ap, sg.cs, getGroup()
1152               .getName());
1153
1154       sg.cs.setThreshold(threshold, ap.av.isIgnoreGapsConsensus());
1155
1156       SliderPanel.showPIDSlider();
1157
1158     }
1159     else
1160     // remove PIDColouring
1161     {
1162       sg.cs.setThreshold(0, ap.av.isIgnoreGapsConsensus());
1163     }
1164
1165     refresh();
1166
1167   }
1168
1169   protected void userDefinedColour_actionPerformed()
1170   {
1171     new UserDefinedColours(ap, getGroup());
1172   }
1173
1174   protected void PIDColour_actionPerformed()
1175   {
1176     SequenceGroup sg = getGroup();
1177     sg.cs = new PIDColourScheme();
1178     sg.cs.setConsensus(AAFrequency.calculate(sg.getSequences(ap.av
1179             .getHiddenRepSequences()), 0, ap.av.getAlignment().getWidth()));
1180     refresh();
1181   }
1182
1183   protected void BLOSUM62Colour_actionPerformed()
1184   {
1185     SequenceGroup sg = getGroup();
1186
1187     sg.cs = new Blosum62ColourScheme();
1188
1189     sg.cs.setConsensus(AAFrequency.calculate(sg.getSequences(ap.av
1190             .getHiddenRepSequences()), 0, ap.av.getAlignment().getWidth()));
1191
1192     refresh();
1193   }
1194
1195   protected void noColourmenuItem_actionPerformed()
1196   {
1197     getGroup().cs = null;
1198     refresh();
1199   }
1200
1201   protected void conservationMenuItem_itemStateChanged()
1202   {
1203     SequenceGroup sg = getGroup();
1204     if (sg.cs == null)
1205     {
1206       return;
1207     }
1208
1209     if (conservationMenuItem.getState())
1210     {
1211
1212       sg.cs.setConservation(Conservation.calculateConservation("Group",
1213               ResidueProperties.propHash, 3, sg.getSequences(ap.av
1214                       .getHiddenRepSequences()), 0, ap.av.getAlignment()
1215                       .getWidth(), false, ap.av.getConsPercGaps(), false));
1216       SliderPanel.setConservationSlider(ap, sg.cs, sg.getName());
1217       SliderPanel.showConservationSlider();
1218     }
1219     else
1220     // remove ConservationColouring
1221     {
1222       sg.cs.setConservation(null);
1223     }
1224
1225     refresh();
1226   }
1227
1228   SequenceGroup getGroup()
1229   {
1230     SequenceGroup sg = ap.av.getSelectionGroup();
1231
1232     // this method won't add a new group if it already exists
1233     if (sg != null)
1234     {
1235       ap.av.getAlignment().addGroup(sg);
1236     }
1237
1238     return sg;
1239   }
1240
1241   void unGroupMenuItem_actionPerformed()
1242   {
1243     SequenceGroup sg = ap.av.getSelectionGroup();
1244     ap.av.getAlignment().deleteGroup(sg);
1245     ap.av.setSelectionGroup(null);
1246     ap.paintAlignment(true);
1247   }
1248
1249   void createGroupMenuItem_actionPerformed()
1250   {
1251     getGroup(); // implicitly create group
1252     refresh();
1253   }
1254
1255   public void showColourText_itemStateChanged()
1256   {
1257     getGroup().setColourText(showColourText.getState());
1258     refresh();
1259   }
1260
1261   public void showText_itemStateChanged()
1262   {
1263     getGroup().setDisplayText(showText.getState());
1264     refresh();
1265   }
1266
1267   public void makeReferenceSeq_actionPerformed()
1268   {
1269     if (!ap.av.getAlignment().hasSeqrep())
1270     {
1271       // initialise the display flags so the user sees something happen
1272       ap.av.setDisplayReferenceSeq(true);
1273       ap.av.setColourByReferenceSeq(true);
1274       ap.av.getAlignment().setSeqrep(seq);
1275     }
1276     else
1277     {
1278       if (ap.av.getAlignment().getSeqrep() == seq)
1279       {
1280         ap.av.getAlignment().setSeqrep(null);
1281       }
1282       else
1283       {
1284         ap.av.getAlignment().setSeqrep(seq);
1285       }
1286     }
1287     refresh();
1288   }
1289
1290   public void showNonconserved_itemStateChanged()
1291   {
1292     getGroup().setShowNonconserved(this.displayNonconserved.getState());
1293     refresh();
1294   }
1295
1296   public void showBoxes_itemStateChanged()
1297   {
1298     getGroup().setDisplayBoxes(showBoxes.getState());
1299     refresh();
1300   }
1301
1302   void hideSequences(boolean representGroup)
1303   {
1304     SequenceGroup sg = ap.av.getSelectionGroup();
1305     if (sg == null || sg.getSize() < 1)
1306     {
1307       ap.av.hideSequence(new SequenceI[] { seq });
1308       return;
1309     }
1310
1311     ap.av.setSelectionGroup(null);
1312
1313     if (representGroup)
1314     {
1315       ap.av.hideRepSequences(seq, sg);
1316
1317       return;
1318     }
1319
1320     int gsize = sg.getSize();
1321     SequenceI[] hseqs;
1322
1323     hseqs = new SequenceI[gsize];
1324
1325     int index = 0;
1326     for (int i = 0; i < gsize; i++)
1327     {
1328       hseqs[index++] = sg.getSequenceAt(i);
1329     }
1330
1331     ap.av.hideSequence(hseqs);
1332     ap.av.sendSelection();
1333   }
1334
1335   /**
1336    * Add annotation types to 'Show annotations' and/or 'Hide annotations' menus.
1337    * "All" is added first, followed by a separator. Then add any annotation
1338    * types associated with the current selection. Separate menus are built for
1339    * the selected sequence group (if any), and the selected sequence.
1340    * <p>
1341    * Some annotation rows are always rendered together - these can be identified
1342    * by a common graphGroup property > -1. Only one of each group will be marked
1343    * as visible (to avoid duplication of the display). For such groups we add a
1344    * composite type name, e.g.
1345    * <p>
1346    * IUPredWS (Long), IUPredWS (Short)
1347    * 
1348    * @param seq
1349    */
1350   protected void buildAnnotationTypesMenus(Menu showMenu, Menu hideMenu,
1351           List<SequenceI> forSequences)
1352   {
1353     showMenu.removeAll();
1354     hideMenu.removeAll();
1355
1356     final List<String> all = Arrays.asList(ALL_ANNOTATIONS);
1357     addAnnotationTypeToShowHide(showMenu, forSequences, "", all, true, true);
1358     addAnnotationTypeToShowHide(hideMenu, forSequences, "", all, true,
1359             false);
1360     showMenu.addSeparator();
1361     hideMenu.addSeparator();
1362
1363     final AlignmentAnnotation[] annotations = ap.getAlignment()
1364             .getAlignmentAnnotation();
1365
1366     /*
1367      * Find shown/hidden annotations types, distinguished by source (calcId),
1368      * and grouped by graphGroup. Using LinkedHashMap means we will retrieve in
1369      * the insertion order, which is the order of the annotations on the
1370      * alignment.
1371      */
1372     Map<String, List<List<String>>> shownTypes = new LinkedHashMap<String, List<List<String>>>();
1373     Map<String, List<List<String>>> hiddenTypes = new LinkedHashMap<String, List<List<String>>>();
1374     AlignmentAnnotationUtils.getShownHiddenTypes(shownTypes, hiddenTypes,
1375             AlignmentAnnotationUtils.asList(annotations), forSequences);
1376
1377     for (String calcId : hiddenTypes.keySet())
1378     {
1379       for (List<String> type : hiddenTypes.get(calcId))
1380       {
1381         addAnnotationTypeToShowHide(showMenu, forSequences, calcId, type,
1382                 false, true);
1383       }
1384     }
1385     // grey out 'show annotations' if none are hidden
1386     showMenu.setEnabled(!hiddenTypes.isEmpty());
1387
1388     for (String calcId : shownTypes.keySet())
1389     {
1390       for (List<String> type : shownTypes.get(calcId))
1391       {
1392         addAnnotationTypeToShowHide(hideMenu, forSequences, calcId, type,
1393                 false, false);
1394       }
1395     }
1396     // grey out 'hide annotations' if none are shown
1397     hideMenu.setEnabled(!shownTypes.isEmpty());
1398   }
1399
1400   /**
1401    * Add one annotation type to the 'Show Annotations' or 'Hide Annotations'
1402    * menus.
1403    * 
1404    * @param showOrHideMenu
1405    *          the menu to add to
1406    * @param forSequences
1407    *          the sequences whose annotations may be shown or hidden
1408    * @param calcId
1409    * @param types
1410    *          the label to add
1411    * @param allTypes
1412    *          if true this is a special label meaning 'All'
1413    * @param actionIsShow
1414    *          if true, the select menu item action is to show the annotation
1415    *          type, else hide
1416    */
1417   protected void addAnnotationTypeToShowHide(Menu showOrHideMenu,
1418           final List<SequenceI> forSequences, String calcId,
1419           final List<String> types, final boolean allTypes,
1420           final boolean actionIsShow)
1421   {
1422     String label = types.toString(); // [a, b, c]
1423     label = label.substring(1, label.length() - 1);
1424     final MenuItem item = new MenuItem(label);
1425     item.addActionListener(new java.awt.event.ActionListener()
1426     {
1427       @Override
1428       public void actionPerformed(ActionEvent e)
1429       {
1430         AlignmentUtils.showOrHideSequenceAnnotations(ap.getAlignment(),
1431                 types, forSequences, allTypes, actionIsShow);
1432         refresh();
1433       }
1434     });
1435     showOrHideMenu.add(item);
1436   }
1437
1438 }