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