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