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