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