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