JAL-2371 CollectionColourScheme wraps ColourSchemeI
[jalview.git] / src / jalview / gui / PopupMenu.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.gui;
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.Annotation;
34 import jalview.datamodel.ColumnSelection;
35 import jalview.datamodel.DBRefEntry;
36 import jalview.datamodel.PDBEntry;
37 import jalview.datamodel.Sequence;
38 import jalview.datamodel.SequenceFeature;
39 import jalview.datamodel.SequenceGroup;
40 import jalview.datamodel.SequenceI;
41 import jalview.gui.ColourMenuHelper.ColourChangeListener;
42 import jalview.io.FileFormat;
43 import jalview.io.FileFormatI;
44 import jalview.io.FormatAdapter;
45 import jalview.io.SequenceAnnotationReport;
46 import jalview.schemes.AnnotationColourGradient;
47 import jalview.schemes.Blosum62ColourScheme;
48 import jalview.schemes.ColourSchemeI;
49 import jalview.schemes.ColourSchemes;
50 import jalview.schemes.PIDColourScheme;
51 import jalview.schemes.ResidueColourScheme;
52 import jalview.util.GroupUrlLink;
53 import jalview.util.GroupUrlLink.UrlStringTooLongException;
54 import jalview.util.MessageManager;
55 import jalview.util.UrlLink;
56
57 import java.awt.Color;
58 import java.awt.event.ActionEvent;
59 import java.awt.event.ActionListener;
60 import java.util.Arrays;
61 import java.util.Collection;
62 import java.util.Collections;
63 import java.util.Hashtable;
64 import java.util.LinkedHashMap;
65 import java.util.List;
66 import java.util.Map;
67 import java.util.SortedMap;
68 import java.util.TreeMap;
69 import java.util.Vector;
70
71 import javax.swing.JCheckBoxMenuItem;
72 import javax.swing.JColorChooser;
73 import javax.swing.JMenu;
74 import javax.swing.JMenuItem;
75 import javax.swing.JPopupMenu;
76
77 /**
78  * DOCUMENT ME!
79  * 
80  * @author $author$
81  * @version $Revision: 1.118 $
82  */
83 public class PopupMenu extends JPopupMenu implements ColourChangeListener
84 {
85   JMenu groupMenu = new JMenu();
86
87   JMenuItem groupName = new JMenuItem();
88
89   protected JCheckBoxMenuItem abovePIDColour = new JCheckBoxMenuItem();
90
91   protected JCheckBoxMenuItem conservationMenuItem = new JCheckBoxMenuItem();
92
93   AlignmentPanel ap;
94
95   JMenu sequenceMenu = new JMenu();
96
97   JMenuItem sequenceName = new JMenuItem();
98
99   JMenuItem sequenceDetails = new JMenuItem();
100
101   JMenuItem sequenceSelDetails = new JMenuItem();
102
103   JMenuItem makeReferenceSeq = new JMenuItem();
104
105   JMenuItem chooseAnnotations = new JMenuItem();
106
107   SequenceI sequence;
108
109   JMenuItem createGroupMenuItem = new JMenuItem();
110
111   JMenuItem unGroupMenuItem = new JMenuItem();
112
113   JMenuItem outline = new JMenuItem();
114
115   JMenu colourMenu = new JMenu();
116
117   JCheckBoxMenuItem showBoxes = new JCheckBoxMenuItem();
118
119   JCheckBoxMenuItem showText = new JCheckBoxMenuItem();
120
121   JCheckBoxMenuItem showColourText = new JCheckBoxMenuItem();
122
123   JCheckBoxMenuItem displayNonconserved = new JCheckBoxMenuItem();
124
125   JMenu editMenu = new JMenu();
126
127   JMenuItem cut = new JMenuItem();
128
129   JMenuItem copy = new JMenuItem();
130
131   JMenuItem upperCase = new JMenuItem();
132
133   JMenuItem lowerCase = new JMenuItem();
134
135   JMenuItem toggle = new JMenuItem();
136
137   JMenu pdbMenu = new JMenu();
138
139   JMenu outputMenu = new JMenu();
140
141   JMenu seqShowAnnotationsMenu = new JMenu();
142
143   JMenu seqHideAnnotationsMenu = new JMenu();
144
145   JMenuItem seqAddReferenceAnnotations = new JMenuItem(
146           MessageManager.getString("label.add_reference_annotations"));
147
148   JMenu groupShowAnnotationsMenu = new JMenu();
149
150   JMenu groupHideAnnotationsMenu = new JMenu();
151
152   JMenuItem groupAddReferenceAnnotations = new JMenuItem(
153           MessageManager.getString("label.add_reference_annotations"));
154
155   JMenuItem sequenceFeature = new JMenuItem();
156
157   JMenuItem textColour = new JMenuItem();
158
159   JMenu jMenu1 = new JMenu();
160
161   JMenuItem pdbStructureDialog = new JMenuItem();
162
163   JMenu rnaStructureMenu = new JMenu();
164
165   JMenuItem editSequence = new JMenuItem();
166
167   JMenu groupLinksMenu;
168
169   JMenuItem hideInsertions = new JMenuItem();
170
171   /**
172    * Creates a new PopupMenu object.
173    * 
174    * @param ap
175    *          DOCUMENT ME!
176    * @param seq
177    *          DOCUMENT ME!
178    */
179   public PopupMenu(final AlignmentPanel ap, Sequence seq, List<String> links)
180   {
181     this(ap, seq, links, null);
182   }
183
184   /**
185    * 
186    * @param ap
187    * @param seq
188    * @param links
189    * @param groupLinks
190    */
191   public PopupMenu(final AlignmentPanel ap, final SequenceI seq,
192           List<String> links, List<String> groupLinks)
193   {
194     // /////////////////////////////////////////////////////////
195     // If this is activated from the sequence panel, the user may want to
196     // edit or annotate a particular residue. Therefore display the residue menu
197     //
198     // If from the IDPanel, we must display the sequence menu
199     // ////////////////////////////////////////////////////////
200     this.ap = ap;
201     sequence = seq;
202
203     for (String ff : FileFormat.getWritableFormats(true))
204     {
205       JMenuItem item = new JMenuItem(ff);
206
207       item.addActionListener(new ActionListener()
208       {
209         @Override
210         public void actionPerformed(ActionEvent e)
211         {
212           outputText_actionPerformed(e);
213         }
214       });
215
216       outputMenu.add(item);
217     }
218
219     /*
220      * Build menus for annotation types that may be shown or hidden, and for
221      * 'reference annotations' that may be added to the alignment. First for the
222      * currently selected sequence (if there is one):
223      */
224     final List<SequenceI> selectedSequence = (seq == null ? Collections
225             .<SequenceI> emptyList() : Arrays.asList(seq));
226     buildAnnotationTypesMenus(seqShowAnnotationsMenu,
227             seqHideAnnotationsMenu, selectedSequence);
228     configureReferenceAnnotationsMenu(seqAddReferenceAnnotations,
229             selectedSequence);
230
231     /*
232      * And repeat for the current selection group (if there is one):
233      */
234     final List<SequenceI> selectedGroup = (ap.av.getSelectionGroup() == null ? Collections
235             .<SequenceI> emptyList() : ap.av.getSelectionGroup()
236             .getSequences());
237     buildAnnotationTypesMenus(groupShowAnnotationsMenu,
238             groupHideAnnotationsMenu, selectedGroup);
239     configureReferenceAnnotationsMenu(groupAddReferenceAnnotations,
240             selectedGroup);
241
242     try
243     {
244       jbInit();
245     } catch (Exception e)
246     {
247       e.printStackTrace();
248     }
249
250     JMenuItem menuItem;
251     if (seq != null)
252     {
253       sequenceMenu.setText(sequence.getName());
254       if (seq == ap.av.getAlignment().getSeqrep())
255       {
256         makeReferenceSeq.setText(MessageManager
257                 .getString("action.unmark_as_reference"));
258       }
259       else
260       {
261         makeReferenceSeq.setText(MessageManager
262                 .getString("action.set_as_reference"));
263       }
264
265       if (!ap.av.getAlignment().isNucleotide())
266       {
267         remove(rnaStructureMenu);
268       }
269       else
270       {
271         int origCount = rnaStructureMenu.getItemCount();
272         /*
273          * add menu items to 2D-render any alignment or sequence secondary
274          * structure annotation
275          */
276         AlignmentAnnotation[] aas = ap.av.getAlignment()
277                 .getAlignmentAnnotation();
278         if (aas != null)
279         {
280           for (final AlignmentAnnotation aa : aas)
281           {
282             if (aa.isValidStruc() && aa.sequenceRef == null)
283             {
284               /*
285                * valid alignment RNA secondary structure annotation
286                */
287               menuItem = new JMenuItem();
288               menuItem.setText(MessageManager.formatMessage(
289                       "label.2d_rna_structure_line",
290                       new Object[] { aa.label }));
291               menuItem.addActionListener(new ActionListener()
292               {
293                 @Override
294                 public void actionPerformed(ActionEvent e)
295                 {
296                   new AppVarna(seq, aa, ap);
297                 }
298               });
299               rnaStructureMenu.add(menuItem);
300             }
301           }
302         }
303
304         if (seq.getAnnotation() != null)
305         {
306           AlignmentAnnotation seqAnns[] = seq.getAnnotation();
307           for (final AlignmentAnnotation aa : seqAnns)
308           {
309             if (aa.isValidStruc())
310             {
311               /*
312                * valid sequence RNA secondary structure annotation
313                */
314               // TODO: make rnastrucF a bit more nice
315               menuItem = new JMenuItem();
316               menuItem.setText(MessageManager.formatMessage(
317                       "label.2d_rna_sequence_name",
318                       new Object[] { seq.getName() }));
319               menuItem.addActionListener(new ActionListener()
320               {
321                 @Override
322                 public void actionPerformed(ActionEvent e)
323                 {
324                   // TODO: VARNA does'nt print gaps in the sequence
325                   new AppVarna(seq, aa, ap);
326                 }
327               });
328               rnaStructureMenu.add(menuItem);
329             }
330           }
331         }
332         if (rnaStructureMenu.getItemCount() == origCount)
333         {
334           remove(rnaStructureMenu);
335         }
336       }
337
338       menuItem = new JMenuItem(
339               MessageManager.getString("action.hide_sequences"));
340       menuItem.addActionListener(new ActionListener()
341       {
342         @Override
343         public void actionPerformed(ActionEvent e)
344         {
345           hideSequences(false);
346         }
347       });
348       add(menuItem);
349
350       if (ap.av.getSelectionGroup() != null
351               && ap.av.getSelectionGroup().getSize() > 1)
352       {
353         menuItem = new JMenuItem(MessageManager.formatMessage(
354                 "label.represent_group_with",
355                 new Object[] { seq.getName() }));
356         menuItem.addActionListener(new ActionListener()
357         {
358           @Override
359           public void actionPerformed(ActionEvent e)
360           {
361             hideSequences(true);
362           }
363         });
364         sequenceMenu.add(menuItem);
365       }
366
367       if (ap.av.hasHiddenRows())
368       {
369         final int index = ap.av.getAlignment().findIndex(seq);
370
371         if (ap.av.adjustForHiddenSeqs(index)
372                 - ap.av.adjustForHiddenSeqs(index - 1) > 1)
373         {
374           menuItem = new JMenuItem(
375                   MessageManager.getString("action.reveal_sequences"));
376           menuItem.addActionListener(new ActionListener()
377           {
378             @Override
379             public void actionPerformed(ActionEvent e)
380             {
381               ap.av.showSequence(index);
382               if (ap.overviewPanel != null)
383               {
384                 ap.overviewPanel.updateOverviewImage();
385               }
386             }
387           });
388           add(menuItem);
389         }
390       }
391     }
392     // for the case when no sequences are even visible
393     if (ap.av.hasHiddenRows())
394     {
395       {
396         menuItem = new JMenuItem(
397                 MessageManager.getString("action.reveal_all"));
398         menuItem.addActionListener(new ActionListener()
399         {
400           @Override
401           public void actionPerformed(ActionEvent e)
402           {
403             ap.av.showAllHiddenSeqs();
404             if (ap.overviewPanel != null)
405             {
406               ap.overviewPanel.updateOverviewImage();
407             }
408           }
409         });
410
411         add(menuItem);
412       }
413
414     }
415
416     SequenceGroup sg = ap.av.getSelectionGroup();
417     boolean isDefinedGroup = (sg != null) ? ap.av.getAlignment()
418             .getGroups().contains(sg) : false;
419
420     if (sg != null && sg.getSize() > 0)
421     {
422       groupName.setText(MessageManager
423               .getString("label.edit_name_and_description_current_group"));
424
425       ColourMenuHelper.setColourSelected(colourMenu, sg.getColourScheme());
426
427       if (sg.cs != null && sg.cs.conservationApplied())
428       {
429         conservationMenuItem.setSelected(true);
430       }
431       displayNonconserved.setSelected(sg.getShowNonconserved());
432       showText.setSelected(sg.getDisplayText());
433       showColourText.setSelected(sg.getColourText());
434       showBoxes.setSelected(sg.getDisplayBoxes());
435       // add any groupURLs to the groupURL submenu and make it visible
436       if (groupLinks != null && groupLinks.size() > 0)
437       {
438         buildGroupURLMenu(sg, groupLinks);
439       }
440       // Add a 'show all structures' for the current selection
441       Hashtable<String, PDBEntry> pdbe = new Hashtable<String, PDBEntry>(), reppdb = new Hashtable<String, PDBEntry>();
442       SequenceI sqass = null;
443       for (SequenceI sq : ap.av.getSequenceSelection())
444       {
445         Vector<PDBEntry> pes = sq.getDatasetSequence().getAllPDBEntries();
446         if (pes != null && pes.size() > 0)
447         {
448           reppdb.put(pes.get(0).getId(), pes.get(0));
449           for (PDBEntry pe : pes)
450           {
451             pdbe.put(pe.getId(), pe);
452             if (sqass == null)
453             {
454               sqass = sq;
455             }
456           }
457         }
458       }
459       if (pdbe.size() > 0)
460       {
461         final PDBEntry[] pe = pdbe.values().toArray(
462                 new PDBEntry[pdbe.size()]), pr = reppdb.values().toArray(
463                 new PDBEntry[reppdb.size()]);
464         final JMenuItem gpdbview, rpdbview;
465       }
466     }
467     else
468     {
469       groupMenu.setVisible(false);
470       editMenu.setVisible(false);
471     }
472
473     if (!isDefinedGroup)
474     {
475       createGroupMenuItem.setVisible(true);
476       unGroupMenuItem.setVisible(false);
477       jMenu1.setText(MessageManager.getString("action.edit_new_group"));
478     }
479     else
480     {
481       createGroupMenuItem.setVisible(false);
482       unGroupMenuItem.setVisible(true);
483       jMenu1.setText(MessageManager.getString("action.edit_group"));
484     }
485
486     if (seq == null)
487     {
488       sequenceMenu.setVisible(false);
489       pdbStructureDialog.setVisible(false);
490       rnaStructureMenu.setVisible(false);
491     }
492
493     if (links != null && links.size() > 0)
494     {
495       addFeatureLinks(seq, links);
496     }
497   }
498
499   /**
500    * Adds a 'Link' menu item with a sub-menu item for each hyperlink provided.
501    * 
502    * @param seq
503    * @param links
504    */
505   void addFeatureLinks(final SequenceI seq, List<String> links)
506   {
507     JMenu linkMenu = new JMenu(MessageManager.getString("action.link"));
508     Map<String, List<String>> linkset = new LinkedHashMap<String, List<String>>();
509
510     for (String link : links)
511     {
512       UrlLink urlLink = null;
513       try
514       {
515         urlLink = new UrlLink(link);
516       } catch (Exception foo)
517       {
518         Cache.log.error("Exception for URLLink '" + link + "'", foo);
519         continue;
520       }
521
522       if (!urlLink.isValid())
523       {
524         Cache.log.error(urlLink.getInvalidMessage());
525         continue;
526       }
527
528       urlLink.createLinksFromSeq(seq, linkset);
529     }
530
531     addshowLinks(linkMenu, linkset.values());
532
533     // disable link menu if there are no valid entries
534     if (linkMenu.getItemCount() > 0)
535     {
536       linkMenu.setEnabled(true);
537     }
538     else
539     {
540       linkMenu.setEnabled(false);
541     }
542
543     if (sequence != null)
544     {
545       sequenceMenu.add(linkMenu);
546     }
547     else
548     {
549       add(linkMenu);
550     }
551
552   }
553
554
555
556   /**
557    * Add annotation types to 'Show annotations' and/or 'Hide annotations' menus.
558    * "All" is added first, followed by a separator. Then add any annotation
559    * types associated with the current selection. Separate menus are built for
560    * the selected sequence group (if any), and the selected sequence.
561    * <p>
562    * Some annotation rows are always rendered together - these can be identified
563    * by a common graphGroup property > -1. Only one of each group will be marked
564    * as visible (to avoid duplication of the display). For such groups we add a
565    * composite type name, e.g.
566    * <p>
567    * IUPredWS (Long), IUPredWS (Short)
568    * 
569    * @param seq
570    */
571   protected void buildAnnotationTypesMenus(JMenu showMenu, JMenu hideMenu,
572           List<SequenceI> forSequences)
573   {
574     showMenu.removeAll();
575     hideMenu.removeAll();
576
577     final List<String> all = Arrays.asList(new String[] { MessageManager
578             .getString("label.all") });
579     addAnnotationTypeToShowHide(showMenu, forSequences, "", all, true, true);
580     addAnnotationTypeToShowHide(hideMenu, forSequences, "", all, true,
581             false);
582     showMenu.addSeparator();
583     hideMenu.addSeparator();
584
585     final AlignmentAnnotation[] annotations = ap.getAlignment()
586             .getAlignmentAnnotation();
587
588     /*
589      * Find shown/hidden annotations types, distinguished by source (calcId),
590      * and grouped by graphGroup. Using LinkedHashMap means we will retrieve in
591      * the insertion order, which is the order of the annotations on the
592      * alignment.
593      */
594     Map<String, List<List<String>>> shownTypes = new LinkedHashMap<String, List<List<String>>>();
595     Map<String, List<List<String>>> hiddenTypes = new LinkedHashMap<String, List<List<String>>>();
596     AlignmentAnnotationUtils.getShownHiddenTypes(shownTypes, hiddenTypes,
597             AlignmentAnnotationUtils.asList(annotations), forSequences);
598
599     for (String calcId : hiddenTypes.keySet())
600     {
601       for (List<String> type : hiddenTypes.get(calcId))
602       {
603         addAnnotationTypeToShowHide(showMenu, forSequences, calcId, type,
604                 false, true);
605       }
606     }
607     // grey out 'show annotations' if none are hidden
608     showMenu.setEnabled(!hiddenTypes.isEmpty());
609
610     for (String calcId : shownTypes.keySet())
611     {
612       for (List<String> type : shownTypes.get(calcId))
613       {
614         addAnnotationTypeToShowHide(hideMenu, forSequences, calcId, type,
615                 false, false);
616       }
617     }
618     // grey out 'hide annotations' if none are shown
619     hideMenu.setEnabled(!shownTypes.isEmpty());
620   }
621
622   /**
623    * Returns a list of sequences - either the current selection group (if there
624    * is one), else the specified single sequence.
625    * 
626    * @param seq
627    * @return
628    */
629   protected List<SequenceI> getSequenceScope(SequenceI seq)
630   {
631     List<SequenceI> forSequences = null;
632     final SequenceGroup selectionGroup = ap.av.getSelectionGroup();
633     if (selectionGroup != null && selectionGroup.getSize() > 0)
634     {
635       forSequences = selectionGroup.getSequences();
636     }
637     else
638     {
639       forSequences = seq == null ? Collections.<SequenceI> emptyList()
640               : Arrays.asList(seq);
641     }
642     return forSequences;
643   }
644
645   /**
646    * Add one annotation type to the 'Show Annotations' or 'Hide Annotations'
647    * menus.
648    * 
649    * @param showOrHideMenu
650    *          the menu to add to
651    * @param forSequences
652    *          the sequences whose annotations may be shown or hidden
653    * @param calcId
654    * @param types
655    *          the label to add
656    * @param allTypes
657    *          if true this is a special label meaning 'All'
658    * @param actionIsShow
659    *          if true, the select menu item action is to show the annotation
660    *          type, else hide
661    */
662   protected void addAnnotationTypeToShowHide(JMenu showOrHideMenu,
663           final List<SequenceI> forSequences, String calcId,
664           final List<String> types, final boolean allTypes,
665           final boolean actionIsShow)
666   {
667     String label = types.toString(); // [a, b, c]
668     label = label.substring(1, label.length() - 1); // a, b, c
669     final JMenuItem item = new JMenuItem(label);
670     item.setToolTipText(calcId);
671     item.addActionListener(new ActionListener()
672     {
673       @Override
674       public void actionPerformed(ActionEvent e)
675       {
676         AlignmentUtils.showOrHideSequenceAnnotations(ap.getAlignment(),
677                 types, forSequences, allTypes, actionIsShow);
678         refresh();
679       }
680     });
681     showOrHideMenu.add(item);
682   }
683
684   private void buildGroupURLMenu(SequenceGroup sg, List<String> groupLinks)
685   {
686
687     // TODO: usability: thread off the generation of group url content so root
688     // menu appears asap
689     // sequence only URLs
690     // ID/regex match URLs
691     groupLinksMenu = new JMenu(
692             MessageManager.getString("action.group_link"));
693     // three types of url that might be created.
694     JMenu[] linkMenus = new JMenu[] { null,
695         new JMenu(MessageManager.getString("action.ids")),
696         new JMenu(MessageManager.getString("action.sequences")),
697         new JMenu(MessageManager.getString("action.ids_sequences")) };
698
699     SequenceI[] seqs = ap.av.getSelectionAsNewSequence();
700     String[][] idandseqs = GroupUrlLink.formStrings(seqs);
701     Hashtable<String, Object[]> commonDbrefs = new Hashtable<String, Object[]>();
702     for (int sq = 0; sq < seqs.length; sq++)
703     {
704
705       int start = seqs[sq].findPosition(sg.getStartRes()), end = seqs[sq]
706               .findPosition(sg.getEndRes());
707       // just collect ids from dataset sequence
708       // TODO: check if IDs collected from selecton group intersects with the
709       // current selection, too
710       SequenceI sqi = seqs[sq];
711       while (sqi.getDatasetSequence() != null)
712       {
713         sqi = sqi.getDatasetSequence();
714       }
715       DBRefEntry[] dbr = sqi.getDBRefs();
716       if (dbr != null && dbr.length > 0)
717       {
718         for (int d = 0; d < dbr.length; d++)
719         {
720           String src = dbr[d].getSource(); // jalview.util.DBRefUtils.getCanonicalName(dbr[d].getSource()).toUpperCase();
721           Object[] sarray = commonDbrefs.get(src);
722           if (sarray == null)
723           {
724             sarray = new Object[2];
725             sarray[0] = new int[] { 0 };
726             sarray[1] = new String[seqs.length];
727
728             commonDbrefs.put(src, sarray);
729           }
730
731           if (((String[]) sarray[1])[sq] == null)
732           {
733             if (!dbr[d].hasMap()
734                     || (dbr[d].getMap().locateMappedRange(start, end) != null))
735             {
736               ((String[]) sarray[1])[sq] = dbr[d].getAccessionId();
737               ((int[]) sarray[0])[0]++;
738             }
739           }
740         }
741       }
742     }
743     // now create group links for all distinct ID/sequence sets.
744     boolean addMenu = false; // indicates if there are any group links to give
745                              // to user
746     for (String link : groupLinks)
747     {
748       GroupUrlLink urlLink = null;
749       try
750       {
751         urlLink = new GroupUrlLink(link);
752       } catch (Exception foo)
753       {
754         Cache.log.error("Exception for GroupURLLink '" + link + "'", foo);
755         continue;
756       }
757       ;
758       if (!urlLink.isValid())
759       {
760         Cache.log.error(urlLink.getInvalidMessage());
761         continue;
762       }
763       final String label = urlLink.getLabel();
764       boolean usingNames = false;
765       // Now see which parts of the group apply for this URL
766       String ltarget = urlLink.getTarget(); // jalview.util.DBRefUtils.getCanonicalName(urlLink.getTarget());
767       Object[] idset = commonDbrefs.get(ltarget.toUpperCase());
768       String[] seqstr, ids; // input to makeUrl
769       if (idset != null)
770       {
771         int numinput = ((int[]) idset[0])[0];
772         String[] allids = ((String[]) idset[1]);
773         seqstr = new String[numinput];
774         ids = new String[numinput];
775         for (int sq = 0, idcount = 0; sq < seqs.length; sq++)
776         {
777           if (allids[sq] != null)
778           {
779             ids[idcount] = allids[sq];
780             seqstr[idcount++] = idandseqs[1][sq];
781           }
782         }
783       }
784       else
785       {
786         // just use the id/seq set
787         seqstr = idandseqs[1];
788         ids = idandseqs[0];
789         usingNames = true;
790       }
791       // and try and make the groupURL!
792
793       Object[] urlset = null;
794       try
795       {
796         urlset = urlLink.makeUrlStubs(ids, seqstr,
797                 "FromJalview" + System.currentTimeMillis(), false);
798       } catch (UrlStringTooLongException e)
799       {
800       }
801       if (urlset != null)
802       {
803         int type = urlLink.getGroupURLType() & 3;
804         // first two bits ofurlLink type bitfield are sequenceids and sequences
805         // TODO: FUTURE: ensure the groupURL menu structure can be generalised
806         addshowLink(linkMenus[type], label
807                 + (((type & 1) == 1) ? ("("
808                         + (usingNames ? "Names" : ltarget) + ")") : ""),
809                 urlLink, urlset);
810         addMenu = true;
811       }
812     }
813     if (addMenu)
814     {
815       groupLinksMenu = new JMenu(
816               MessageManager.getString("action.group_link"));
817       for (int m = 0; m < linkMenus.length; m++)
818       {
819         if (linkMenus[m] != null
820                 && linkMenus[m].getMenuComponentCount() > 0)
821         {
822           groupLinksMenu.add(linkMenus[m]);
823         }
824       }
825
826       groupMenu.add(groupLinksMenu);
827     }
828   }
829
830   private void addshowLinks(JMenu linkMenu, Collection<List<String>> linkset)
831   {
832     for (List<String> linkstrset : linkset)
833     {
834       // split linkstr into label and url
835       addshowLink(linkMenu, linkstrset.get(1), linkstrset.get(3));
836     }
837   }
838
839   /**
840    * add a show URL menu item to the given linkMenu
841    * 
842    * @param linkMenu
843    * @param label
844    *          - menu label string
845    * @param url
846    *          - url to open
847    */
848   private void addshowLink(JMenu linkMenu, String label, final String url)
849   {
850     JMenuItem item = new JMenuItem(label);
851     item.setToolTipText(MessageManager.formatMessage(
852             "label.open_url_param", new Object[] { url }));
853     item.addActionListener(new ActionListener()
854     {
855       @Override
856       public void actionPerformed(ActionEvent e)
857       {
858         new Thread(new Runnable()
859         {
860
861           @Override
862           public void run()
863           {
864             showLink(url);
865           }
866
867         }).start();
868       }
869     });
870
871     linkMenu.add(item);
872   }
873
874   /**
875    * add a late bound groupURL item to the given linkMenu
876    * 
877    * @param linkMenu
878    * @param label
879    *          - menu label string
880    * @param urlgenerator
881    *          GroupURLLink used to generate URL
882    * @param urlstub
883    *          Object array returned from the makeUrlStubs function.
884    */
885   private void addshowLink(JMenu linkMenu, String label,
886           final GroupUrlLink urlgenerator, final Object[] urlstub)
887   {
888     JMenuItem item = new JMenuItem(label);
889     item.setToolTipText(MessageManager.formatMessage(
890             "label.open_url_seqs_param",
891             new Object[] { urlgenerator.getUrl_prefix(),
892                 urlgenerator.getNumberInvolved(urlstub) }));
893     // TODO: put in info about what is being sent.
894     item.addActionListener(new ActionListener()
895     {
896       @Override
897       public void actionPerformed(ActionEvent e)
898       {
899         new Thread(new Runnable()
900         {
901
902           @Override
903           public void run()
904           {
905             try
906             {
907               showLink(urlgenerator.constructFrom(urlstub));
908             } catch (UrlStringTooLongException e2)
909             {
910             }
911           }
912
913         }).start();
914       }
915     });
916
917     linkMenu.add(item);
918   }
919
920   /**
921    * DOCUMENT ME!
922    * 
923    * @throws Exception
924    *           DOCUMENT ME!
925    */
926   private void jbInit() throws Exception
927   {
928     groupMenu.setText(MessageManager.getString("label.selection"));
929     groupName.setText(MessageManager.getString("label.name"));
930     groupName.addActionListener(new ActionListener()
931     {
932       @Override
933       public void actionPerformed(ActionEvent e)
934       {
935         groupName_actionPerformed();
936       }
937     });
938     sequenceMenu.setText(MessageManager.getString("label.sequence"));
939     sequenceName.setText(MessageManager
940             .getString("label.edit_name_description"));
941     sequenceName.addActionListener(new ActionListener()
942     {
943       @Override
944       public void actionPerformed(ActionEvent e)
945       {
946         sequenceName_actionPerformed();
947       }
948     });
949     chooseAnnotations.setText(MessageManager
950             .getString("action.choose_annotations"));
951     chooseAnnotations.addActionListener(new ActionListener()
952     {
953       @Override
954       public void actionPerformed(ActionEvent e)
955       {
956         chooseAnnotations_actionPerformed(e);
957       }
958     });
959     sequenceDetails.setText(MessageManager
960             .getString("label.sequence_details"));
961     sequenceDetails.addActionListener(new ActionListener()
962     {
963       @Override
964       public void actionPerformed(ActionEvent e)
965       {
966         sequenceDetails_actionPerformed();
967       }
968     });
969     sequenceSelDetails.setText(MessageManager
970             .getString("label.sequence_details"));
971     sequenceSelDetails.addActionListener(new ActionListener()
972     {
973       @Override
974       public void actionPerformed(ActionEvent e)
975       {
976         sequenceSelectionDetails_actionPerformed();
977       }
978     });
979     unGroupMenuItem
980             .setText(MessageManager.getString("action.remove_group"));
981     unGroupMenuItem.addActionListener(new ActionListener()
982     {
983       @Override
984       public void actionPerformed(ActionEvent e)
985       {
986         unGroupMenuItem_actionPerformed();
987       }
988     });
989     createGroupMenuItem.setText(MessageManager
990             .getString("action.create_group"));
991     createGroupMenuItem.addActionListener(new ActionListener()
992     {
993       @Override
994       public void actionPerformed(ActionEvent e)
995       {
996         createGroupMenuItem_actionPerformed();
997       }
998     });
999
1000     outline.setText(MessageManager.getString("action.border_colour"));
1001     outline.addActionListener(new ActionListener()
1002     {
1003       @Override
1004       public void actionPerformed(ActionEvent e)
1005       {
1006         outline_actionPerformed();
1007       }
1008     });
1009     showBoxes.setText(MessageManager.getString("action.boxes"));
1010     showBoxes.setState(true);
1011     showBoxes.addActionListener(new ActionListener()
1012     {
1013       @Override
1014       public void actionPerformed(ActionEvent e)
1015       {
1016         showBoxes_actionPerformed();
1017       }
1018     });
1019     showText.setText(MessageManager.getString("action.text"));
1020     showText.setState(true);
1021     showText.addActionListener(new ActionListener()
1022     {
1023       @Override
1024       public void actionPerformed(ActionEvent e)
1025       {
1026         showText_actionPerformed();
1027       }
1028     });
1029     showColourText.setText(MessageManager.getString("label.colour_text"));
1030     showColourText.addActionListener(new ActionListener()
1031     {
1032       @Override
1033       public void actionPerformed(ActionEvent e)
1034       {
1035         showColourText_actionPerformed();
1036       }
1037     });
1038     displayNonconserved.setText(MessageManager
1039             .getString("label.show_non_conserved"));
1040     displayNonconserved.setState(true);
1041     displayNonconserved.addActionListener(new ActionListener()
1042     {
1043       @Override
1044       public void actionPerformed(ActionEvent e)
1045       {
1046         showNonconserved_actionPerformed();
1047       }
1048     });
1049     editMenu.setText(MessageManager.getString("action.edit"));
1050     cut.setText(MessageManager.getString("action.cut"));
1051     cut.addActionListener(new ActionListener()
1052     {
1053       @Override
1054       public void actionPerformed(ActionEvent e)
1055       {
1056         cut_actionPerformed();
1057       }
1058     });
1059     upperCase.setText(MessageManager.getString("label.to_upper_case"));
1060     upperCase.addActionListener(new ActionListener()
1061     {
1062       @Override
1063       public void actionPerformed(ActionEvent e)
1064       {
1065         changeCase(e);
1066       }
1067     });
1068     copy.setText(MessageManager.getString("action.copy"));
1069     copy.addActionListener(new ActionListener()
1070     {
1071       @Override
1072       public void actionPerformed(ActionEvent e)
1073       {
1074         copy_actionPerformed();
1075       }
1076     });
1077     lowerCase.setText(MessageManager.getString("label.to_lower_case"));
1078     lowerCase.addActionListener(new ActionListener()
1079     {
1080       @Override
1081       public void actionPerformed(ActionEvent e)
1082       {
1083         changeCase(e);
1084       }
1085     });
1086     toggle.setText(MessageManager.getString("label.toggle_case"));
1087     toggle.addActionListener(new ActionListener()
1088     {
1089       @Override
1090       public void actionPerformed(ActionEvent e)
1091       {
1092         changeCase(e);
1093       }
1094     });
1095     outputMenu.setText(MessageManager.getString("label.out_to_textbox")
1096             + "...");
1097     seqShowAnnotationsMenu.setText(MessageManager
1098             .getString("label.show_annotations"));
1099     seqHideAnnotationsMenu.setText(MessageManager
1100             .getString("label.hide_annotations"));
1101     groupShowAnnotationsMenu.setText(MessageManager
1102             .getString("label.show_annotations"));
1103     groupHideAnnotationsMenu.setText(MessageManager
1104             .getString("label.hide_annotations"));
1105     sequenceFeature.setText(MessageManager
1106             .getString("label.create_sequence_feature"));
1107     sequenceFeature.addActionListener(new ActionListener()
1108     {
1109       @Override
1110       public void actionPerformed(ActionEvent e)
1111       {
1112         sequenceFeature_actionPerformed();
1113       }
1114     });
1115     jMenu1.setText(MessageManager.getString("label.group"));
1116     pdbStructureDialog.setText(MessageManager
1117             .getString("label.show_pdbstruct_dialog"));
1118     pdbStructureDialog.addActionListener(new ActionListener()
1119     {
1120       @Override
1121       public void actionPerformed(ActionEvent actionEvent)
1122       {
1123         SequenceI[] selectedSeqs = new SequenceI[] { sequence };
1124         if (ap.av.getSelectionGroup() != null)
1125         {
1126           selectedSeqs = ap.av.getSequenceSelection();
1127         }
1128         new StructureChooser(selectedSeqs, sequence, ap);
1129       }
1130     });
1131
1132     rnaStructureMenu.setText(MessageManager
1133             .getString("label.view_rna_structure"));
1134
1135     // colStructureMenu.setText("Colour By Structure");
1136     editSequence.setText(MessageManager.getString("label.edit_sequence")
1137             + "...");
1138     editSequence.addActionListener(new ActionListener()
1139     {
1140       @Override
1141       public void actionPerformed(ActionEvent actionEvent)
1142       {
1143         editSequence_actionPerformed(actionEvent);
1144       }
1145     });
1146     makeReferenceSeq.setText(MessageManager
1147             .getString("label.mark_as_representative"));
1148     makeReferenceSeq.addActionListener(new ActionListener()
1149     {
1150
1151       @Override
1152       public void actionPerformed(ActionEvent actionEvent)
1153       {
1154         makeReferenceSeq_actionPerformed(actionEvent);
1155
1156       }
1157     });
1158     hideInsertions.setText(MessageManager
1159             .getString("label.hide_insertions"));
1160     hideInsertions.addActionListener(new ActionListener()
1161     {
1162
1163       @Override
1164       public void actionPerformed(ActionEvent e)
1165       {
1166         hideInsertions_actionPerformed(e);
1167       }
1168     });
1169     /*
1170      * annotationMenuItem.setText("By Annotation");
1171      * annotationMenuItem.addActionListener(new ActionListener() { public void
1172      * actionPerformed(ActionEvent actionEvent) {
1173      * annotationMenuItem_actionPerformed(actionEvent); } });
1174      */
1175     groupMenu.add(sequenceSelDetails);
1176     add(groupMenu);
1177     add(sequenceMenu);
1178     add(rnaStructureMenu);
1179     add(pdbStructureDialog);
1180     if (sequence != null)
1181     {
1182       add(hideInsertions);
1183     }
1184     // annotations configuration panel suppressed for now
1185     // groupMenu.add(chooseAnnotations);
1186
1187     /*
1188      * Add show/hide annotations to the Sequence menu, and to the Selection menu
1189      * (if a selection group is in force).
1190      */
1191     sequenceMenu.add(seqShowAnnotationsMenu);
1192     sequenceMenu.add(seqHideAnnotationsMenu);
1193     sequenceMenu.add(seqAddReferenceAnnotations);
1194     groupMenu.add(groupShowAnnotationsMenu);
1195     groupMenu.add(groupHideAnnotationsMenu);
1196     groupMenu.add(groupAddReferenceAnnotations);
1197     groupMenu.add(editMenu);
1198     groupMenu.add(outputMenu);
1199     groupMenu.add(sequenceFeature);
1200     groupMenu.add(createGroupMenuItem);
1201     groupMenu.add(unGroupMenuItem);
1202     groupMenu.add(jMenu1);
1203     sequenceMenu.add(sequenceName);
1204     sequenceMenu.add(sequenceDetails);
1205     sequenceMenu.add(makeReferenceSeq);
1206
1207     initColourMenu();
1208     buildColourMenu();
1209
1210     editMenu.add(copy);
1211     editMenu.add(cut);
1212     editMenu.add(editSequence);
1213     editMenu.add(upperCase);
1214     editMenu.add(lowerCase);
1215     editMenu.add(toggle);
1216     // JBPNote: These shouldn't be added here - should appear in a generic
1217     // 'apply web service to this sequence menu'
1218     // pdbMenu.add(RNAFold);
1219     // pdbMenu.add(ContraFold);
1220     jMenu1.add(groupName);
1221     jMenu1.add(colourMenu);
1222     jMenu1.add(showBoxes);
1223     jMenu1.add(showText);
1224     jMenu1.add(showColourText);
1225     jMenu1.add(outline);
1226     jMenu1.add(displayNonconserved);
1227   }
1228
1229   /**
1230    * Constructs the entries for the colour menu
1231    */
1232   protected void initColourMenu()
1233   {
1234     colourMenu.setText(MessageManager.getString("label.group_colour"));
1235     textColour.setText(MessageManager.getString("label.text_colour"));
1236     textColour.addActionListener(new ActionListener()
1237     {
1238       @Override
1239       public void actionPerformed(ActionEvent e)
1240       {
1241         textColour_actionPerformed();
1242       }
1243     });
1244     abovePIDColour.setText(MessageManager
1245             .getString("label.above_identity_threshold"));
1246     abovePIDColour.addActionListener(new ActionListener()
1247     {
1248       @Override
1249       public void actionPerformed(ActionEvent e)
1250       {
1251         abovePIDColour_actionPerformed();
1252       }
1253     });
1254
1255     conservationMenuItem.setText(MessageManager
1256             .getString("action.by_conservation"));
1257     conservationMenuItem.addActionListener(new ActionListener()
1258     {
1259       @Override
1260       public void actionPerformed(ActionEvent e)
1261       {
1262         conservationMenuItem_actionPerformed();
1263       }
1264     });
1265   }
1266
1267   /**
1268    * Builds the group colour sub-menu, including any user-defined colours which
1269    * were loaded at startup or during the Jalview session
1270    */
1271   protected void buildColourMenu()
1272   {
1273     SequenceGroup sg = ap.av.getSelectionGroup();
1274     if (sg == null)
1275     {
1276       /*
1277        * popup menu with no sequence group scope
1278        */
1279       return;
1280     }
1281     colourMenu.removeAll();
1282     colourMenu.add(textColour);
1283     colourMenu.addSeparator();
1284
1285     ColourMenuHelper.addMenuItems(colourMenu, this, sg, false);
1286
1287     colourMenu.addSeparator();
1288     colourMenu.add(conservationMenuItem);
1289     colourMenu.add(abovePIDColour);
1290   }
1291
1292   /**
1293    * Check for any annotations on the underlying dataset sequences (for the
1294    * current selection group) which are not 'on the alignment'.If any are found,
1295    * enable the option to add them to the alignment. The criteria for 'on the
1296    * alignment' is finding an alignment annotation on the alignment, matched on
1297    * calcId, label and sequenceRef.
1298    * 
1299    * A tooltip is also constructed that displays the source (calcId) and type
1300    * (label) of the annotations that can be added.
1301    * 
1302    * @param menuItem
1303    * @param forSequences
1304    */
1305   protected void configureReferenceAnnotationsMenu(JMenuItem menuItem,
1306           List<SequenceI> forSequences)
1307   {
1308     menuItem.setEnabled(false);
1309
1310     /*
1311      * Temporary store to hold distinct calcId / type pairs for the tooltip.
1312      * Using TreeMap means calcIds are shown in alphabetical order.
1313      */
1314     SortedMap<String, String> tipEntries = new TreeMap<String, String>();
1315     final Map<SequenceI, List<AlignmentAnnotation>> candidates = new LinkedHashMap<SequenceI, List<AlignmentAnnotation>>();
1316     AlignmentI al = this.ap.av.getAlignment();
1317     AlignmentUtils.findAddableReferenceAnnotations(forSequences,
1318             tipEntries, candidates, al);
1319     if (!candidates.isEmpty())
1320     {
1321       StringBuilder tooltip = new StringBuilder(64);
1322       tooltip.append(MessageManager.getString("label.add_annotations_for"));
1323
1324       /*
1325        * Found annotations that could be added. Enable the menu item, and
1326        * configure its tooltip and action.
1327        */
1328       menuItem.setEnabled(true);
1329       for (String calcId : tipEntries.keySet())
1330       {
1331         tooltip.append("<br/>" + calcId + "/" + tipEntries.get(calcId));
1332       }
1333       String tooltipText = JvSwingUtils.wrapTooltip(true,
1334               tooltip.toString());
1335       menuItem.setToolTipText(tooltipText);
1336
1337       menuItem.addActionListener(new ActionListener()
1338       {
1339         @Override
1340         public void actionPerformed(ActionEvent e)
1341         {
1342           addReferenceAnnotations_actionPerformed(candidates);
1343         }
1344       });
1345     }
1346   }
1347
1348   /**
1349    * Add annotations to the sequences and to the alignment.
1350    * 
1351    * @param candidates
1352    *          a map whose keys are sequences on the alignment, and values a list
1353    *          of annotations to add to each sequence
1354    */
1355   protected void addReferenceAnnotations_actionPerformed(
1356           Map<SequenceI, List<AlignmentAnnotation>> candidates)
1357   {
1358     final SequenceGroup selectionGroup = this.ap.av.getSelectionGroup();
1359     final AlignmentI alignment = this.ap.getAlignment();
1360     AlignmentUtils.addReferenceAnnotations(candidates, alignment,
1361             selectionGroup);
1362     refresh();
1363   }
1364
1365   protected void makeReferenceSeq_actionPerformed(ActionEvent actionEvent)
1366   {
1367     if (!ap.av.getAlignment().hasSeqrep())
1368     {
1369       // initialise the display flags so the user sees something happen
1370       ap.av.setDisplayReferenceSeq(true);
1371       ap.av.setColourByReferenceSeq(true);
1372       ap.av.getAlignment().setSeqrep(sequence);
1373     }
1374     else
1375     {
1376       if (ap.av.getAlignment().getSeqrep() == sequence)
1377       {
1378         ap.av.getAlignment().setSeqrep(null);
1379       }
1380       else
1381       {
1382         ap.av.getAlignment().setSeqrep(sequence);
1383       }
1384     }
1385     refresh();
1386   }
1387
1388   protected void hideInsertions_actionPerformed(ActionEvent actionEvent)
1389   {
1390     if (sequence != null)
1391     {
1392       ColumnSelection cs = ap.av.getColumnSelection();
1393       if (cs == null)
1394       {
1395         cs = new ColumnSelection();
1396       }
1397       cs.hideInsertionsFor(sequence);
1398       ap.av.setColumnSelection(cs);
1399     }
1400     refresh();
1401   }
1402
1403   protected void sequenceSelectionDetails_actionPerformed()
1404   {
1405     createSequenceDetailsReport(ap.av.getSequenceSelection());
1406   }
1407
1408   protected void sequenceDetails_actionPerformed()
1409   {
1410     createSequenceDetailsReport(new SequenceI[] { sequence });
1411   }
1412
1413   public void createSequenceDetailsReport(SequenceI[] sequences)
1414   {
1415     CutAndPasteHtmlTransfer cap = new CutAndPasteHtmlTransfer();
1416     StringBuilder contents = new StringBuilder(128);
1417     for (SequenceI seq : sequences)
1418     {
1419       contents.append("<p><h2>"
1420               + MessageManager
1421                       .formatMessage(
1422                               "label.create_sequence_details_report_annotation_for",
1423                               new Object[] { seq.getDisplayId(true) })
1424               + "</h2></p><p>");
1425       new SequenceAnnotationReport(null)
1426               .createSequenceAnnotationReport(
1427                       contents,
1428                       seq,
1429                       true,
1430                       true,
1431                       (ap.getSeqPanel().seqCanvas.fr != null) ? ap
1432                               .getSeqPanel().seqCanvas.fr.getMinMax()
1433                               : null);
1434       contents.append("</p>");
1435     }
1436     cap.setText("<html>" + contents.toString() + "</html>");
1437
1438     Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1439             "label.sequence_details_for",
1440             (sequences.length == 1 ? new Object[] { sequences[0]
1441                     .getDisplayId(true) } : new Object[] { MessageManager
1442                     .getString("label.selection") })), 500, 400);
1443
1444   }
1445
1446   protected void showNonconserved_actionPerformed()
1447   {
1448     getGroup().setShowNonconserved(displayNonconserved.isSelected());
1449     refresh();
1450   }
1451
1452   /**
1453    * call to refresh view after settings change
1454    */
1455   void refresh()
1456   {
1457     ap.updateAnnotation();
1458     ap.paintAlignment(true);
1459
1460     PaintRefresher.Refresh(this, ap.av.getSequenceSetId());
1461   }
1462
1463   /*
1464    * protected void covariationColour_actionPerformed() { getGroup().cs = new
1465    * CovariationColourScheme(sequence.getAnnotation()[0]); refresh(); }
1466    */
1467   /**
1468    * DOCUMENT ME!
1469    * 
1470    * @param e
1471    *          DOCUMENT ME!
1472    */
1473   protected void abovePIDColour_actionPerformed()
1474   {
1475     SequenceGroup sg = getGroup();
1476     if (sg.cs == null)
1477     {
1478       return;
1479     }
1480
1481     if (abovePIDColour.isSelected())
1482     {
1483       sg.cs.setConsensus(AAFrequency.calculate(
1484               sg.getSequences(ap.av.getHiddenRepSequences()),
1485               sg.getStartRes(), sg.getEndRes() + 1));
1486
1487       int threshold = SliderPanel.setPIDSliderSource(ap,
1488               sg.getGroupColourScheme(), getGroup()
1489               .getName());
1490
1491       sg.cs.setThreshold(threshold, ap.av.isIgnoreGapsConsensus());
1492
1493       SliderPanel.showPIDSlider();
1494     }
1495     else
1496     // remove PIDColouring
1497     {
1498       sg.cs.setThreshold(0, ap.av.isIgnoreGapsConsensus());
1499     }
1500
1501     refresh();
1502   }
1503
1504   /**
1505    * Open a panel where the user can choose which types of sequence annotation
1506    * to show or hide.
1507    * 
1508    * @param e
1509    */
1510   protected void chooseAnnotations_actionPerformed(ActionEvent e)
1511   {
1512     // todo correct way to guard against opening a duplicate panel?
1513     new AnnotationChooser(ap);
1514   }
1515
1516   /**
1517    * DOCUMENT ME!
1518    * 
1519    * @param e
1520    *          DOCUMENT ME!
1521    */
1522   protected void conservationMenuItem_actionPerformed()
1523   {
1524     SequenceGroup sg = getGroup();
1525     if (sg.cs == null)
1526     {
1527       return;
1528     }
1529
1530     if (conservationMenuItem.isSelected())
1531     {
1532       // JBPNote: Conservation name shouldn't be i18n translated
1533       Conservation c = new Conservation("Group", sg.getSequences(ap.av
1534               .getHiddenRepSequences()), sg.getStartRes(),
1535               sg.getEndRes() + 1);
1536
1537       c.calculate();
1538       c.verdict(false, ap.av.getConsPercGaps());
1539       sg.cs.setConservation(c);
1540
1541       SliderPanel.setConservationSlider(ap, sg.getGroupColourScheme(),
1542               sg.getName());
1543       SliderPanel.showConservationSlider();
1544     }
1545     else
1546     // remove ConservationColouring
1547     {
1548       sg.cs.setConservation(null);
1549     }
1550
1551     refresh();
1552   }
1553
1554   public void annotationMenuItem_actionPerformed(ActionEvent actionEvent)
1555   {
1556     SequenceGroup sg = getGroup();
1557     if (sg == null)
1558     {
1559       return;
1560     }
1561
1562     AnnotationColourGradient acg = new AnnotationColourGradient(
1563             sequence.getAnnotation()[0], null,
1564             AnnotationColourGradient.NO_THRESHOLD);
1565
1566     acg.setPredefinedColours(true);
1567     sg.setColourScheme(acg);
1568
1569     refresh();
1570   }
1571
1572   /**
1573    * DOCUMENT ME!
1574    * 
1575    * @param e
1576    *          DOCUMENT ME!
1577    */
1578   protected void groupName_actionPerformed()
1579   {
1580
1581     SequenceGroup sg = getGroup();
1582     EditNameDialog dialog = new EditNameDialog(sg.getName(),
1583             sg.getDescription(), "       "
1584                     + MessageManager.getString("label.group_name") + " ",
1585             MessageManager.getString("label.group_description") + " ",
1586             MessageManager.getString("label.edit_group_name_description"),
1587             ap.alignFrame);
1588
1589     if (!dialog.accept)
1590     {
1591       return;
1592     }
1593
1594     sg.setName(dialog.getName());
1595     sg.setDescription(dialog.getDescription());
1596     refresh();
1597   }
1598
1599   /**
1600    * Get selection group - adding it to the alignment if necessary.
1601    * 
1602    * @return sequence group to operate on
1603    */
1604   SequenceGroup getGroup()
1605   {
1606     SequenceGroup sg = ap.av.getSelectionGroup();
1607     // this method won't add a new group if it already exists
1608     if (sg != null)
1609     {
1610       ap.av.getAlignment().addGroup(sg);
1611     }
1612
1613     return sg;
1614   }
1615
1616   /**
1617    * DOCUMENT ME!
1618    * 
1619    * @param e
1620    *          DOCUMENT ME!
1621    */
1622   void sequenceName_actionPerformed()
1623   {
1624     EditNameDialog dialog = new EditNameDialog(sequence.getName(),
1625             sequence.getDescription(),
1626             "       " + MessageManager.getString("label.sequence_name")
1627                     + " ",
1628             MessageManager.getString("label.sequence_description") + " ",
1629             MessageManager
1630                     .getString("label.edit_sequence_name_description"),
1631             ap.alignFrame);
1632
1633     if (!dialog.accept)
1634     {
1635       return;
1636     }
1637
1638     if (dialog.getName() != null)
1639     {
1640       if (dialog.getName().indexOf(" ") > -1)
1641       {
1642         JvOptionPane
1643                 .showMessageDialog(
1644                         ap,
1645                         MessageManager
1646                                 .getString("label.spaces_converted_to_backslashes"),
1647                         MessageManager
1648                                 .getString("label.no_spaces_allowed_sequence_name"),
1649                         JvOptionPane.WARNING_MESSAGE);
1650       }
1651
1652       sequence.setName(dialog.getName().replace(' ', '_'));
1653       ap.paintAlignment(false);
1654     }
1655
1656     sequence.setDescription(dialog.getDescription());
1657
1658     ap.av.firePropertyChange("alignment", null, ap.av.getAlignment()
1659             .getSequences());
1660
1661   }
1662
1663   /**
1664    * DOCUMENT ME!
1665    * 
1666    * @param e
1667    *          DOCUMENT ME!
1668    */
1669   void unGroupMenuItem_actionPerformed()
1670   {
1671     SequenceGroup sg = ap.av.getSelectionGroup();
1672     ap.av.getAlignment().deleteGroup(sg);
1673     ap.av.setSelectionGroup(null);
1674     refresh();
1675   }
1676
1677   void createGroupMenuItem_actionPerformed()
1678   {
1679     getGroup(); // implicitly creates group - note - should apply defaults / use
1680                 // standard alignment window logic for this
1681     refresh();
1682   }
1683
1684   /**
1685    * DOCUMENT ME!
1686    * 
1687    * @param e
1688    *          DOCUMENT ME!
1689    */
1690   protected void outline_actionPerformed()
1691   {
1692     SequenceGroup sg = getGroup();
1693     Color col = JColorChooser.showDialog(this,
1694             MessageManager.getString("label.select_outline_colour"),
1695             Color.BLUE);
1696
1697     if (col != null)
1698     {
1699       sg.setOutlineColour(col);
1700     }
1701
1702     refresh();
1703   }
1704
1705   /**
1706    * DOCUMENT ME!
1707    * 
1708    * @param e
1709    *          DOCUMENT ME!
1710    */
1711   public void showBoxes_actionPerformed()
1712   {
1713     getGroup().setDisplayBoxes(showBoxes.isSelected());
1714     refresh();
1715   }
1716
1717   /**
1718    * DOCUMENT ME!
1719    * 
1720    * @param e
1721    *          DOCUMENT ME!
1722    */
1723   public void showText_actionPerformed()
1724   {
1725     getGroup().setDisplayText(showText.isSelected());
1726     refresh();
1727   }
1728
1729   /**
1730    * DOCUMENT ME!
1731    * 
1732    * @param e
1733    *          DOCUMENT ME!
1734    */
1735   public void showColourText_actionPerformed()
1736   {
1737     getGroup().setColourText(showColourText.isSelected());
1738     refresh();
1739   }
1740
1741   public void showLink(String url)
1742   {
1743     try
1744     {
1745       jalview.util.BrowserLauncher.openURL(url);
1746     } catch (Exception ex)
1747     {
1748       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1749               MessageManager.getString("label.web_browser_not_found_unix"),
1750               MessageManager.getString("label.web_browser_not_found"),
1751               JvOptionPane.WARNING_MESSAGE);
1752
1753       ex.printStackTrace();
1754     }
1755   }
1756
1757   void hideSequences(boolean representGroup)
1758   {
1759     ap.av.hideSequences(sequence, representGroup);
1760   }
1761
1762   public void copy_actionPerformed()
1763   {
1764     ap.alignFrame.copy_actionPerformed(null);
1765   }
1766
1767   public void cut_actionPerformed()
1768   {
1769     ap.alignFrame.cut_actionPerformed(null);
1770   }
1771
1772   void changeCase(ActionEvent e)
1773   {
1774     Object source = e.getSource();
1775     SequenceGroup sg = ap.av.getSelectionGroup();
1776
1777     if (sg != null)
1778     {
1779       List<int[]> startEnd = ap.av.getVisibleRegionBoundaries(
1780               sg.getStartRes(), sg.getEndRes() + 1);
1781
1782       String description;
1783       int caseChange;
1784
1785       if (source == toggle)
1786       {
1787         description = MessageManager.getString("label.toggle_case");
1788         caseChange = ChangeCaseCommand.TOGGLE_CASE;
1789       }
1790       else if (source == upperCase)
1791       {
1792         description = MessageManager.getString("label.to_upper_case");
1793         caseChange = ChangeCaseCommand.TO_UPPER;
1794       }
1795       else
1796       {
1797         description = MessageManager.getString("label.to_lower_case");
1798         caseChange = ChangeCaseCommand.TO_LOWER;
1799       }
1800
1801       ChangeCaseCommand caseCommand = new ChangeCaseCommand(description,
1802               sg.getSequencesAsArray(ap.av.getHiddenRepSequences()),
1803               startEnd, caseChange);
1804
1805       ap.alignFrame.addHistoryItem(caseCommand);
1806
1807       ap.av.firePropertyChange("alignment", null, ap.av.getAlignment()
1808               .getSequences());
1809
1810     }
1811   }
1812
1813   public void outputText_actionPerformed(ActionEvent e)
1814   {
1815     CutAndPasteTransfer cap = new CutAndPasteTransfer();
1816     cap.setForInput(null);
1817     Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1818             "label.alignment_output_command",
1819             new Object[] { e.getActionCommand() }), 600, 500);
1820
1821     String[] omitHidden = null;
1822
1823     System.out.println("PROMPT USER HERE"); // TODO: decide if a prompt happens
1824     // or we simply trust the user wants
1825     // wysiwig behaviour
1826
1827     FileFormatI fileFormat = FileFormat.forName(e.getActionCommand());
1828     cap.setText(new FormatAdapter(ap).formatSequences(fileFormat, ap, true));
1829   }
1830
1831   public void sequenceFeature_actionPerformed()
1832   {
1833     SequenceGroup sg = ap.av.getSelectionGroup();
1834     if (sg == null)
1835     {
1836       return;
1837     }
1838
1839     int rsize = 0, gSize = sg.getSize();
1840     SequenceI[] rseqs, seqs = new SequenceI[gSize];
1841     SequenceFeature[] tfeatures, features = new SequenceFeature[gSize];
1842
1843     for (int i = 0; i < gSize; i++)
1844     {
1845       int start = sg.getSequenceAt(i).findPosition(sg.getStartRes());
1846       int end = sg.findEndRes(sg.getSequenceAt(i));
1847       if (start <= end)
1848       {
1849         seqs[rsize] = sg.getSequenceAt(i).getDatasetSequence();
1850         features[rsize] = new SequenceFeature(null, null, null, start, end,
1851                 "Jalview");
1852         rsize++;
1853       }
1854     }
1855     rseqs = new SequenceI[rsize];
1856     tfeatures = new SequenceFeature[rsize];
1857     System.arraycopy(seqs, 0, rseqs, 0, rsize);
1858     System.arraycopy(features, 0, tfeatures, 0, rsize);
1859     features = tfeatures;
1860     seqs = rseqs;
1861     if (ap.getSeqPanel().seqCanvas.getFeatureRenderer().amendFeatures(seqs,
1862             features, true, ap))
1863     {
1864       ap.alignFrame.setShowSeqFeatures(true);
1865       ap.highlightSearchResults(null);
1866     }
1867   }
1868
1869   public void textColour_actionPerformed()
1870   {
1871     SequenceGroup sg = getGroup();
1872     if (sg != null)
1873     {
1874       new TextColourChooser().chooseColour(ap, sg);
1875     }
1876   }
1877
1878   public void colourByStructure(String pdbid)
1879   {
1880     Annotation[] anots = ap.av.getStructureSelectionManager()
1881             .colourSequenceFromStructure(sequence, pdbid);
1882
1883     AlignmentAnnotation an = new AlignmentAnnotation("Structure",
1884             "Coloured by " + pdbid, anots);
1885
1886     ap.av.getAlignment().addAnnotation(an);
1887     an.createSequenceMapping(sequence, 0, true);
1888     // an.adjustForAlignment();
1889     ap.av.getAlignment().setAnnotationIndex(an, 0);
1890
1891     ap.adjustAnnotationHeight();
1892
1893     sequence.addAlignmentAnnotation(an);
1894
1895   }
1896
1897   public void editSequence_actionPerformed(ActionEvent actionEvent)
1898   {
1899     SequenceGroup sg = ap.av.getSelectionGroup();
1900
1901     if (sg != null)
1902     {
1903       if (sequence == null)
1904       {
1905         sequence = sg.getSequenceAt(0);
1906       }
1907
1908       EditNameDialog dialog = new EditNameDialog(
1909               sequence.getSequenceAsString(sg.getStartRes(),
1910                       sg.getEndRes() + 1), null,
1911               MessageManager.getString("label.edit_sequence"), null,
1912               MessageManager.getString("label.edit_sequence"),
1913               ap.alignFrame);
1914
1915       if (dialog.accept)
1916       {
1917         EditCommand editCommand = new EditCommand(
1918                 MessageManager.getString("label.edit_sequences"),
1919                 Action.REPLACE, dialog.getName().replace(' ',
1920                         ap.av.getGapCharacter()),
1921                 sg.getSequencesAsArray(ap.av.getHiddenRepSequences()),
1922                 sg.getStartRes(), sg.getEndRes() + 1, ap.av.getAlignment());
1923
1924         ap.alignFrame.addHistoryItem(editCommand);
1925
1926         ap.av.firePropertyChange("alignment", null, ap.av.getAlignment()
1927                 .getSequences());
1928       }
1929     }
1930   }
1931
1932   /**
1933    * Action on user selecting an item from the colour menu (that does not have
1934    * its bespoke action handler)
1935    */
1936   @Override
1937   public void changeColour_actionPerformed(String colourSchemeName)
1938   {
1939     SequenceGroup sg = getGroup();
1940     if (ResidueColourScheme.USER_DEFINED.equals(colourSchemeName))
1941     {
1942       /*
1943        * open a panel to load or configure a user-defined colour scheme
1944        */
1945       new UserDefinedColours(ap, sg);
1946     }
1947     else
1948     {
1949       /*
1950        * switch to the chosen colour scheme (or null for None)
1951        */
1952       ColourSchemeI colourScheme = ColourSchemes.getInstance().getColourScheme(
1953               colourSchemeName, sg, ap.av.getHiddenRepSequences());
1954       sg.setColourScheme(colourScheme);
1955       if (colourScheme instanceof Blosum62ColourScheme
1956               || colourScheme instanceof PIDColourScheme)
1957       {
1958         sg.cs.setConsensus(AAFrequency.calculate(
1959                 sg.getSequences(ap.av.getHiddenRepSequences()),
1960                 sg.getStartRes(), sg.getEndRes() + 1));
1961       }
1962     }
1963
1964     refresh();
1965   }
1966
1967 }