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