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