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