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