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