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