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