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