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