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