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