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