Merge branch 'develop' into features/r2_11_2_alphafold/JAL-2349_JAL-3855
[jalview.git] / src / jalview / gui / AnnotationLabels.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 java.awt.Color;
24 import java.awt.Cursor;
25 import java.awt.Dimension;
26 import java.awt.Font;
27 import java.awt.FontMetrics;
28 import java.awt.Graphics;
29 import java.awt.Graphics2D;
30 import java.awt.RenderingHints;
31 import java.awt.Toolkit;
32 import java.awt.datatransfer.StringSelection;
33 import java.awt.event.ActionEvent;
34 import java.awt.event.ActionListener;
35 import java.awt.event.MouseEvent;
36 import java.awt.event.MouseListener;
37 import java.awt.event.MouseMotionListener;
38 import java.awt.geom.AffineTransform;
39 import java.util.Arrays;
40 import java.util.Collections;
41 import java.util.Iterator;
42 import java.util.Locale;
43
44 import javax.swing.JCheckBoxMenuItem;
45 import javax.swing.JMenuItem;
46 import javax.swing.JPanel;
47 import javax.swing.JPopupMenu;
48 import javax.swing.SwingUtilities;
49 import javax.swing.ToolTipManager;
50
51 import jalview.analysis.AlignSeq;
52 import jalview.analysis.AlignmentUtils;
53 import jalview.datamodel.Alignment;
54 import jalview.datamodel.AlignmentAnnotation;
55 import jalview.datamodel.Annotation;
56 import jalview.datamodel.HiddenColumns;
57 import jalview.datamodel.Sequence;
58 import jalview.datamodel.SequenceGroup;
59 import jalview.datamodel.SequenceI;
60 import jalview.io.FileFormat;
61 import jalview.io.FormatAdapter;
62 import jalview.util.Comparison;
63 import jalview.util.MessageManager;
64 import jalview.util.Platform;
65
66 /**
67  * The panel that holds the labels for alignment annotations, providing
68  * tooltips, context menus, drag to reorder rows, and drag to adjust panel
69  * height
70  */
71 public class AnnotationLabels extends JPanel
72         implements MouseListener, MouseMotionListener, ActionListener
73 {
74   private static final String HTML_END_TAG = "</html>";
75
76   private static final String HTML_START_TAG = "<html>";
77
78   /**
79    * width in pixels within which height adjuster arrows are shown and active
80    */
81   private static final int HEIGHT_ADJUSTER_WIDTH = 50;
82
83   /**
84    * height in pixels for allowing height adjuster to be active
85    */
86   private static int HEIGHT_ADJUSTER_HEIGHT = 10;
87
88   private static final Font font = new Font("Arial", Font.PLAIN, 11);
89
90   private static final String TOGGLE_LABELSCALE = MessageManager
91           .getString("label.scale_label_to_column");
92
93   private static final String ADDNEW = MessageManager
94           .getString("label.add_new_row");
95
96   private static final String EDITNAME = MessageManager
97           .getString("label.edit_label_description");
98
99   private static final String HIDE = MessageManager
100           .getString("label.hide_row");
101
102   private static final String DELETE = MessageManager
103           .getString("label.delete_row");
104
105   private static final String SHOWALL = MessageManager
106           .getString("label.show_all_hidden_rows");
107
108   private static final String OUTPUT_TEXT = MessageManager
109           .getString("label.export_annotation");
110
111   private static final String COPYCONS_SEQ = MessageManager
112           .getString("label.copy_consensus_sequence");
113
114   private final boolean debugRedraw = false;
115
116   private AlignmentPanel ap;
117
118   AlignViewport av;
119
120   private MouseEvent dragEvent;
121
122   private int oldY;
123
124   private int selectedRow;
125
126   private int scrollOffset = 0;
127
128   private boolean hasHiddenRows;
129
130   private boolean resizePanel = false;
131
132   /**
133    * Creates a new AnnotationLabels object
134    * 
135    * @param ap
136    */
137   public AnnotationLabels(AlignmentPanel ap)
138   {
139
140     this.ap = ap;
141     av = ap.av;
142     ToolTipManager.sharedInstance().registerComponent(this);
143
144     addMouseListener(this);
145     addMouseMotionListener(this);
146     addMouseWheelListener(ap.getAnnotationPanel());
147   }
148
149   public AnnotationLabels(AlignViewport av)
150   {
151     this.av = av;
152   }
153
154   /**
155    * DOCUMENT ME!
156    * 
157    * @param y
158    *          DOCUMENT ME!
159    */
160   public void setScrollOffset(int y)
161   {
162     scrollOffset = y;
163     repaint();
164   }
165
166   /**
167    * sets selectedRow to -2 if no annotation preset, -1 if no visible row is at
168    * y
169    * 
170    * @param y
171    *          coordinate position to search for a row
172    */
173   void getSelectedRow(int y)
174   {
175     int height = 0;
176     AlignmentAnnotation[] aa = ap.av.getAlignment()
177             .getAlignmentAnnotation();
178     selectedRow = -2;
179     if (aa != null)
180     {
181       for (int i = 0; i < aa.length; i++)
182       {
183         selectedRow = -1;
184         if (!aa[i].visible)
185         {
186           continue;
187         }
188
189         height += aa[i].height;
190
191         if (y < height)
192         {
193           selectedRow = i;
194
195           break;
196         }
197       }
198     }
199   }
200
201   /**
202    * DOCUMENT ME!
203    * 
204    * @param evt
205    *          DOCUMENT ME!
206    */
207   @Override
208   public void actionPerformed(ActionEvent evt)
209   {
210     AlignmentAnnotation[] aa = ap.av.getAlignment()
211             .getAlignmentAnnotation();
212
213     String action = evt.getActionCommand();
214     if (ADDNEW.equals(action))
215     {
216       /*
217        * non-returning dialog
218        */
219       AlignmentAnnotation newAnnotation = new AlignmentAnnotation(null,
220               null, new Annotation[ap.av.getAlignment().getWidth()]);
221       editLabelDescription(newAnnotation, true);
222     }
223     else if (EDITNAME.equals(action))
224     {
225       /*
226        * non-returning dialog
227        */
228       editLabelDescription(aa[selectedRow], false);
229     }
230     else if (HIDE.equals(action))
231     {
232       aa[selectedRow].visible = false;
233     }
234     else if (DELETE.equals(action))
235     {
236       ap.av.getAlignment().deleteAnnotation(aa[selectedRow]);
237       ap.av.getCalcManager().removeWorkerForAnnotation(aa[selectedRow]);
238     }
239     else if (SHOWALL.equals(action))
240     {
241       for (int i = 0; i < aa.length; i++)
242       {
243         if (!aa[i].visible && aa[i].annotations != null)
244         {
245           aa[i].visible = true;
246         }
247       }
248     }
249     else if (OUTPUT_TEXT.equals(action))
250     {
251       new AnnotationExporter(ap).exportAnnotation(aa[selectedRow]);
252     }
253     else if (COPYCONS_SEQ.equals(action))
254     {
255       SequenceI cons = null;
256       if (aa[selectedRow].groupRef != null)
257       {
258         cons = aa[selectedRow].groupRef.getConsensusSeq();
259       }
260       else
261       {
262         cons = av.getConsensusSeq();
263       }
264       if (cons != null)
265       {
266         copy_annotseqtoclipboard(cons);
267       }
268     }
269     else if (TOGGLE_LABELSCALE.equals(action))
270     {
271       aa[selectedRow].scaleColLabel = !aa[selectedRow].scaleColLabel;
272     }
273
274     ap.refresh(true);
275   }
276
277   /**
278    * Shows a dialog where the annotation name and description may be edited. If
279    * parameter addNew is true, then on confirmation, a new AlignmentAnnotation
280    * is added, else an existing annotation is updated.
281    * 
282    * @param annotation
283    * @param addNew
284    */
285   void editLabelDescription(AlignmentAnnotation annotation, boolean addNew)
286   {
287     String name = MessageManager.getString("label.annotation_name");
288     String description = MessageManager
289             .getString("label.annotation_description");
290     String title = MessageManager
291             .getString("label.edit_annotation_name_description");
292     EditNameDialog dialog = new EditNameDialog(annotation.label,
293             annotation.description, name, description);
294
295     dialog.showDialog(ap.alignFrame, title, () -> {
296       annotation.label = dialog.getName();
297       String text = dialog.getDescription();
298       if (text != null && text.length() == 0)
299       {
300         text = null;
301       }
302       annotation.description = text;
303       if (addNew)
304       {
305         ap.av.getAlignment().addAnnotation(annotation);
306         ap.av.getAlignment().setAnnotationIndex(annotation, 0);
307       }
308       ap.refresh(true);
309       return null;
310     });
311   }
312
313   @Override
314   public void mousePressed(MouseEvent evt)
315   {
316     getSelectedRow(evt.getY() - getScrollOffset());
317     oldY = evt.getY();
318     if (evt.isPopupTrigger())
319     {
320       showPopupMenu(evt);
321     }
322   }
323
324   /**
325    * Build and show the Pop-up menu at the right-click mouse position
326    * 
327    * @param evt
328    */
329   void showPopupMenu(MouseEvent evt)
330   {
331     evt.consume();
332     final AlignmentAnnotation[] aa = ap.av.getAlignment()
333             .getAlignmentAnnotation();
334
335     JPopupMenu pop = new JPopupMenu(
336             MessageManager.getString("label.annotations"));
337     JMenuItem item = new JMenuItem(ADDNEW);
338     item.addActionListener(this);
339     pop.add(item);
340     if (selectedRow < 0)
341     {
342       if (hasHiddenRows)
343       { // let the user make everything visible again
344         item = new JMenuItem(SHOWALL);
345         item.addActionListener(this);
346         pop.add(item);
347       }
348       pop.show(this, evt.getX(), evt.getY());
349       return;
350     }
351     item = new JMenuItem(EDITNAME);
352     item.addActionListener(this);
353     pop.add(item);
354     item = new JMenuItem(HIDE);
355     item.addActionListener(this);
356     pop.add(item);
357     // JAL-1264 hide all sequence-specific annotations of this type
358     if (selectedRow < aa.length)
359     {
360       if (aa[selectedRow].sequenceRef != null)
361       {
362         final String label = aa[selectedRow].label;
363         JMenuItem hideType = new JMenuItem();
364         String text = MessageManager.getString("label.hide_all") + " "
365                 + label;
366         hideType.setText(text);
367         hideType.addActionListener(new ActionListener()
368         {
369           @Override
370           public void actionPerformed(ActionEvent e)
371           {
372             AlignmentUtils.showOrHideSequenceAnnotations(
373                     ap.av.getAlignment(), Collections.singleton(label),
374                     null, false, false);
375             ap.refresh(true);
376           }
377         });
378         pop.add(hideType);
379       }
380     }
381     item = new JMenuItem(DELETE);
382     item.addActionListener(this);
383     pop.add(item);
384     if (hasHiddenRows)
385     {
386       item = new JMenuItem(SHOWALL);
387       item.addActionListener(this);
388       pop.add(item);
389     }
390     item = new JMenuItem(OUTPUT_TEXT);
391     item.addActionListener(this);
392     pop.add(item);
393     // TODO: annotation object should be typed for autocalculated/derived
394     // property methods
395     if (selectedRow < aa.length)
396     {
397       final String label = aa[selectedRow].label;
398       if (!aa[selectedRow].autoCalculated)
399       {
400         if (aa[selectedRow].graph == AlignmentAnnotation.NO_GRAPH)
401         {
402           // display formatting settings for this row.
403           pop.addSeparator();
404           // av and sequencegroup need to implement same interface for
405           item = new JCheckBoxMenuItem(TOGGLE_LABELSCALE,
406                   aa[selectedRow].scaleColLabel);
407           item.addActionListener(this);
408           pop.add(item);
409         }
410       }
411       else if (label.indexOf("Consensus") > -1)
412       {
413         addConsensusMenuOptions(ap, aa[selectedRow], pop);
414
415         final JMenuItem consclipbrd = new JMenuItem(COPYCONS_SEQ);
416         consclipbrd.addActionListener(this);
417         pop.add(consclipbrd);
418       }
419     }
420     pop.show(this, evt.getX(), evt.getY());
421   }
422
423   /**
424    * A helper method that adds menu options for calculation and visualisation of
425    * group and/or alignment consensus annotation to a popup menu. This is
426    * designed to be reusable for either unwrapped mode (popup menu is shown on
427    * component AnnotationLabels), or wrapped mode (popup menu is shown on
428    * IdPanel when the mouse is over an annotation label).
429    * 
430    * @param ap
431    * @param ann
432    * @param pop
433    */
434   static void addConsensusMenuOptions(AlignmentPanel ap,
435           AlignmentAnnotation ann, JPopupMenu pop)
436   {
437     pop.addSeparator();
438
439     final JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(
440             MessageManager.getString("label.ignore_gaps_consensus"),
441             (ann.groupRef != null) ? ann.groupRef.getIgnoreGapsConsensus()
442                     : ap.av.isIgnoreGapsConsensus());
443     final AlignmentAnnotation aaa = ann;
444     cbmi.addActionListener(new ActionListener()
445     {
446       @Override
447       public void actionPerformed(ActionEvent e)
448       {
449         if (aaa.groupRef != null)
450         {
451           aaa.groupRef.setIgnoreGapsConsensus(cbmi.getState());
452           ap.getAnnotationPanel()
453                   .paint(ap.getAnnotationPanel().getGraphics());
454         }
455         else
456         {
457           ap.av.setIgnoreGapsConsensus(cbmi.getState(), ap);
458         }
459         ap.alignmentChanged();
460       }
461     });
462     pop.add(cbmi);
463
464     if (aaa.groupRef != null)
465     {
466       /*
467        * group consensus options
468        */
469       final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
470               MessageManager.getString("label.show_group_histogram"),
471               ann.groupRef.isShowConsensusHistogram());
472       chist.addActionListener(new ActionListener()
473       {
474         @Override
475         public void actionPerformed(ActionEvent e)
476         {
477           aaa.groupRef.setShowConsensusHistogram(chist.getState());
478           ap.repaint();
479         }
480       });
481       pop.add(chist);
482       final JCheckBoxMenuItem cprofl = new JCheckBoxMenuItem(
483               MessageManager.getString("label.show_group_logo"),
484               ann.groupRef.isShowSequenceLogo());
485       cprofl.addActionListener(new ActionListener()
486       {
487         @Override
488         public void actionPerformed(ActionEvent e)
489         {
490           aaa.groupRef.setshowSequenceLogo(cprofl.getState());
491           ap.repaint();
492         }
493       });
494       pop.add(cprofl);
495       final JCheckBoxMenuItem cproflnorm = new JCheckBoxMenuItem(
496               MessageManager.getString("label.normalise_group_logo"),
497               ann.groupRef.isNormaliseSequenceLogo());
498       cproflnorm.addActionListener(new ActionListener()
499       {
500         @Override
501         public void actionPerformed(ActionEvent e)
502         {
503           aaa.groupRef.setNormaliseSequenceLogo(cproflnorm.getState());
504           // automatically enable logo display if we're clicked
505           aaa.groupRef.setshowSequenceLogo(true);
506           ap.repaint();
507         }
508       });
509       pop.add(cproflnorm);
510     }
511     else
512     {
513       /*
514        * alignment consensus options
515        */
516       final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
517               MessageManager.getString("label.show_histogram"),
518               ap.av.isShowConsensusHistogram());
519       chist.addActionListener(new ActionListener()
520       {
521         @Override
522         public void actionPerformed(ActionEvent e)
523         {
524           ap.av.setShowConsensusHistogram(chist.getState());
525           ap.alignFrame.setMenusForViewport();
526           ap.repaint();
527         }
528       });
529       pop.add(chist);
530       final JCheckBoxMenuItem cprof = new JCheckBoxMenuItem(
531               MessageManager.getString("label.show_logo"),
532               ap.av.isShowSequenceLogo());
533       cprof.addActionListener(new ActionListener()
534       {
535         @Override
536         public void actionPerformed(ActionEvent e)
537         {
538           ap.av.setShowSequenceLogo(cprof.getState());
539           ap.alignFrame.setMenusForViewport();
540           ap.repaint();
541         }
542       });
543       pop.add(cprof);
544       final JCheckBoxMenuItem cprofnorm = new JCheckBoxMenuItem(
545               MessageManager.getString("label.normalise_logo"),
546               ap.av.isNormaliseSequenceLogo());
547       cprofnorm.addActionListener(new ActionListener()
548       {
549         @Override
550         public void actionPerformed(ActionEvent e)
551         {
552           ap.av.setShowSequenceLogo(true);
553           ap.av.setNormaliseSequenceLogo(cprofnorm.getState());
554           ap.alignFrame.setMenusForViewport();
555           ap.repaint();
556         }
557       });
558       pop.add(cprofnorm);
559     }
560   }
561
562   /**
563    * Reorders annotation rows after a drag of a label
564    * 
565    * @param evt
566    */
567   @Override
568   public void mouseReleased(MouseEvent evt)
569   {
570     if (evt.isPopupTrigger())
571     {
572       showPopupMenu(evt);
573       return;
574     }
575
576     int start = selectedRow;
577     getSelectedRow(evt.getY() - getScrollOffset());
578     int end = selectedRow;
579
580     /*
581      * if dragging to resize instead, start == end
582      */
583     if (start != end)
584     {
585       // Swap these annotations
586       AlignmentAnnotation startAA = ap.av.getAlignment()
587               .getAlignmentAnnotation()[start];
588       if (end == -1)
589       {
590         end = ap.av.getAlignment().getAlignmentAnnotation().length - 1;
591       }
592       AlignmentAnnotation endAA = ap.av.getAlignment()
593               .getAlignmentAnnotation()[end];
594
595       ap.av.getAlignment().getAlignmentAnnotation()[end] = startAA;
596       ap.av.getAlignment().getAlignmentAnnotation()[start] = endAA;
597     }
598
599     resizePanel = false;
600     dragEvent = null;
601     repaint();
602     ap.getAnnotationPanel().repaint();
603   }
604
605   /**
606    * Removes the height adjuster image on leaving the panel, unless currently
607    * dragging it
608    */
609   @Override
610   public void mouseExited(MouseEvent evt)
611   {
612     if (resizePanel && dragEvent == null)
613     {
614       resizePanel = false;
615       repaint();
616     }
617   }
618
619   /**
620    * A mouse drag may be either an adjustment of the panel height (if flag
621    * resizePanel is set on), or a reordering of the annotation rows. The former
622    * is dealt with by this method, the latter in mouseReleased.
623    * 
624    * @param evt
625    */
626   @Override
627   public void mouseDragged(MouseEvent evt)
628   {
629     dragEvent = evt;
630
631     if (resizePanel)
632     {
633       Dimension d = ap.annotationScroller.getPreferredSize();
634       int dif = evt.getY() - oldY;
635
636       dif /= ap.av.getCharHeight();
637       dif *= ap.av.getCharHeight();
638
639       if ((d.height - dif) > 20)
640       {
641         ap.annotationScroller
642                 .setPreferredSize(new Dimension(d.width, d.height - dif));
643         d = ap.annotationSpaceFillerHolder.getPreferredSize();
644         ap.annotationSpaceFillerHolder
645                 .setPreferredSize(new Dimension(d.width, d.height - dif));
646         ap.paintAlignment(true, false);
647       }
648
649       ap.addNotify();
650     }
651     else
652     {
653       repaint();
654     }
655   }
656
657   /**
658    * Updates the tooltip as the mouse moves over the labels
659    * 
660    * @param evt
661    */
662   @Override
663   public void mouseMoved(MouseEvent evt)
664   {
665     showOrHideAdjuster(evt);
666
667     getSelectedRow(evt.getY() - getScrollOffset());
668
669     if (selectedRow > -1 && ap.av.getAlignment()
670             .getAlignmentAnnotation().length > selectedRow)
671     {
672       AlignmentAnnotation[] anns = ap.av.getAlignment()
673               .getAlignmentAnnotation();
674       AlignmentAnnotation aa = anns[selectedRow];
675
676       String desc = getTooltip(aa);
677       this.setToolTipText(desc);
678       String msg = getStatusMessage(aa, anns);
679       ap.alignFrame.setStatus(msg);
680     }
681   }
682
683   /**
684    * Constructs suitable text to show in the status bar when over an annotation
685    * label, containing the associated sequence name (if any), and the annotation
686    * labels (or all labels for a graph group annotation)
687    * 
688    * @param aa
689    * @param anns
690    * @return
691    */
692   static String getStatusMessage(AlignmentAnnotation aa,
693           AlignmentAnnotation[] anns)
694   {
695     if (aa == null)
696     {
697       return null;
698     }
699
700     StringBuilder msg = new StringBuilder(32);
701     if (aa.sequenceRef != null)
702     {
703       msg.append(aa.sequenceRef.getName()).append(" : ");
704     }
705
706     if (aa.graphGroup == -1)
707     {
708       msg.append(aa.label);
709     }
710     else if (anns != null)
711     {
712       boolean first = true;
713       for (int i = anns.length - 1; i >= 0; i--)
714       {
715         if (anns[i].graphGroup == aa.graphGroup)
716         {
717           if (!first)
718           {
719             msg.append(", ");
720           }
721           msg.append(anns[i].label);
722           first = false;
723         }
724       }
725     }
726
727     return msg.toString();
728   }
729
730   /**
731    * Answers a tooltip, formatted as html, containing the annotation description
732    * (prefixed by associated sequence id if applicable), and the annotation
733    * (non-positional) score if it has one. Answers null if neither description
734    * nor score is found.
735    * 
736    * @param aa
737    * @return
738    */
739   static String getTooltip(AlignmentAnnotation aa)
740   {
741     if (aa == null)
742     {
743       return null;
744     }
745     StringBuilder tooltip = new StringBuilder();
746     if (aa.description != null && !aa.description.equals("New description"))
747     {
748       // TODO: we could refactor and merge this code with the code in
749       // jalview.gui.SeqPanel.mouseMoved(..) that formats sequence feature
750       // tooltips
751       String desc = aa.getDescription(true).trim();
752       if (!desc.toLowerCase(Locale.ROOT).startsWith(HTML_START_TAG))
753       {
754         tooltip.append(HTML_START_TAG);
755         desc = desc.replace("<", "&lt;");
756       }
757       else if (desc.toLowerCase(Locale.ROOT).endsWith(HTML_END_TAG))
758       {
759         desc = desc.substring(0, desc.length() - HTML_END_TAG.length());
760       }
761       tooltip.append(desc);
762     }
763     else
764     {
765       // begin the tooltip's html fragment
766       tooltip.append(HTML_START_TAG);
767     }
768     if (aa.hasScore())
769     {
770       if (tooltip.length() > HTML_START_TAG.length())
771       {
772         tooltip.append("<br/>");
773       }
774       // TODO: limit precision of score to avoid noise from imprecise
775       // doubles
776       // (64.7 becomes 64.7+/some tiny value).
777       tooltip.append(" Score: ").append(String.valueOf(aa.score));
778     }
779
780     if (tooltip.length() > HTML_START_TAG.length())
781     {
782       return tooltip.append(HTML_END_TAG).toString();
783     }
784
785     /*
786      * nothing in the tooltip (except "<html>")
787      */
788     return null;
789   }
790
791   /**
792    * Shows the height adjuster image if the mouse moves into the top left
793    * region, or hides it if the mouse leaves the regio
794    * 
795    * @param evt
796    */
797   protected void showOrHideAdjuster(MouseEvent evt)
798   {
799     boolean was = resizePanel;
800     resizePanel = evt.getY() < HEIGHT_ADJUSTER_HEIGHT
801             && evt.getX() < HEIGHT_ADJUSTER_WIDTH;
802
803     if (resizePanel != was)
804     {
805       setCursor(Cursor
806               .getPredefinedCursor(resizePanel ? Cursor.S_RESIZE_CURSOR
807                       : Cursor.DEFAULT_CURSOR));
808       repaint();
809     }
810   }
811
812   @Override
813   public void mouseClicked(MouseEvent evt)
814   {
815     final AlignmentAnnotation[] aa = ap.av.getAlignment()
816             .getAlignmentAnnotation();
817     if (!evt.isPopupTrigger() && SwingUtilities.isLeftMouseButton(evt))
818     {
819       if (selectedRow > -1 && selectedRow < aa.length)
820       {
821         if (aa[selectedRow].groupRef != null)
822         {
823           if (evt.getClickCount() >= 2)
824           {
825             // todo: make the ap scroll to the selection - not necessary, first
826             // click highlights/scrolls, second selects
827             ap.getSeqPanel().ap.getIdPanel().highlightSearchResults(null);
828             // process modifiers
829             SequenceGroup sg = ap.av.getSelectionGroup();
830             if (sg == null || sg == aa[selectedRow].groupRef
831                     || !(Platform.isControlDown(evt) || evt.isShiftDown()))
832             {
833               if (Platform.isControlDown(evt) || evt.isShiftDown())
834               {
835                 // clone a new selection group from the associated group
836                 ap.av.setSelectionGroup(
837                         new SequenceGroup(aa[selectedRow].groupRef));
838               }
839               else
840               {
841                 // set selection to the associated group so it can be edited
842                 ap.av.setSelectionGroup(aa[selectedRow].groupRef);
843               }
844             }
845             else
846             {
847               // modify current selection with associated group
848               int remainToAdd = aa[selectedRow].groupRef.getSize();
849               for (SequenceI sgs : aa[selectedRow].groupRef.getSequences())
850               {
851                 if (jalview.util.Platform.isControlDown(evt))
852                 {
853                   sg.addOrRemove(sgs, --remainToAdd == 0);
854                 }
855                 else
856                 {
857                   // notionally, we should also add intermediate sequences from
858                   // last added sequence ?
859                   sg.addSequence(sgs, --remainToAdd == 0);
860                 }
861               }
862             }
863
864             ap.paintAlignment(false, false);
865             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
866             ap.av.sendSelection();
867           }
868           else
869           {
870             ap.getSeqPanel().ap.getIdPanel().highlightSearchResults(
871                     aa[selectedRow].groupRef.getSequences(null));
872           }
873           return;
874         }
875         else if (aa[selectedRow].sequenceRef != null)
876         {
877           if (evt.getClickCount() == 1)
878           {
879             ap.getSeqPanel().ap.getIdPanel()
880                     .highlightSearchResults(Arrays.asList(new SequenceI[]
881                     { aa[selectedRow].sequenceRef }));
882           }
883           else if (evt.getClickCount() >= 2)
884           {
885             ap.getSeqPanel().ap.getIdPanel().highlightSearchResults(null);
886             SequenceGroup sg = ap.av.getSelectionGroup();
887             if (sg != null)
888             {
889               // we make a copy rather than edit the current selection if no
890               // modifiers pressed
891               // see Enhancement JAL-1557
892               if (!(Platform.isControlDown(evt) || evt.isShiftDown()))
893               {
894                 sg = new SequenceGroup(sg);
895                 sg.clear();
896                 sg.addSequence(aa[selectedRow].sequenceRef, false);
897               }
898               else
899               {
900                 if (Platform.isControlDown(evt))
901                 {
902                   sg.addOrRemove(aa[selectedRow].sequenceRef, true);
903                 }
904                 else
905                 {
906                   // notionally, we should also add intermediate sequences from
907                   // last added sequence ?
908                   sg.addSequence(aa[selectedRow].sequenceRef, true);
909                 }
910               }
911             }
912             else
913             {
914               sg = new SequenceGroup();
915               sg.setStartRes(0);
916               sg.setEndRes(ap.av.getAlignment().getWidth() - 1);
917               sg.addSequence(aa[selectedRow].sequenceRef, false);
918             }
919             ap.av.setSelectionGroup(sg);
920             ap.paintAlignment(false, false);
921             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
922             ap.av.sendSelection();
923           }
924
925         }
926       }
927       return;
928     }
929   }
930
931   /**
932    * do a single sequence copy to jalview and the system clipboard
933    * 
934    * @param sq
935    *          sequence to be copied to clipboard
936    */
937   protected void copy_annotseqtoclipboard(SequenceI sq)
938   {
939     SequenceI[] seqs = new SequenceI[] { sq };
940     String[] omitHidden = null;
941     SequenceI[] dseqs = new SequenceI[] { sq.getDatasetSequence() };
942     if (dseqs[0] == null)
943     {
944       dseqs[0] = new Sequence(sq);
945       dseqs[0].setSequence(AlignSeq.extractGaps(Comparison.GapChars,
946               sq.getSequenceAsString()));
947
948       sq.setDatasetSequence(dseqs[0]);
949     }
950     Alignment ds = new Alignment(dseqs);
951     if (av.hasHiddenColumns())
952     {
953       Iterator<int[]> it = av.getAlignment().getHiddenColumns()
954               .getVisContigsIterator(0, sq.getLength(), false);
955       omitHidden = new String[] { sq.getSequenceStringFromIterator(it) };
956     }
957
958     int[] alignmentStartEnd = new int[] { 0, ds.getWidth() - 1 };
959     if (av.hasHiddenColumns())
960     {
961       alignmentStartEnd = av.getAlignment().getHiddenColumns()
962               .getVisibleStartAndEndIndex(av.getAlignment().getWidth());
963     }
964
965     String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
966             seqs, omitHidden, alignmentStartEnd);
967
968     Toolkit.getDefaultToolkit().getSystemClipboard()
969             .setContents(new StringSelection(output), Desktop.instance);
970
971     HiddenColumns hiddenColumns = null;
972
973     if (av.hasHiddenColumns())
974     {
975       hiddenColumns = new HiddenColumns(
976               av.getAlignment().getHiddenColumns());
977     }
978
979     Desktop.jalviewClipboard = new Object[] { seqs, ds, // what is the dataset
980                                                         // of a consensus
981                                                         // sequence ? need to
982                                                         // flag
983         // sequence as special.
984         hiddenColumns };
985   }
986
987   /**
988    * DOCUMENT ME!
989    * 
990    * @param g1
991    *          DOCUMENT ME!
992    */
993   @Override
994   public void paintComponent(Graphics g)
995   {
996
997     int width = getWidth();
998     if (width == 0)
999     {
1000       width = ap.calculateIdWidth().width;
1001     }
1002
1003     Graphics2D g2 = (Graphics2D) g;
1004     if (av.antiAlias)
1005     {
1006       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1007               RenderingHints.VALUE_ANTIALIAS_ON);
1008     }
1009
1010     drawComponent(g2, true, width);
1011
1012   }
1013
1014   /**
1015    * Draw the full set of annotation Labels for the alignment at the given
1016    * cursor
1017    * 
1018    * @param g
1019    *          Graphics2D instance (needed for font scaling)
1020    * @param width
1021    *          Width for scaling labels
1022    * 
1023    */
1024   public void drawComponent(Graphics g, int width)
1025   {
1026     drawComponent(g, false, width);
1027   }
1028
1029   /**
1030    * Draw the full set of annotation Labels for the alignment at the given
1031    * cursor
1032    * 
1033    * @param g
1034    *          Graphics2D instance (needed for font scaling)
1035    * @param clip
1036    *          - true indicates that only current visible area needs to be
1037    *          rendered
1038    * @param width
1039    *          Width for scaling labels
1040    */
1041   public void drawComponent(Graphics g, boolean clip, int width)
1042   {
1043     if (av.getFont().getSize() < 10)
1044     {
1045       g.setFont(font);
1046     }
1047     else
1048     {
1049       g.setFont(av.getFont());
1050     }
1051
1052     FontMetrics fm = g.getFontMetrics(g.getFont());
1053     g.setColor(Color.white);
1054     g.fillRect(0, 0, getWidth(), getHeight());
1055
1056     g.translate(0, getScrollOffset());
1057     g.setColor(Color.black);
1058     SequenceI lastSeqRef = null;
1059     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
1060     int fontHeight = g.getFont().getSize();
1061     int y = 0;
1062     int x = 0;
1063     int graphExtras = 0;
1064     int offset = 0;
1065     Font baseFont = g.getFont();
1066     FontMetrics baseMetrics = fm;
1067     int ofontH = fontHeight;
1068     int sOffset = 0;
1069     int visHeight = 0;
1070     int[] visr = (ap != null && ap.getAnnotationPanel() != null)
1071             ? ap.getAnnotationPanel().getVisibleVRange()
1072             : null;
1073     if (clip && visr != null)
1074     {
1075       sOffset = visr[0];
1076       visHeight = visr[1];
1077     }
1078     boolean visible = true, before = false, after = false;
1079     if (aa != null)
1080     {
1081       hasHiddenRows = false;
1082       int olY = 0;
1083       for (int i = 0; i < aa.length; i++)
1084       {
1085         visible = true;
1086         if (!aa[i].visible)
1087         {
1088           hasHiddenRows = true;
1089           continue;
1090         }
1091         olY = y;
1092         y += aa[i].height;
1093         if (clip)
1094         {
1095           if (y < sOffset)
1096           {
1097             if (!before)
1098             {
1099               if (debugRedraw)
1100               {
1101                 System.out.println("before vis: " + i);
1102               }
1103               before = true;
1104             }
1105             // don't draw what isn't visible
1106             continue;
1107           }
1108           if (olY > visHeight)
1109           {
1110
1111             if (!after)
1112             {
1113               if (debugRedraw)
1114               {
1115                 System.out.println(
1116                         "Scroll offset: " + sOffset + " after vis: " + i);
1117               }
1118               after = true;
1119             }
1120             // don't draw what isn't visible
1121             continue;
1122           }
1123         }
1124         g.setColor(Color.black);
1125
1126         offset = -aa[i].height / 2;
1127
1128         if (aa[i].hasText)
1129         {
1130           offset += fm.getHeight() / 2;
1131           offset -= fm.getDescent();
1132         }
1133         else
1134         {
1135           offset += fm.getDescent();
1136         }
1137         String label = aa[i].label;
1138         boolean vertBar = false;
1139         if (aa[i].sequenceRef != null)
1140         {
1141           if (aa[i].sequenceRef != lastSeqRef)
1142           {
1143             label = aa[i].sequenceRef.getName() + " " + label;
1144             // TODO record relationship between sequence and this annotation and
1145             // display it here
1146           }
1147           else
1148           {
1149             vertBar = true;
1150           }
1151         }
1152         x = width - fm.stringWidth(label) - 3;
1153
1154         if (aa[i].graphGroup > -1)
1155         {
1156           int groupSize = 0;
1157           // TODO: JAL-1291 revise rendering model so the graphGroup map is
1158           // computed efficiently for all visible labels
1159           for (int gg = 0; gg < aa.length; gg++)
1160           {
1161             if (aa[gg].graphGroup == aa[i].graphGroup)
1162             {
1163               groupSize++;
1164             }
1165           }
1166           if (groupSize * (fontHeight + 8) < aa[i].height)
1167           {
1168             graphExtras = (aa[i].height - (groupSize * (fontHeight + 8)))
1169                     / 2;
1170           }
1171           else
1172           {
1173             // scale font to fit
1174             float h = aa[i].height / (float) groupSize, s;
1175             if (h < 9)
1176             {
1177               visible = false;
1178             }
1179             else
1180             {
1181               fontHeight = -8 + (int) h;
1182               s = ((float) fontHeight) / (float) ofontH;
1183               Font f = baseFont
1184                       .deriveFont(AffineTransform.getScaleInstance(s, s));
1185               g.setFont(f);
1186               fm = g.getFontMetrics();
1187               graphExtras = (aa[i].height - (groupSize * (fontHeight + 8)))
1188                       / 2;
1189             }
1190           }
1191           if (visible)
1192           {
1193             for (int gg = 0; gg < aa.length; gg++)
1194             {
1195               if (aa[gg].graphGroup == aa[i].graphGroup)
1196               {
1197                 x = width - fm.stringWidth(aa[gg].label) - 3;
1198                 g.drawString(aa[gg].label, x, y - graphExtras);
1199
1200                 if (aa[gg]._linecolour != null)
1201                 {
1202
1203                   g.setColor(aa[gg]._linecolour);
1204                   g.drawLine(x, y - graphExtras + 3,
1205                           x + fm.stringWidth(aa[gg].label),
1206                           y - graphExtras + 3);
1207                 }
1208
1209                 g.setColor(Color.black);
1210                 graphExtras += fontHeight + 8;
1211               }
1212             }
1213           }
1214           g.setFont(baseFont);
1215           fm = baseMetrics;
1216           fontHeight = ofontH;
1217         }
1218         else
1219         {
1220           if (vertBar)
1221           {
1222             g.drawLine(20, y + offset, 20, y - aa[i].height);
1223             g.drawLine(20, y + offset, x - 20, y + offset);
1224
1225           }
1226           g.drawString(label, x, y + offset);
1227         }
1228         lastSeqRef = aa[i].sequenceRef;
1229       }
1230     }
1231
1232     if (!resizePanel && dragEvent != null && aa != null)
1233     {
1234       g.setColor(Color.lightGray);
1235       g.drawString(
1236               (aa[selectedRow].sequenceRef == null ? ""
1237                       : aa[selectedRow].sequenceRef.getName())
1238                       + aa[selectedRow].label,
1239               dragEvent.getX(), dragEvent.getY() - getScrollOffset());
1240     }
1241
1242     if (!av.getWrapAlignment() && ((aa == null) || (aa.length < 1)))
1243     {
1244       g.drawString(MessageManager.getString("label.right_click"), 2, 8);
1245       g.drawString(MessageManager.getString("label.to_add_annotation"), 2,
1246               18);
1247     }
1248   }
1249
1250   public int getScrollOffset()
1251   {
1252     return scrollOffset;
1253   }
1254
1255   @Override
1256   public void mouseEntered(MouseEvent e)
1257   {
1258   }
1259 }