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