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