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