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